2 This file is part of GNUnet.
3 (C) 2009, 2010 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 2, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file fs/gnunet-service-fs.c
23 * @brief gnunet anonymity protocol implementation
24 * @author Christian Grothoff
27 * - TTL/priority calculations are absent!
29 * - have non-zero preference / priority for requests we initiate!
30 * - track stats for hot-path routing
31 * - implement hot-path routing decision procedure
32 * - implement: bound_priority, test_load_too_high, validate_nblock
33 * - add content migration support (store locally) [or create new service]
38 #include "gnunet_constants.h"
39 #include "gnunet_core_service.h"
40 #include "gnunet_datastore_service.h"
41 #include "gnunet_peer_lib.h"
42 #include "gnunet_protocols.h"
43 #include "gnunet_signatures.h"
44 #include "gnunet_statistics_service.h"
45 #include "gnunet_util_lib.h"
46 #include "gnunet-service-fs_drq.h"
47 #include "gnunet-service-fs_indexing.h"
50 #define DEBUG_FS GNUNET_YES
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,
670 if (NULL == pr->client_request_list)
672 GNUNET_STATISTICS_update (stats,
673 gettext_noop ("# P2P searches active"),
679 GNUNET_STATISTICS_update (stats,
680 gettext_noop ("# client searches active"),
684 /* might have already been removed from map in 'process_reply' (if
685 there was a unique reply) or never inserted if it was a
686 duplicate; hence ignore the return value here */
687 (void) GNUNET_CONTAINER_multihashmap_remove (query_request_map,
692 GNUNET_FS_drq_get_cancel (pr->drq);
695 if (pr->client_request_list != NULL)
697 GNUNET_CONTAINER_DLL_remove (pr->client_request_list->client_list->rl_head,
698 pr->client_request_list->client_list->rl_tail,
699 pr->client_request_list);
700 GNUNET_free (pr->client_request_list);
701 pr->client_request_list = NULL;
705 GNUNET_PEER_resolve (pr->cp->pid,
707 (void) GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
714 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
719 GNUNET_CORE_peer_change_preference_cancel (pr->irc);
722 if (pr->replies_seen != NULL)
724 GNUNET_free (pr->replies_seen);
725 pr->replies_seen = NULL;
727 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
729 GNUNET_SCHEDULER_cancel (sched,
731 pr->task = GNUNET_SCHEDULER_NO_TASK;
733 while (NULL != pr->pending_head)
734 destroy_pending_message_list_entry (pr->pending_head);
735 GNUNET_PEER_change_rc (pr->target_pid, -1);
736 if (pr->used_pids != NULL)
738 GNUNET_PEER_decrement_rcs (pr->used_pids, pr->used_pids_off);
739 GNUNET_free (pr->used_pids);
740 pr->used_pids_off = 0;
741 pr->used_pids_size = 0;
742 pr->used_pids = NULL;
749 * Method called whenever a given peer connects.
751 * @param cls closure, not used
752 * @param peer peer identity this notification is about
753 * @param latency reported latency of the connection with 'other'
754 * @param distance reported distance (DV) to 'other'
757 peer_connect_handler (void *cls,
759 GNUNET_PeerIdentity * peer,
760 struct GNUNET_TIME_Relative latency,
763 struct ConnectedPeer *cp;
765 cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
766 cp->pid = GNUNET_PEER_intern (peer);
767 GNUNET_CONTAINER_multihashmap_put (connected_peers,
770 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
775 * Free (each) request made by the peer.
777 * @param cls closure, points to peer that the request belongs to
778 * @param key current key code
779 * @param value value in the hash map
780 * @return GNUNET_YES (we should continue to iterate)
783 destroy_request (void *cls,
784 const GNUNET_HashCode * key,
787 const struct GNUNET_PeerIdentity * peer = cls;
788 struct PendingRequest *pr = value;
790 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
793 destroy_pending_request (pr);
799 * Method called whenever a peer disconnects.
801 * @param cls closure, not used
802 * @param peer peer identity this notification is about
805 peer_disconnect_handler (void *cls,
807 GNUNET_PeerIdentity * peer)
809 struct ConnectedPeer *cp;
810 struct PendingMessage *pm;
813 GNUNET_CONTAINER_multihashmap_get_multiple (peer_request_map,
817 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
821 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
823 if (NULL != cp->last_client_replies[i])
825 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
826 cp->last_client_replies[i] = NULL;
829 GNUNET_CONTAINER_multihashmap_remove (connected_peers,
832 GNUNET_PEER_change_rc (cp->pid, -1);
833 GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
835 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
836 while (NULL != (pm = cp->pending_messages_head))
837 destroy_pending_message (pm, 0 /* delivery failed */);
838 GNUNET_break (0 == cp->pending_requests);
844 * Iterator over hash map entries that removes all occurences
845 * of the given 'client' from the 'last_client_replies' of the
846 * given connected peer.
848 * @param cls closure, the 'struct GNUNET_SERVER_Client*' to remove
849 * @param key current key code (unused)
850 * @param value value in the hash map (the 'struct ConnectedPeer*' to change)
851 * @return GNUNET_YES (we should continue to iterate)
854 remove_client_from_last_client_replies (void *cls,
855 const GNUNET_HashCode * key,
858 struct GNUNET_SERVER_Client *client = cls;
859 struct ConnectedPeer *cp = value;
862 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
864 if (cp->last_client_replies[i] == client)
866 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
867 cp->last_client_replies[i] = NULL;
875 * A client disconnected. Remove all of its pending queries.
877 * @param cls closure, NULL
878 * @param client identification of the client
881 handle_client_disconnect (void *cls,
882 struct GNUNET_SERVER_Client
885 struct ClientList *pos;
886 struct ClientList *prev;
887 struct ClientRequestList *rcl;
888 struct ClientResponseMessage *creply;
894 while ( (NULL != pos) &&
895 (pos->client != client) )
901 return; /* no requests pending for this client */
902 while (NULL != (rcl = pos->rl_head))
904 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
905 "Destroying pending request `%s' on disconnect\n",
906 GNUNET_h2s (&rcl->req->query));
907 destroy_pending_request (rcl->req);
910 client_list = pos->next;
912 prev->next = pos->next;
915 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
918 while (NULL != (creply = pos->res_head))
920 GNUNET_CONTAINER_DLL_remove (pos->res_head,
923 GNUNET_free (creply);
925 GNUNET_SERVER_client_drop (pos->client);
927 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
928 &remove_client_from_last_client_replies,
934 * Iterator to free peer entries.
936 * @param cls closure, unused
937 * @param key current key code
938 * @param value value in the hash map (peer entry)
939 * @return GNUNET_YES (we should continue to iterate)
942 clean_peer (void *cls,
943 const GNUNET_HashCode * key,
946 peer_disconnect_handler (NULL, (const struct GNUNET_PeerIdentity*) key);
952 * Task run during shutdown.
958 shutdown_task (void *cls,
959 const struct GNUNET_SCHEDULER_TaskContext *tc)
961 while (client_list != NULL)
962 handle_client_disconnect (NULL,
963 client_list->client);
964 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
967 GNUNET_break (0 == GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap));
968 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
969 requests_by_expiration_heap = 0;
970 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
971 connected_peers = NULL;
972 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (query_request_map));
973 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
974 query_request_map = NULL;
975 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (peer_request_map));
976 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
977 peer_request_map = NULL;
978 GNUNET_assert (NULL != core);
979 GNUNET_CORE_disconnect (core);
983 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
991 /* ******************* Utility functions ******************** */
995 * Transmit the given message by copying it to the target buffer
996 * "buf". "buf" will be NULL and "size" zero if the socket was closed
997 * for writing in the meantime. In that case, do nothing
998 * (the disconnect or shutdown handler will take care of the rest).
999 * If we were able to transmit messages and there are still more
1000 * pending, ask core again for further calls to this function.
1002 * @param cls closure, pointer to the 'struct ConnectedPeer*'
1003 * @param size number of bytes available in buf
1004 * @param buf where the callee should write the message
1005 * @return number of bytes written to buf
1008 transmit_to_peer (void *cls,
1009 size_t size, void *buf)
1011 struct ConnectedPeer *cp = cls;
1013 struct GNUNET_PeerIdentity pid;
1014 struct PendingMessage *pm;
1021 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1022 "Dropping message, core too busy.\n");
1027 while ( (NULL != (pm = cp->pending_messages_head) ) &&
1028 (pm->msize <= size) )
1030 memcpy (&cbuf[msize], &pm[1], pm->msize);
1033 destroy_pending_message (pm, cp->pid);
1037 GNUNET_PEER_resolve (cp->pid,
1039 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1041 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1048 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1049 "Transmitting %u bytes to peer %u.\n",
1058 * Add a message to the set of pending messages for the given peer.
1060 * @param cp peer to send message to
1061 * @param pm message to queue
1062 * @param pr request on which behalf this message is being queued
1065 add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
1066 struct PendingMessage *pm,
1067 struct PendingRequest *pr)
1069 struct PendingMessage *pos;
1070 struct PendingMessageList *pml;
1071 struct GNUNET_PeerIdentity pid;
1073 GNUNET_assert (pm->next == NULL);
1074 GNUNET_assert (pm->pml == NULL);
1075 pml = GNUNET_malloc (sizeof (struct PendingMessageList));
1080 GNUNET_CONTAINER_DLL_insert (pr->pending_head,
1083 pos = cp->pending_messages_head;
1084 while ( (pos != NULL) &&
1085 (pm->priority < pos->priority) )
1087 GNUNET_CONTAINER_DLL_insert_after (cp->pending_messages_head,
1088 cp->pending_messages_tail,
1091 cp->pending_requests++;
1092 if (cp->pending_requests > MAX_QUEUE_PER_PEER)
1093 destroy_pending_message (cp->pending_messages_tail, 0);
1094 if (cp->cth == NULL)
1096 /* need to schedule transmission */
1097 GNUNET_PEER_resolve (cp->pid, &pid);
1098 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1099 cp->pending_messages_head->priority,
1102 cp->pending_messages_head->msize,
1106 if (cp->cth == NULL)
1109 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1110 "Failed to schedule transmission with core!\n");
1112 /* FIXME: call stats (rare, bad case) */
1118 * Mingle hash with the mingle_number to produce different bits.
1121 mingle_hash (const GNUNET_HashCode * in,
1122 int32_t mingle_number,
1123 GNUNET_HashCode * hc)
1127 GNUNET_CRYPTO_hash (&mingle_number,
1130 GNUNET_CRYPTO_hash_xor (&m, in, hc);
1135 * Test if the load on this peer is too high
1136 * to even consider processing the query at
1139 * @return GNUNET_YES if the load is too high, GNUNET_NO otherwise
1142 test_load_too_high ()
1144 return GNUNET_NO; // FIXME
1148 /* ******************* Pending Request Refresh Task ******************** */
1153 * We use a random delay to make the timing of requests less
1154 * predictable. This function returns such a random delay. We add a base
1155 * delay of MAX_CORK_DELAY (1s).
1157 * FIXME: make schedule dependent on the specifics of the request?
1158 * Or bandwidth and number of connected peers and load?
1160 * @return random delay to use for some request, between 1s and 1000+TTL_DECREMENT ms
1162 static struct GNUNET_TIME_Relative
1163 get_processing_delay ()
1166 GNUNET_TIME_relative_add (GNUNET_CONSTANTS_MAX_CORK_DELAY,
1167 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1168 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1174 * We're processing a GET request from another peer and have decided
1175 * to forward it to other peers. This function is called periodically
1176 * and should forward the request to other peers until we have all
1177 * possible replies. If we have transmitted the *only* reply to
1178 * the initiator we should destroy the pending request. If we have
1179 * many replies in the queue to the initiator, we should delay sending
1180 * out more queries until the reply queue has shrunk some.
1182 * @param cls our "struct ProcessGetContext *"
1186 forward_request_task (void *cls,
1187 const struct GNUNET_SCHEDULER_TaskContext *tc);
1191 * Function called after we either failed or succeeded
1192 * at transmitting a query to a peer.
1194 * @param cls the requests "struct PendingRequest*"
1195 * @param tpid ID of receiving peer, 0 on transmission error
1198 transmit_query_continuation (void *cls,
1199 GNUNET_PEER_Id tpid)
1201 struct PendingRequest *pr = cls;
1203 GNUNET_STATISTICS_update (stats,
1204 gettext_noop ("# queries scheduled for forwarding"),
1210 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1211 "Transmission of request failed, will try again later.\n");
1213 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1214 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1215 get_processing_delay (),
1216 &forward_request_task,
1220 GNUNET_STATISTICS_update (stats,
1221 gettext_noop ("# queries forwarded"),
1224 GNUNET_PEER_change_rc (tpid, 1);
1225 if (pr->used_pids_off == pr->used_pids_size)
1226 GNUNET_array_grow (pr->used_pids,
1228 pr->used_pids_size * 2 + 2);
1229 pr->used_pids[pr->used_pids_off++] = tpid;
1230 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1231 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1232 get_processing_delay (),
1233 &forward_request_task,
1239 * How many bytes should a bloomfilter be if we have already seen
1240 * entry_count responses? Note that BLOOMFILTER_K gives us the number
1241 * of bits set per entry. Furthermore, we should not re-size the
1242 * filter too often (to keep it cheap).
1244 * Since other peers will also add entries but not resize the filter,
1245 * we should generally pick a slightly larger size than what the
1246 * strict math would suggest.
1248 * @return must be a power of two and smaller or equal to 2^15.
1251 compute_bloomfilter_size (unsigned int entry_count)
1254 unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
1255 uint16_t max = 1 << 15;
1257 if (entry_count > max)
1260 while ((size < max) && (size < ideal))
1269 * Recalculate our bloom filter for filtering replies. This function
1270 * will create a new bloom filter from scratch, so it should only be
1271 * called if we have no bloomfilter at all (and hence can create a
1272 * fresh one of minimal size without problems) OR if our peer is the
1273 * initiator (in which case we may resize to larger than mimimum size).
1275 * @param pr request for which the BF is to be recomputed
1278 refresh_bloomfilter (struct PendingRequest *pr)
1282 GNUNET_HashCode mhash;
1284 nsize = compute_bloomfilter_size (pr->replies_seen_off);
1285 if (nsize == pr->bf_size)
1286 return; /* size not changed */
1288 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
1289 pr->bf_size = nsize;
1290 pr->mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
1291 pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1294 for (i=0;i<pr->replies_seen_off;i++)
1296 mingle_hash (&pr->replies_seen[i], pr->mingle, &mhash);
1297 GNUNET_CONTAINER_bloomfilter_add (pr->bf, &mhash);
1303 * Function called after we've tried to reserve a certain amount of
1304 * bandwidth for a reply. Check if we succeeded and if so send our
1307 * @param cls the requests "struct PendingRequest*"
1308 * @param peer identifies the peer
1309 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1310 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1311 * @param amount set to the amount that was actually reserved or unreserved
1312 * @param preference current traffic preference for the given peer
1315 target_reservation_cb (void *cls,
1317 GNUNET_PeerIdentity * peer,
1318 struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
1319 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1321 uint64_t preference)
1323 struct PendingRequest *pr = cls;
1324 struct ConnectedPeer *cp;
1325 struct PendingMessage *pm;
1326 struct GetMessage *gm;
1327 GNUNET_HashCode *ext;
1337 /* error in communication with core, try again later */
1338 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1339 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1340 get_processing_delay (),
1341 &forward_request_task,
1345 // (3) transmit, update ttl/priority
1346 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1350 /* Peer must have just left */
1352 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1353 "Selected peer disconnected!\n");
1355 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1356 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1357 get_processing_delay (),
1358 &forward_request_task,
1362 no_route = GNUNET_NO;
1363 /* FIXME: check against DBLOCK_SIZE and possibly return
1364 amount to reserve; however, this also needs to work
1365 with testcases which currently start out with a far
1366 too low per-peer bw limit, so they would never send
1367 anything. Big issue. */
1373 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1374 "Failed to reserve bandwidth for reply (got %d/%u bytes only)!\n",
1378 GNUNET_STATISTICS_update (stats,
1379 gettext_noop ("# reply bandwidth reservation requests failed"),
1382 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1383 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1384 get_processing_delay (),
1385 &forward_request_task,
1387 return; /* this target round failed */
1389 /* FIXME: if we are "quite" busy, we may still want to skip
1390 this round; need more load detection code! */
1391 no_route = GNUNET_YES;
1394 GNUNET_STATISTICS_update (stats,
1395 gettext_noop ("# queries scheduled for forwarding"),
1398 /* build message and insert message into priority queue */
1400 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1401 "Forwarding request `%s' to `%4s'!\n",
1402 GNUNET_h2s (&pr->query),
1407 if (GNUNET_YES == no_route)
1409 bm |= GET_MESSAGE_BIT_RETURN_TO;
1412 if (pr->namespace != NULL)
1414 bm |= GET_MESSAGE_BIT_SKS_NAMESPACE;
1417 if (pr->target_pid != 0)
1419 bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
1422 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
1423 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1424 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1426 gm = (struct GetMessage*) &pm[1];
1427 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
1428 gm->header.size = htons (msize);
1429 gm->type = htonl (pr->type);
1430 pr->remaining_priority /= 2;
1431 gm->priority = htonl (pr->remaining_priority);
1432 gm->ttl = htonl (pr->ttl);
1433 gm->filter_mutator = htonl(pr->mingle);
1434 gm->hash_bitmap = htonl (bm);
1435 gm->query = pr->query;
1436 ext = (GNUNET_HashCode*) &gm[1];
1438 if (GNUNET_YES == no_route)
1439 GNUNET_PEER_resolve (pr->cp->pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1440 if (pr->namespace != NULL)
1441 memcpy (&ext[k++], pr->namespace, sizeof (GNUNET_HashCode));
1442 if (pr->target_pid != 0)
1443 GNUNET_PEER_resolve (pr->target_pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1444 bfdata = (char *) &ext[k];
1446 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
1449 pm->cont = &transmit_query_continuation;
1451 add_to_pending_messages_for_peer (cp, pm, pr);
1456 * Closure used for "target_peer_select_cb".
1458 struct PeerSelectionContext
1461 * The request for which we are selecting
1464 struct PendingRequest *pr;
1467 * Current "prime" target.
1469 struct GNUNET_PeerIdentity target;
1472 * How much do we like this target?
1474 double target_score;
1480 * Function called for each connected peer to determine
1481 * which one(s) would make good targets for forwarding.
1483 * @param cls closure (struct PeerSelectionContext)
1484 * @param key current key code (peer identity)
1485 * @param value value in the hash map (struct ConnectedPeer)
1486 * @return GNUNET_YES if we should continue to
1491 target_peer_select_cb (void *cls,
1492 const GNUNET_HashCode * key,
1495 struct PeerSelectionContext *psc = cls;
1496 struct ConnectedPeer *cp = value;
1497 struct PendingRequest *pr = psc->pr;
1502 /* 1) check that this peer is not the initiator */
1504 return GNUNET_YES; /* skip */
1506 /* 2) 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 // 3) 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,
1637 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1638 "Trying query `%s' with priority %u and TTL %d.\n",
1639 GNUNET_h2s (&pr->query),
1646 /* FIXME: should we do something here as well!? */
1649 /* (3) reserve reply bandwidth */
1650 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1651 &psc.target.hashPubKey);
1652 GNUNET_assert (NULL != cp);
1653 pr->irc = GNUNET_CORE_peer_change_preference (sched, cfg,
1655 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1656 GNUNET_BANDWIDTH_value_init ((uint32_t) -1 /* no limit */),
1658 (uint64_t) cp->inc_preference,
1659 &target_reservation_cb,
1661 cp->inc_preference = 0.0;
1665 /* **************************** P2P PUT Handling ************************ */
1669 * Function called after we either failed or succeeded
1670 * at transmitting a reply to a peer.
1672 * @param cls the requests "struct PendingRequest*"
1673 * @param tpid ID of receiving peer, 0 on transmission error
1676 transmit_reply_continuation (void *cls,
1677 GNUNET_PEER_Id tpid)
1679 struct PendingRequest *pr = cls;
1683 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1684 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1685 /* only one reply expected, done with the request! */
1686 destroy_pending_request (pr);
1688 case GNUNET_DATASTORE_BLOCKTYPE_ANY:
1689 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1690 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1700 * Check if the given KBlock is well-formed.
1702 * @param kb the kblock data (or at least "dsize" bytes claiming to be one)
1703 * @param dsize size of "kb" in bytes; check for < sizeof(struct KBlock)!
1704 * @param query where to store the query that this block answers
1705 * @return GNUNET_OK if this is actually a well-formed KBlock
1708 check_kblock (const struct KBlock *kb,
1710 GNUNET_HashCode *query)
1712 if (dsize < sizeof (struct KBlock))
1714 GNUNET_break_op (0);
1715 return GNUNET_SYSERR;
1717 if (dsize - sizeof (struct KBlock) !=
1718 ntohl (kb->purpose.size)
1719 - sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose)
1720 - sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) )
1722 GNUNET_break_op (0);
1723 return GNUNET_SYSERR;
1726 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_KBLOCK,
1731 GNUNET_break_op (0);
1732 return GNUNET_SYSERR;
1735 GNUNET_CRYPTO_hash (&kb->keyspace,
1736 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1743 * Check if the given NBlock is well-formed.
1745 * @param nb the nblock data (or at least "dsize" bytes claiming to be one)
1746 * @param dsize size of "nb" in bytes; check for < sizeof(struct NBlock)!
1747 * @param query where to store the query that this block answers
1748 * @return GNUNET_OK if this is actually a well-formed NBlock
1751 check_nblock (const struct NBlock *nb,
1753 GNUNET_HashCode *query)
1755 if (dsize < sizeof (struct NBlock))
1757 GNUNET_break_op (0);
1758 return GNUNET_SYSERR;
1760 if (dsize - sizeof (struct NBlock) !=
1761 ntohl (nb->ns_purpose.size)
1762 - sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose)
1763 - sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) )
1765 GNUNET_break_op (0);
1766 return GNUNET_SYSERR;
1769 ntohl (nb->ksk_purpose.size) + sizeof (struct GNUNET_CRYPTO_RsaSignature))
1771 GNUNET_break_op (0);
1772 return GNUNET_SYSERR;
1775 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_NBLOCK_KSIG,
1780 GNUNET_break_op (0);
1781 return GNUNET_SYSERR;
1784 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_NBLOCK,
1789 GNUNET_break_op (0);
1790 return GNUNET_SYSERR;
1793 GNUNET_CRYPTO_hash (&nb->keyspace,
1794 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1801 * Check if the given SBlock is well-formed.
1803 * @param sb the sblock data (or at least "dsize" bytes claiming to be one)
1804 * @param dsize size of "kb" in bytes; check for < sizeof(struct SBlock)!
1805 * @param query where to store the query that this block answers
1806 * @param namespace where to store the namespace that this block belongs to
1807 * @return GNUNET_OK if this is actually a well-formed SBlock
1810 check_sblock (const struct SBlock *sb,
1812 GNUNET_HashCode *query,
1813 GNUNET_HashCode *namespace)
1815 if (dsize < sizeof (struct SBlock))
1817 GNUNET_break_op (0);
1818 return GNUNET_SYSERR;
1821 ntohl (sb->purpose.size) + sizeof (struct GNUNET_CRYPTO_RsaSignature))
1823 GNUNET_break_op (0);
1824 return GNUNET_SYSERR;
1827 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_SBLOCK,
1832 GNUNET_break_op (0);
1833 return GNUNET_SYSERR;
1836 *query = sb->identifier;
1837 if (namespace != NULL)
1838 GNUNET_CRYPTO_hash (&sb->subspace,
1839 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1846 * Transmit the given message by copying it to the target buffer
1847 * "buf". "buf" will be NULL and "size" zero if the socket was closed
1848 * for writing in the meantime. In that case, do nothing
1849 * (the disconnect or shutdown handler will take care of the rest).
1850 * If we were able to transmit messages and there are still more
1851 * pending, ask core again for further calls to this function.
1853 * @param cls closure, pointer to the 'struct ClientList*'
1854 * @param size number of bytes available in buf
1855 * @param buf where the callee should write the message
1856 * @return number of bytes written to buf
1859 transmit_to_client (void *cls,
1860 size_t size, void *buf)
1862 struct ClientList *cl = cls;
1864 struct ClientResponseMessage *creply;
1871 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1872 "Not sending reply, client communication problem.\n");
1877 while ( (NULL != (creply = cl->res_head) ) &&
1878 (creply->msize <= size) )
1880 memcpy (&cbuf[msize], &creply[1], creply->msize);
1881 msize += creply->msize;
1882 size -= creply->msize;
1883 GNUNET_CONTAINER_DLL_remove (cl->res_head,
1886 GNUNET_free (creply);
1889 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
1891 GNUNET_TIME_UNIT_FOREVER_REL,
1892 &transmit_to_client,
1895 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1896 "Transmitted %u bytes to client\n",
1897 (unsigned int) msize);
1904 * Closure for "process_reply" function.
1906 struct ProcessReplyClosure
1909 * The data for the reply.
1913 // FIXME: add 'struct ConnectedPeer' to track 'last_xxx_replies' here!
1916 * When the reply expires.
1918 struct GNUNET_TIME_Absolute expiration;
1926 * Namespace that this reply belongs to
1927 * (if it is of type SBLOCK).
1929 GNUNET_HashCode namespace;
1932 * Type of the block.
1937 * How much was this reply worth to us?
1944 * We have received a reply; handle it!
1946 * @param cls response (struct ProcessReplyClosure)
1947 * @param key our query
1948 * @param value value in the hash map (info about the query)
1949 * @return GNUNET_YES (we should continue to iterate)
1952 process_reply (void *cls,
1953 const GNUNET_HashCode * key,
1956 struct ProcessReplyClosure *prq = cls;
1957 struct PendingRequest *pr = value;
1958 struct PendingMessage *reply;
1959 struct ClientResponseMessage *creply;
1960 struct ClientList *cl;
1961 struct PutMessage *pm;
1962 struct ConnectedPeer *cp;
1963 GNUNET_HashCode chash;
1964 GNUNET_HashCode mhash;
1968 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1969 "Matched result (type %u) for query `%s' with pending request\n",
1970 (unsigned int) prq->type,
1973 GNUNET_STATISTICS_update (stats,
1974 gettext_noop ("# replies received and matched"),
1977 GNUNET_CRYPTO_hash (prq->data,
1982 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1983 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1984 /* only possible reply, stop requesting! */
1985 while (NULL != pr->pending_head)
1986 destroy_pending_message_list_entry (pr->pending_head);
1987 if (pr->drq != NULL)
1989 if (pr->client_request_list != NULL)
1990 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
1992 GNUNET_FS_drq_get_cancel (pr->drq);
1995 pr->do_remove = GNUNET_YES;
1996 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
1998 GNUNET_SCHEDULER_cancel (sched,
2000 pr->task = GNUNET_SCHEDULER_NO_TASK;
2002 GNUNET_break (GNUNET_YES ==
2003 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
2007 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2008 if (pr->namespace == NULL)
2013 if (0 != memcmp (pr->namespace,
2015 sizeof (GNUNET_HashCode)))
2017 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2018 _("Reply mismatched in terms of namespace. Discarded.\n"));
2019 return GNUNET_YES; /* wrong namespace */
2021 /* then: fall-through! */
2022 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
2023 case GNUNET_DATASTORE_BLOCKTYPE_NBLOCK:
2026 mingle_hash (&chash, pr->mingle, &mhash);
2027 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
2030 GNUNET_STATISTICS_update (stats,
2031 gettext_noop ("# duplicate replies discarded (bloomfilter)"),
2035 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2036 "Duplicate response `%s', discarding.\n",
2037 GNUNET_h2s (&mhash));
2039 return GNUNET_YES; /* duplicate */
2042 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2043 "New response `%s', adding to filter.\n",
2044 GNUNET_h2s (&mhash));
2047 if (pr->client_request_list != NULL)
2049 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);
2053 pr->replies_seen[pr->replies_seen_off++] = chash;
2055 if ( (pr->bf == NULL) ||
2056 (pr->client_request_list != NULL) )
2057 refresh_bloomfilter (pr);
2058 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
2065 prq->priority += pr->remaining_priority;
2066 pr->remaining_priority = 0;
2067 if (pr->client_request_list != NULL)
2069 GNUNET_STATISTICS_update (stats,
2070 gettext_noop ("# replies received for local clients"),
2073 cl = pr->client_request_list->client_list;
2074 msize = sizeof (struct PutMessage) + prq->size;
2075 creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
2076 creply->msize = msize;
2077 creply->client_list = cl;
2078 GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
2082 pm = (struct PutMessage*) &creply[1];
2083 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2084 pm->header.size = htons (msize);
2085 pm->type = htonl (prq->type);
2086 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
2087 memcpy (&pm[1], prq->data, prq->size);
2091 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2092 "Transmitting result for query `%s' to client\n",
2095 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
2097 GNUNET_TIME_UNIT_FOREVER_REL,
2098 &transmit_to_client,
2101 GNUNET_break (cl->th != NULL);
2103 destroy_pending_request (pr);
2109 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2110 "Transmitting result for query `%s' to other peer (PID=%u)\n",
2112 (unsigned int) cp->pid);
2114 GNUNET_STATISTICS_update (stats,
2115 gettext_noop ("# replies received for other peers"),
2118 msize = sizeof (struct PutMessage) + prq->size;
2119 reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
2120 reply->cont = &transmit_reply_continuation;
2121 reply->cont_cls = pr;
2122 reply->msize = msize;
2123 reply->priority = (uint32_t) -1; /* send replies first! */
2124 pm = (struct PutMessage*) &reply[1];
2125 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2126 pm->header.size = htons (msize);
2127 pm->type = htonl (prq->type);
2128 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
2129 memcpy (&pm[1], prq->data, prq->size);
2130 add_to_pending_messages_for_peer (cp, reply, pr);
2132 // FIXME: implement hot-path routing statistics keeping!
2138 * Handle P2P "PUT" message.
2140 * @param cls closure, always NULL
2141 * @param other the other peer involved (sender or receiver, NULL
2142 * for loopback messages where we are both sender and receiver)
2143 * @param message the actual message
2144 * @param latency reported latency of the connection with 'other'
2145 * @param distance reported distance (DV) to 'other'
2146 * @return GNUNET_OK to keep the connection open,
2147 * GNUNET_SYSERR to close it (signal serious error)
2150 handle_p2p_put (void *cls,
2151 const struct GNUNET_PeerIdentity *other,
2152 const struct GNUNET_MessageHeader *message,
2153 struct GNUNET_TIME_Relative latency,
2156 const struct PutMessage *put;
2160 struct GNUNET_TIME_Absolute expiration;
2161 GNUNET_HashCode query;
2162 struct ProcessReplyClosure prq;
2164 msize = ntohs (message->size);
2165 if (msize < sizeof (struct PutMessage))
2168 return GNUNET_SYSERR;
2170 put = (const struct PutMessage*) message;
2171 dsize = msize - sizeof (struct PutMessage);
2172 type = ntohl (put->type);
2173 expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
2175 /* first, validate! */
2178 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2179 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2180 GNUNET_CRYPTO_hash (&put[1], dsize, &query);
2182 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
2184 check_kblock ((const struct KBlock*) &put[1],
2187 return GNUNET_SYSERR;
2189 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2191 check_sblock ((const struct SBlock*) &put[1],
2195 return GNUNET_SYSERR;
2197 case GNUNET_DATASTORE_BLOCKTYPE_NBLOCK:
2199 check_nblock ((const struct NBlock*) &put[1],
2202 return GNUNET_SYSERR;
2205 /* unknown block type */
2206 GNUNET_break_op (0);
2207 return GNUNET_SYSERR;
2211 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2212 "Received result for query `%s' from peer `%4s'\n",
2213 GNUNET_h2s (&query),
2214 GNUNET_i2s (other));
2216 GNUNET_STATISTICS_update (stats,
2217 gettext_noop ("# replies received (overall)"),
2220 /* now, lookup 'query' */
2221 prq.data = (const void*) &put[1];
2224 prq.expiration = expiration;
2226 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2230 // FIXME: if migration is on and load is low,
2231 // queue to store data in datastore;
2232 // use "prq.priority" for that!
2237 /* **************************** P2P GET Handling ************************ */
2241 * Closure for 'check_duplicate_request_{peer,client}'.
2243 struct CheckDuplicateRequestClosure
2246 * The new request we should check if it already exists.
2248 const struct PendingRequest *pr;
2251 * Existing request found by the checker, NULL if none.
2253 struct PendingRequest *have;
2258 * Iterator over entries in the 'query_request_map' that
2259 * tries to see if we have the same request pending from
2260 * the same client already.
2262 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
2263 * @param key current key code (query, ignored, must match)
2264 * @param value value in the hash map (a 'struct PendingRequest'
2265 * that already exists)
2266 * @return GNUNET_YES if we should continue to
2267 * iterate (no match yet)
2268 * GNUNET_NO if not (match found).
2271 check_duplicate_request_client (void *cls,
2272 const GNUNET_HashCode * key,
2275 struct CheckDuplicateRequestClosure *cdc = cls;
2276 struct PendingRequest *have = value;
2278 if (have->client_request_list == NULL)
2280 if ( (cdc->pr->client_request_list->client_list->client == have->client_request_list->client_list->client) &&
2291 * We're processing (local) results for a search request
2292 * from another peer. Pass applicable results to the
2293 * peer and if we are done either clean up (operation
2294 * complete) or forward to other peers (more results possible).
2296 * @param cls our closure (struct LocalGetContext)
2297 * @param key key for the content
2298 * @param size number of bytes in data
2299 * @param data content stored
2300 * @param type type of the content
2301 * @param priority priority of the content
2302 * @param anonymity anonymity-level for the content
2303 * @param expiration expiration time for the content
2304 * @param uid unique identifier for the datum;
2305 * maybe 0 if no unique identifier is available
2308 process_local_reply (void *cls,
2309 const GNUNET_HashCode * key,
2315 struct GNUNET_TIME_Absolute
2319 struct PendingRequest *pr = cls;
2320 struct ProcessReplyClosure prq;
2321 struct CheckDuplicateRequestClosure cdrc;
2322 GNUNET_HashCode dhash;
2323 GNUNET_HashCode mhash;
2324 GNUNET_HashCode query;
2329 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2330 "Done processing local replies, forwarding request to other peers.\n");
2333 if (pr->client_request_list != NULL)
2335 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
2337 /* Figure out if this is a duplicate request and possibly
2338 merge 'struct PendingRequest' entries */
2341 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2343 &check_duplicate_request_client,
2345 if (cdrc.have != NULL)
2348 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2349 "Received request for block `%s' twice from client, will only request once.\n",
2350 GNUNET_h2s (&pr->query));
2353 destroy_pending_request (pr);
2358 /* no more results */
2359 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2360 pr->task = GNUNET_SCHEDULER_add_now (sched,
2361 &forward_request_task,
2366 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2367 "New local response to `%s' of type %u.\n",
2371 if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
2374 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2375 "Found ONDEMAND block, performing on-demand encoding\n");
2377 GNUNET_STATISTICS_update (stats,
2378 gettext_noop ("# on-demand blocks matched requests"),
2382 GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
2383 anonymity, expiration, uid,
2384 &process_local_reply,
2386 GNUNET_FS_drq_get_next (GNUNET_YES);
2389 /* check for duplicates */
2390 GNUNET_CRYPTO_hash (data, size, &dhash);
2391 mingle_hash (&dhash,
2394 if ( (pr->bf != NULL) &&
2396 GNUNET_CONTAINER_bloomfilter_test (pr->bf,
2400 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2401 "Result from datastore filtered by bloomfilter (duplicate).\n");
2403 GNUNET_STATISTICS_update (stats,
2404 gettext_noop ("# results filtered by query bloomfilter"),
2407 GNUNET_FS_drq_get_next (GNUNET_YES);
2411 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2412 "Found result for query `%s' in local datastore\n",
2415 GNUNET_STATISTICS_update (stats,
2416 gettext_noop ("# results found locally"),
2419 pr->results_found++;
2420 memset (&prq, 0, sizeof (prq));
2422 prq.expiration = expiration;
2424 if ( (type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) &&
2425 (GNUNET_OK != check_sblock ((const struct SBlock*) data,
2431 /* FIXME: consider removing the block? */
2432 GNUNET_FS_drq_get_next (GNUNET_YES);
2436 prq.priority = priority;
2437 process_reply (&prq, key, pr);
2439 if ( (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK) ||
2440 (type == GNUNET_DATASTORE_BLOCKTYPE_IBLOCK) )
2442 GNUNET_FS_drq_get_next (GNUNET_NO);
2445 if ( (pr->client_request_list == NULL) &&
2446 ( (GNUNET_YES == test_load_too_high()) ||
2447 (pr->results_found > 5 + 2 * pr->priority) ) )
2450 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2451 "Load too high, done with request\n");
2453 GNUNET_STATISTICS_update (stats,
2454 gettext_noop ("# processing result set cut short due to load"),
2457 GNUNET_FS_drq_get_next (GNUNET_NO);
2460 GNUNET_FS_drq_get_next (GNUNET_YES);
2465 * We've received a request with the specified priority. Bound it
2466 * according to how much we trust the given peer.
2468 * @param prio_in requested priority
2469 * @param cp the peer making the request
2470 * @return effective priority
2473 bound_priority (uint32_t prio_in,
2474 struct ConnectedPeer *cp)
2481 * Iterator over entries in the 'query_request_map' that
2482 * tries to see if we have the same request pending from
2483 * the same peer already.
2485 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
2486 * @param key current key code (query, ignored, must match)
2487 * @param value value in the hash map (a 'struct PendingRequest'
2488 * that already exists)
2489 * @return GNUNET_YES if we should continue to
2490 * iterate (no match yet)
2491 * GNUNET_NO if not (match found).
2494 check_duplicate_request_peer (void *cls,
2495 const GNUNET_HashCode * key,
2498 struct CheckDuplicateRequestClosure *cdc = cls;
2499 struct PendingRequest *have = value;
2501 if (cdc->pr->target_pid == have->target_pid)
2511 * Handle P2P "GET" request.
2513 * @param cls closure, always NULL
2514 * @param other the other peer involved (sender or receiver, NULL
2515 * for loopback messages where we are both sender and receiver)
2516 * @param message the actual message
2517 * @param latency reported latency of the connection with 'other'
2518 * @param distance reported distance (DV) to 'other'
2519 * @return GNUNET_OK to keep the connection open,
2520 * GNUNET_SYSERR to close it (signal serious error)
2523 handle_p2p_get (void *cls,
2524 const struct GNUNET_PeerIdentity *other,
2525 const struct GNUNET_MessageHeader *message,
2526 struct GNUNET_TIME_Relative latency,
2529 struct PendingRequest *pr;
2530 struct ConnectedPeer *cp;
2531 struct ConnectedPeer *cps;
2532 struct CheckDuplicateRequestClosure cdc;
2533 struct GNUNET_TIME_Relative timeout;
2535 const struct GetMessage *gm;
2537 const GNUNET_HashCode *opt;
2540 uint32_t ttl_decrement;
2545 msize = ntohs(message->size);
2546 if (msize < sizeof (struct GetMessage))
2548 GNUNET_break_op (0);
2549 return GNUNET_SYSERR;
2551 gm = (const struct GetMessage*) message;
2552 type = ntohl (gm->type);
2555 case GNUNET_DATASTORE_BLOCKTYPE_ANY:
2556 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2557 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2558 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
2559 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2562 GNUNET_break_op (0);
2563 return GNUNET_SYSERR;
2565 bm = ntohl (gm->hash_bitmap);
2573 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
2575 GNUNET_break_op (0);
2576 return GNUNET_SYSERR;
2578 opt = (const GNUNET_HashCode*) &gm[1];
2579 bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
2580 bm = ntohl (gm->hash_bitmap);
2581 if ( (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)) &&
2582 (type != GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) )
2584 GNUNET_break_op (0);
2585 return GNUNET_SYSERR;
2588 cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2589 &other->hashPubKey);
2592 /* peer must have just disconnected */
2593 GNUNET_STATISTICS_update (stats,
2594 gettext_noop ("# requests dropped due to initiator not being connected"),
2597 return GNUNET_SYSERR;
2599 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
2600 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2607 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
2608 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2609 "Failed to find RETURN-TO peer `%4s' in connection set. Dropping query.\n",
2610 GNUNET_i2s ((const struct GNUNET_PeerIdentity*) &opt[bits-1]));
2613 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2614 "Failed to find peer `%4s' in connection set. Dropping query.\n",
2615 GNUNET_i2s (other));
2617 GNUNET_STATISTICS_update (stats,
2618 gettext_noop ("# requests dropped due to missing reverse route"),
2621 /* FIXME: try connect? */
2624 /* note that we can really only check load here since otherwise
2625 peers could find out that we are overloaded by not being
2626 disconnected after sending us a malformed query... */
2627 if (GNUNET_YES == test_load_too_high ())
2630 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2631 "Dropping query from `%s', this peer is too busy.\n",
2632 GNUNET_i2s (other));
2634 GNUNET_STATISTICS_update (stats,
2635 gettext_noop ("# requests dropped due to high load"),
2642 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2643 "Received request for `%s' of type %u from peer `%4s' with flags %u\n",
2644 GNUNET_h2s (&gm->query),
2645 (unsigned int) type,
2649 have_ns = (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE));
2650 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
2651 (have_ns ? sizeof(GNUNET_HashCode) : 0));
2653 pr->namespace = (GNUNET_HashCode*) &pr[1];
2655 pr->mingle = ntohl (gm->filter_mutator);
2656 if (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2657 memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
2658 if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
2659 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
2661 pr->anonymity_level = 1;
2662 pr->priority = bound_priority (ntohl (gm->priority), cps);
2663 pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
2664 pr->query = gm->query;
2665 /* decrement ttl (always) */
2666 ttl_decrement = 2 * TTL_DECREMENT +
2667 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2669 if ( (pr->ttl < 0) &&
2670 (((int32_t)(pr->ttl - ttl_decrement)) > 0) )
2673 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2674 "Dropping query from `%s' due to TTL underflow (%d - %u).\n",
2679 GNUNET_STATISTICS_update (stats,
2680 gettext_noop ("# requests dropped due TTL underflow"),
2683 /* integer underflow => drop (should be very rare)! */
2687 pr->ttl -= ttl_decrement;
2688 pr->start_time = GNUNET_TIME_absolute_get ();
2690 /* get bloom filter */
2693 pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
2696 pr->bf_size = bfsize;
2701 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2703 &check_duplicate_request_peer,
2705 if (cdc.have != NULL)
2707 if (cdc.have->start_time.value + cdc.have->ttl >=
2708 pr->start_time.value + pr->ttl)
2710 /* existing request has higher TTL, drop new one! */
2711 cdc.have->priority += pr->priority;
2712 destroy_pending_request (pr);
2714 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2715 "Have existing request with higher TTL, dropping new request.\n",
2716 GNUNET_i2s (other));
2718 GNUNET_STATISTICS_update (stats,
2719 gettext_noop ("# requests dropped due to higher-TTL request"),
2726 /* existing request has lower TTL, drop old one! */
2727 pr->priority += cdc.have->priority;
2728 /* Possible optimization: if we have applicable pending
2729 replies in 'cdc.have', we might want to move those over
2730 (this is a really rare special-case, so it is not clear
2731 that this would be worth it) */
2732 destroy_pending_request (cdc.have);
2733 /* keep processing 'pr'! */
2738 GNUNET_CONTAINER_multihashmap_put (query_request_map,
2741 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2742 GNUNET_CONTAINER_multihashmap_put (peer_request_map,
2745 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2747 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
2749 pr->start_time.value + pr->ttl);
2751 GNUNET_STATISTICS_update (stats,
2752 gettext_noop ("# P2P searches received"),
2755 GNUNET_STATISTICS_update (stats,
2756 gettext_noop ("# P2P searches active"),
2760 /* calculate change in traffic preference */
2761 preference = (double) pr->priority;
2762 if (preference < QUERY_BANDWIDTH_VALUE)
2763 preference = QUERY_BANDWIDTH_VALUE;
2764 cps->inc_preference += preference;
2766 /* process locally */
2767 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2768 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2769 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
2770 (pr->priority + 1));
2771 pr->drq = GNUNET_FS_drq_get (&gm->query,
2773 &process_local_reply,
2778 /* Are multiple results possible? If so, start processing remotely now! */
2781 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2782 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2783 /* only one result, wait for datastore */
2786 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2787 pr->task = GNUNET_SCHEDULER_add_now (sched,
2788 &forward_request_task,
2792 /* make sure we don't track too many requests */
2793 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
2795 pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
2796 destroy_pending_request (pr);
2802 /* **************************** CS GET Handling ************************ */
2806 * Handle START_SEARCH-message (search request from client).
2808 * @param cls closure
2809 * @param client identification of the client
2810 * @param message the actual message
2813 handle_start_search (void *cls,
2814 struct GNUNET_SERVER_Client *client,
2815 const struct GNUNET_MessageHeader *message)
2817 static GNUNET_HashCode all_zeros;
2818 const struct SearchMessage *sm;
2819 struct ClientList *cl;
2820 struct ClientRequestList *crl;
2821 struct PendingRequest *pr;
2826 msize = ntohs (message->size);
2827 if ( (msize < sizeof (struct SearchMessage)) ||
2828 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
2831 GNUNET_SERVER_receive_done (client,
2835 GNUNET_STATISTICS_update (stats,
2836 gettext_noop ("# client searches received"),
2839 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
2840 sm = (const struct SearchMessage*) message;
2841 type = ntohl (sm->type);
2843 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2844 "Received request for `%s' of type %u from local client\n",
2845 GNUNET_h2s (&sm->query),
2846 (unsigned int) type);
2850 case GNUNET_DATASTORE_BLOCKTYPE_ANY:
2851 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2852 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2853 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
2854 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2855 case GNUNET_DATASTORE_BLOCKTYPE_NBLOCK:
2859 GNUNET_SERVER_receive_done (client,
2865 while ( (cl != NULL) &&
2866 (cl->client != client) )
2870 cl = GNUNET_malloc (sizeof (struct ClientList));
2871 cl->client = client;
2872 GNUNET_SERVER_client_keep (client);
2873 cl->next = client_list;
2876 /* detect duplicate KBLOCK requests */
2877 if ( (type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
2878 (type == GNUNET_DATASTORE_BLOCKTYPE_NBLOCK) ||
2879 (type == GNUNET_DATASTORE_BLOCKTYPE_ANY) )
2882 while ( (crl != NULL) &&
2883 ( (0 != memcmp (&crl->req->query,
2885 sizeof (GNUNET_HashCode))) ||
2886 (crl->req->type != type) ) )
2891 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2892 "Have existing request, merging content-seen lists.\n");
2895 /* Duplicate request (used to send long list of
2896 known/blocked results); merge 'pr->replies_seen'
2897 and update bloom filter */
2898 GNUNET_array_grow (pr->replies_seen,
2899 pr->replies_seen_size,
2900 pr->replies_seen_off + sc);
2901 memcpy (&pr->replies_seen[pr->replies_seen_off],
2903 sc * sizeof (GNUNET_HashCode));
2904 pr->replies_seen_off += sc;
2905 refresh_bloomfilter (pr);
2906 GNUNET_STATISTICS_update (stats,
2907 gettext_noop ("# client searches updated (merged content seen list)"),
2910 GNUNET_SERVER_receive_done (client,
2915 GNUNET_STATISTICS_update (stats,
2916 gettext_noop ("# client searches active"),
2919 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
2920 ((type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ? sizeof(GNUNET_HashCode) : 0));
2921 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
2922 memset (crl, 0, sizeof (struct ClientRequestList));
2923 crl->client_list = cl;
2924 GNUNET_CONTAINER_DLL_insert (cl->rl_head,
2929 pr->client_request_list = crl;
2930 GNUNET_array_grow (pr->replies_seen,
2931 pr->replies_seen_size,
2933 memcpy (pr->replies_seen,
2935 sc * sizeof (GNUNET_HashCode));
2936 pr->replies_seen_off = sc;
2937 pr->anonymity_level = ntohl (sm->anonymity_level);
2938 refresh_bloomfilter (pr);
2939 pr->query = sm->query;
2942 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2943 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2944 if (0 != memcmp (&sm->target,
2946 sizeof (GNUNET_HashCode)))
2947 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
2949 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2950 pr->namespace = (GNUNET_HashCode*) &pr[1];
2951 memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
2956 GNUNET_CONTAINER_multihashmap_put (query_request_map,
2959 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2960 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2961 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* get on-demand blocks too! */
2962 pr->drq = GNUNET_FS_drq_get (&sm->query,
2964 &process_local_reply,
2966 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
2971 /* **************************** Startup ************************ */
2975 * List of handlers for P2P messages
2976 * that we care about.
2978 static struct GNUNET_CORE_MessageHandler p2p_handlers[] =
2981 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
2983 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
2989 * List of handlers for the messages understood by this
2992 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2993 {&GNUNET_FS_handle_index_start, NULL,
2994 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
2995 {&GNUNET_FS_handle_index_list_get, NULL,
2996 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
2997 {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
2998 sizeof (struct UnindexMessage) },
2999 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
3006 * Process fs requests.
3008 * @param s scheduler to use
3009 * @param server the initialized server
3010 * @param c configuration to use
3013 main_init (struct GNUNET_SCHEDULER_Handle *s,
3014 struct GNUNET_SERVER_Handle *server,
3015 const struct GNUNET_CONFIGURATION_Handle *c)
3019 stats = GNUNET_STATISTICS_create (sched, "fs", cfg);
3020 connected_peers = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3021 query_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3022 peer_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3023 requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
3024 core = GNUNET_CORE_connect (sched,
3026 GNUNET_TIME_UNIT_FOREVER_REL,
3029 &peer_connect_handler,
3030 &peer_disconnect_handler,
3036 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3037 _("Failed to connect to `%s' service.\n"),
3039 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
3040 connected_peers = NULL;
3041 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
3042 query_request_map = NULL;
3043 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
3044 requests_by_expiration_heap = NULL;
3045 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
3046 peer_request_map = NULL;
3048 return GNUNET_SYSERR;
3050 GNUNET_SERVER_disconnect_notify (server,
3051 &handle_client_disconnect,
3053 GNUNET_SERVER_add_handlers (server, handlers);
3054 GNUNET_SCHEDULER_add_delayed (sched,
3055 GNUNET_TIME_UNIT_FOREVER_REL,
3063 * Process fs requests.
3065 * @param cls closure
3066 * @param sched scheduler to use
3067 * @param server the initialized server
3068 * @param cfg configuration to use
3072 struct GNUNET_SCHEDULER_Handle *sched,
3073 struct GNUNET_SERVER_Handle *server,
3074 const struct GNUNET_CONFIGURATION_Handle *cfg)
3076 if ( (GNUNET_OK != GNUNET_FS_drq_init (sched, cfg)) ||
3077 (GNUNET_OK != GNUNET_FS_indexing_init (sched, cfg)) ||
3078 (GNUNET_OK != main_init (sched, server, cfg)) )
3080 GNUNET_SCHEDULER_shutdown (sched);
3087 * The main function for the fs service.
3089 * @param argc number of arguments from the command line
3090 * @param argv command line arguments
3091 * @return 0 ok, 1 on error
3094 main (int argc, char *const *argv)
3096 return (GNUNET_OK ==
3097 GNUNET_SERVICE_run (argc,
3100 GNUNET_SERVICE_OPTION_NONE,
3101 &run, NULL)) ? 0 : 1;
3104 /* end of gnunet-service-fs.c */