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 * - have non-zero preference / priority for requests we initiate!
28 * - track stats for hot-path routing
29 * - implement hot-path routing decision procedure
30 * - implement: bound_priority, test_load_too_high, validate_skblock
31 * - add content migration support (store locally)
36 #include "gnunet_constants.h"
37 #include "gnunet_core_service.h"
38 #include "gnunet_datastore_service.h"
39 #include "gnunet_peer_lib.h"
40 #include "gnunet_protocols.h"
41 #include "gnunet_signatures.h"
42 #include "gnunet_util_lib.h"
43 #include "gnunet-service-fs_drq.h"
44 #include "gnunet-service-fs_indexing.h"
47 #define DEBUG_FS GNUNET_YES
50 * Maximum number of outgoing messages we queue per peer.
51 * FIXME: set to a tiny value for testing; make configurable.
53 #define MAX_QUEUE_PER_PEER 2
57 * Maximum number of requests (from other peers) that we're
58 * willing to have pending at any given point in time.
59 * FIXME: set from configuration (and 32 is a tiny value for testing only).
61 static uint64_t max_pending_requests = 32;
65 * Information we keep for each pending reply. The
66 * actual message follows at the end of this struct.
68 struct PendingMessage;
72 * Function called upon completion of a transmission.
75 * @param pid ID of receiving peer, 0 on transmission error
77 typedef void (*TransmissionContinuation)(void * cls,
82 * Information we keep for each pending message (GET/PUT). The
83 * actual message follows at the end of this struct.
88 * This is a doubly-linked list of messages to the same peer.
90 struct PendingMessage *next;
93 * This is a doubly-linked list of messages to the same peer.
95 struct PendingMessage *prev;
98 * Entry in pending message list for this pending message.
100 struct PendingMessageList *pml;
103 * Function to call immediately once we have transmitted this
106 TransmissionContinuation cont;
114 * Size of the reply; actual reply message follows
115 * at the end of this struct.
120 * How important is this message for us?
128 * Information about a peer that we are connected to.
129 * We track data that is useful for determining which
130 * peers should receive our requests. We also keep
131 * a list of messages to transmit to this peer.
137 * List of the last clients for which this peer successfully
140 struct GNUNET_SERVER_Client *last_client_replies[CS2P_SUCCESS_LIST_SIZE];
143 * List of the last PIDs for which
144 * this peer successfully answered a query;
145 * We use 0 to indicate no successful reply.
147 GNUNET_PEER_Id last_p2p_replies[P2P_SUCCESS_LIST_SIZE];
150 * Average delay between sending the peer a request and
151 * getting a reply (only calculated over the requests for
152 * which we actually got a reply). Calculated
153 * as a moving average: new_delay = ((n-1)*last_delay+curr_delay) / n
155 struct GNUNET_TIME_Relative avg_delay;
158 * Handle for an active request for transmission to this
161 struct GNUNET_CORE_TransmitHandle *cth;
164 * Messages (replies, queries, content migration) we would like to
165 * send to this peer in the near future. Sorted by priority, head.
167 struct PendingMessage *pending_messages_head;
170 * Messages (replies, queries, content migration) we would like to
171 * send to this peer in the near future. Sorted by priority, tail.
173 struct PendingMessage *pending_messages_tail;
176 * Average priority of successful replies. Calculated
177 * as a moving average: new_avg = ((n-1)*last_avg+curr_prio) / n
182 * Increase in traffic preference still to be submitted
183 * to the core service for this peer. FIXME: double or 'uint64_t'?
185 double inc_preference;
188 * The peer's identity.
193 * Size of the linked list of 'pending_messages'.
195 unsigned int pending_requests;
198 * Which offset in "last_p2p_replies" will be updated next?
199 * (we go round-robin).
201 unsigned int last_p2p_replies_woff;
204 * Which offset in "last_client_replies" will be updated next?
205 * (we go round-robin).
207 unsigned int last_client_replies_woff;
213 * Information we keep for each pending request. We should try to
214 * keep this struct as small as possible since its memory consumption
215 * is key to how many requests we can have pending at once.
217 struct PendingRequest;
221 * Doubly-linked list of requests we are performing
222 * on behalf of the same client.
224 struct ClientRequestList
228 * This is a doubly-linked list.
230 struct ClientRequestList *next;
233 * This is a doubly-linked list.
235 struct ClientRequestList *prev;
238 * Request this entry represents.
240 struct PendingRequest *req;
243 * Client list this request belongs to.
245 struct ClientList *client_list;
251 * Replies to be transmitted to the client. The actual
252 * response message is allocated after this struct.
254 struct ClientResponseMessage
257 * This is a doubly-linked list.
259 struct ClientResponseMessage *next;
262 * This is a doubly-linked list.
264 struct ClientResponseMessage *prev;
267 * Client list entry this response belongs to.
269 struct ClientList *client_list;
272 * Number of bytes in the response.
279 * Linked list of clients we are performing requests
285 * This is a linked list.
287 struct ClientList *next;
290 * ID of a client making a request, NULL if this entry is for a
293 struct GNUNET_SERVER_Client *client;
296 * Head of list of requests performed on behalf
297 * of this client right now.
299 struct ClientRequestList *rl_head;
302 * Tail of list of requests performed on behalf
303 * of this client right now.
305 struct ClientRequestList *rl_tail;
308 * Head of linked list of responses.
310 struct ClientResponseMessage *res_head;
313 * Tail of linked list of responses.
315 struct ClientResponseMessage *res_tail;
318 * Context for sending replies.
320 struct GNUNET_CONNECTION_TransmitHandle *th;
326 * Doubly-linked list of messages we are performing
327 * due to a pending request.
329 struct PendingMessageList
333 * This is a doubly-linked list of messages on behalf of the same request.
335 struct PendingMessageList *next;
338 * This is a doubly-linked list of messages on behalf of the same request.
340 struct PendingMessageList *prev;
343 * Message this entry represents.
345 struct PendingMessage *pm;
348 * Request this entry belongs to.
350 struct PendingRequest *req;
353 * Peer this message is targeted for.
355 struct ConnectedPeer *target;
361 * Information we keep for each pending request. We should try to
362 * keep this struct as small as possible since its memory consumption
363 * is key to how many requests we can have pending at once.
365 struct PendingRequest
369 * If this request was made by a client, this is our entry in the
370 * client request list; otherwise NULL.
372 struct ClientRequestList *client_request_list;
375 * Entry of peer responsible for this entry (if this request
376 * was made by a peer).
378 struct ConnectedPeer *cp;
381 * If this is a namespace query, pointer to the hash of the public
382 * key of the namespace; otherwise NULL. Pointer will be to the
383 * end of this struct (so no need to free it).
385 const GNUNET_HashCode *namespace;
388 * Bloomfilter we use to filter out replies that we don't care about
389 * (anymore). NULL as long as we are interested in all replies.
391 struct GNUNET_CONTAINER_BloomFilter *bf;
394 * Context of our GNUNET_CORE_peer_change_preference call.
396 struct GNUNET_CORE_InformationRequestContext *irc;
399 * Hash code of all replies that we have seen so far (only valid
400 * if client is not NULL since we only track replies like this for
403 GNUNET_HashCode *replies_seen;
406 * Node in the heap representing this entry; NULL
407 * if we have no heap node.
409 struct GNUNET_CONTAINER_HeapNode *hnode;
412 * Head of list of messages being performed on behalf of this
415 struct PendingMessageList *pending_head;
418 * Tail of list of messages being performed on behalf of this
421 struct PendingMessageList *pending_tail;
424 * When did we first see this request (form this peer), or, if our
425 * client is initiating, when did we last initiate a search?
427 struct GNUNET_TIME_Absolute start_time;
430 * The query that this request is for.
432 GNUNET_HashCode query;
435 * The task responsible for transmitting queries
438 GNUNET_SCHEDULER_TaskIdentifier task;
441 * (Interned) Peer identifier that identifies a preferred target
444 GNUNET_PEER_Id target_pid;
447 * (Interned) Peer identifiers of peers that have already
448 * received our query for this content.
450 GNUNET_PEER_Id *used_pids;
453 * Our entry in the DRQ (non-NULL while we wait for our
454 * turn to interact with the local database).
456 struct DatastoreRequestQueue *drq;
459 * Size of the 'bf' (in bytes).
464 * Desired anonymity level; only valid for requests from a local client.
466 uint32_t anonymity_level;
469 * How many entries in "used_pids" are actually valid?
471 unsigned int used_pids_off;
474 * How long is the "used_pids" array?
476 unsigned int used_pids_size;
479 * Number of results found for this request.
481 unsigned int results_found;
484 * How many entries in "replies_seen" are actually valid?
486 unsigned int replies_seen_off;
489 * How long is the "replies_seen" array?
491 unsigned int replies_seen_size;
494 * Priority with which this request was made. If one of our clients
495 * made the request, then this is the current priority that we are
496 * using when initiating the request. This value is used when
497 * we decide to reward other peers with trust for providing a reply.
502 * Priority points left for us to spend when forwarding this request
505 uint32_t remaining_priority;
508 * Number to mingle hashes for bloom-filter tests with.
513 * TTL with which we saw this request (or, if we initiated, TTL that
514 * we used for the request).
519 * Type of the content that this request is for.
529 static struct GNUNET_SCHEDULER_Handle *sched;
534 static const struct GNUNET_CONFIGURATION_Handle *cfg;
537 * Map of peer identifiers to "struct ConnectedPeer" (for that peer).
539 static struct GNUNET_CONTAINER_MultiHashMap *connected_peers;
542 * Map of peer identifiers to "struct PendingRequest" (for that peer).
544 static struct GNUNET_CONTAINER_MultiHashMap *peer_request_map;
547 * Map of query identifiers to "struct PendingRequest" (for that query).
549 static struct GNUNET_CONTAINER_MultiHashMap *query_request_map;
552 * Heap with the request that will expire next at the top. Contains
553 * pointers of type "struct PendingRequest*"; these will *also* be
554 * aliased from the "requests_by_peer" data structures and the
555 * "requests_by_query" table. Note that requests from our clients
556 * don't expire and are thus NOT in the "requests_by_expiration"
557 * (or the "requests_by_peer" tables).
559 static struct GNUNET_CONTAINER_Heap *requests_by_expiration_heap;
562 * Linked list of clients we are currently processing requests for.
564 struct ClientList *client_list;
567 * Pointer to handle to the core service (points to NULL until we've
570 struct GNUNET_CORE_Handle *core;
573 /* ******************* clean up functions ************************ */
577 * We're done with a particular message list entry.
578 * Free all associated resources.
580 * @param pml entry to destroy
583 destroy_pending_message_list_entry (struct PendingMessageList *pml)
585 GNUNET_CONTAINER_DLL_remove (pml->req->pending_head,
586 pml->req->pending_tail,
588 GNUNET_CONTAINER_DLL_remove (pml->target->pending_messages_head,
589 pml->target->pending_messages_tail,
591 pml->target->pending_requests--;
592 GNUNET_free (pml->pm);
598 * Destroy the given pending message (and call the respective
601 * @param pm message to destroy
602 * @param tpid id of peer that the message was delivered to, or 0 for none
605 destroy_pending_message (struct PendingMessage *pm,
608 struct PendingMessageList *pml = pm->pml;
609 TransmissionContinuation cont;
612 GNUNET_assert (pml->pm == pm);
613 GNUNET_assert ( (tpid == 0) || (tpid == pml->target->pid) );
615 cont_cls = pm->cont_cls;
616 destroy_pending_message_list_entry (pml);
623 * We're done processing a particular request.
624 * Free all associated resources.
626 * @param pr request to destroy
629 destroy_pending_request (struct PendingRequest *pr)
631 struct GNUNET_PeerIdentity pid;
633 if (pr->hnode != NULL)
635 GNUNET_CONTAINER_heap_remove_node (requests_by_expiration_heap,
639 /* might have already been removed from map in 'process_reply' (if
640 there was a unique reply) or never inserted if it was a
641 duplicate; hence ignore the return value here */
642 (void) GNUNET_CONTAINER_multihashmap_remove (query_request_map,
647 GNUNET_FS_drq_get_cancel (pr->drq);
650 if (pr->client_request_list != NULL)
652 GNUNET_CONTAINER_DLL_remove (pr->client_request_list->client_list->rl_head,
653 pr->client_request_list->client_list->rl_tail,
654 pr->client_request_list);
655 GNUNET_free (pr->client_request_list);
656 pr->client_request_list = NULL;
660 GNUNET_PEER_resolve (pr->cp->pid,
662 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
669 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
674 GNUNET_CORE_peer_change_preference_cancel (pr->irc);
677 if (pr->replies_seen != NULL)
679 GNUNET_free (pr->replies_seen);
680 pr->replies_seen = NULL;
682 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
684 GNUNET_SCHEDULER_cancel (sched,
686 pr->task = GNUNET_SCHEDULER_NO_TASK;
688 while (NULL != pr->pending_head)
689 destroy_pending_message_list_entry (pr->pending_head);
690 GNUNET_PEER_change_rc (pr->target_pid, -1);
691 if (pr->used_pids != NULL)
693 GNUNET_PEER_decrement_rcs (pr->used_pids, pr->used_pids_off);
694 GNUNET_free (pr->used_pids);
695 pr->used_pids_off = 0;
696 pr->used_pids_size = 0;
697 pr->used_pids = NULL;
704 * Method called whenever a given peer connects.
706 * @param cls closure, not used
707 * @param peer peer identity this notification is about
708 * @param latency reported latency of the connection with 'other'
709 * @param distance reported distance (DV) to 'other'
712 peer_connect_handler (void *cls,
714 GNUNET_PeerIdentity * peer,
715 struct GNUNET_TIME_Relative latency,
718 struct ConnectedPeer *cp;
720 cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
721 cp->pid = GNUNET_PEER_intern (peer);
722 GNUNET_CONTAINER_multihashmap_put (connected_peers,
725 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
730 * Free (each) request made by the peer.
732 * @param cls closure, points to peer that the request belongs to
733 * @param key current key code
734 * @param value value in the hash map
735 * @return GNUNET_YES (we should continue to iterate)
738 destroy_request (void *cls,
739 const GNUNET_HashCode * key,
742 const struct GNUNET_PeerIdentity * peer = cls;
743 struct PendingRequest *pr = value;
745 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
748 destroy_pending_request (pr);
754 * Method called whenever a peer disconnects.
756 * @param cls closure, not used
757 * @param peer peer identity this notification is about
760 peer_disconnect_handler (void *cls,
762 GNUNET_PeerIdentity * peer)
764 struct ConnectedPeer *cp;
765 struct PendingMessage *pm;
768 GNUNET_CONTAINER_multihashmap_get_multiple (peer_request_map,
772 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
776 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
778 if (NULL != cp->last_client_replies[i])
780 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
781 cp->last_client_replies[i] = NULL;
784 GNUNET_CONTAINER_multihashmap_remove (connected_peers,
787 GNUNET_PEER_change_rc (cp->pid, -1);
788 GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
790 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
791 while (NULL != (pm = cp->pending_messages_head))
792 destroy_pending_message (pm, 0 /* delivery failed */);
793 GNUNET_break (0 == cp->pending_requests);
799 * Iterator over hash map entries that removes all occurences
800 * of the given 'client' from the 'last_client_replies' of the
801 * given connected peer.
803 * @param cls closure, the 'struct GNUNET_SERVER_Client*' to remove
804 * @param key current key code (unused)
805 * @param value value in the hash map (the 'struct ConnectedPeer*' to change)
806 * @return GNUNET_YES (we should continue to iterate)
809 remove_client_from_last_client_replies (void *cls,
810 const GNUNET_HashCode * key,
813 struct GNUNET_SERVER_Client *client = cls;
814 struct ConnectedPeer *cp = value;
817 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
819 if (cp->last_client_replies[i] == client)
821 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
822 cp->last_client_replies[i] = NULL;
830 * A client disconnected. Remove all of its pending queries.
832 * @param cls closure, NULL
833 * @param client identification of the client
836 handle_client_disconnect (void *cls,
837 struct GNUNET_SERVER_Client
840 struct ClientList *pos;
841 struct ClientList *prev;
842 struct ClientRequestList *rcl;
843 struct ClientResponseMessage *creply;
849 while ( (NULL != pos) &&
850 (pos->client != client) )
856 return; /* no requests pending for this client */
857 while (NULL != (rcl = pos->rl_head))
858 destroy_pending_request (rcl->req);
860 client_list = pos->next;
862 prev->next = pos->next;
865 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
868 while (NULL != (creply = pos->res_head))
870 GNUNET_CONTAINER_DLL_remove (pos->res_head,
873 GNUNET_free (creply);
875 GNUNET_SERVER_client_drop (pos->client);
877 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
878 &remove_client_from_last_client_replies,
884 * Iterator to free peer entries.
886 * @param cls closure, unused
887 * @param key current key code
888 * @param value value in the hash map (peer entry)
889 * @return GNUNET_YES (we should continue to iterate)
892 clean_peer (void *cls,
893 const GNUNET_HashCode * key,
896 peer_disconnect_handler (NULL, (const struct GNUNET_PeerIdentity*) key);
902 * Task run during shutdown.
908 shutdown_task (void *cls,
909 const struct GNUNET_SCHEDULER_TaskContext *tc)
911 while (client_list != NULL)
912 handle_client_disconnect (NULL,
913 client_list->client);
914 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
917 GNUNET_break (0 == GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap));
918 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
919 requests_by_expiration_heap = 0;
920 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
921 connected_peers = NULL;
922 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (query_request_map));
923 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
924 query_request_map = NULL;
925 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (peer_request_map));
926 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
927 peer_request_map = NULL;
928 GNUNET_assert (NULL != core);
929 GNUNET_CORE_disconnect (core);
936 /* ******************* Utility functions ******************** */
940 * Transmit the given message by copying it to the target buffer
941 * "buf". "buf" will be NULL and "size" zero if the socket was closed
942 * for writing in the meantime. In that case, do nothing
943 * (the disconnect or shutdown handler will take care of the rest).
944 * If we were able to transmit messages and there are still more
945 * pending, ask core again for further calls to this function.
947 * @param cls closure, pointer to the 'struct ConnectedPeer*'
948 * @param size number of bytes available in buf
949 * @param buf where the callee should write the message
950 * @return number of bytes written to buf
953 transmit_to_peer (void *cls,
954 size_t size, void *buf)
956 struct ConnectedPeer *cp = cls;
958 struct GNUNET_PeerIdentity pid;
959 struct PendingMessage *pm;
966 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
967 "Dropping message, core too busy.\n");
972 while ( (NULL != (pm = cp->pending_messages_head) ) &&
973 (pm->msize <= size) )
975 memcpy (&cbuf[msize], &pm[1], pm->msize);
978 destroy_pending_message (pm, cp->pid);
982 GNUNET_PEER_resolve (cp->pid,
984 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
986 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
993 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
994 "Transmitting %u bytes to peer %u.\n",
1003 * Add a message to the set of pending messages for the given peer.
1005 * @param cp peer to send message to
1006 * @param pm message to queue
1007 * @param pr request on which behalf this message is being queued
1010 add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
1011 struct PendingMessage *pm,
1012 struct PendingRequest *pr)
1014 struct PendingMessage *pos;
1015 struct PendingMessageList *pml;
1016 struct GNUNET_PeerIdentity pid;
1018 GNUNET_assert (pm->next == NULL);
1019 GNUNET_assert (pm->pml == NULL);
1020 pml = GNUNET_malloc (sizeof (struct PendingMessageList));
1025 GNUNET_CONTAINER_DLL_insert (pr->pending_head,
1028 pos = cp->pending_messages_head;
1029 while ( (pos != NULL) &&
1030 (pm->priority < pos->priority) )
1032 GNUNET_CONTAINER_DLL_insert_after (cp->pending_messages_head,
1033 cp->pending_messages_tail,
1036 cp->pending_requests++;
1037 if (cp->pending_requests > MAX_QUEUE_PER_PEER)
1038 destroy_pending_message (cp->pending_messages_tail, 0);
1039 if (cp->cth == NULL)
1041 /* need to schedule transmission */
1042 GNUNET_PEER_resolve (cp->pid, &pid);
1043 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1044 cp->pending_messages_head->priority,
1045 GNUNET_TIME_UNIT_FOREVER_REL,
1047 cp->pending_messages_head->msize,
1051 if (cp->cth == NULL)
1054 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1055 "Failed to schedule transmission with core!\n");
1057 /* FIXME: call stats (rare, bad case) */
1063 * Mingle hash with the mingle_number to produce different bits.
1066 mingle_hash (const GNUNET_HashCode * in,
1067 int32_t mingle_number,
1068 GNUNET_HashCode * hc)
1072 GNUNET_CRYPTO_hash (&mingle_number,
1075 GNUNET_CRYPTO_hash_xor (&m, in, hc);
1080 * Test if the load on this peer is too high
1081 * to even consider processing the query at
1084 * @return GNUNET_YES if the load is too high, GNUNET_NO otherwise
1087 test_load_too_high ()
1089 return GNUNET_NO; // FIXME
1093 /* ******************* Pending Request Refresh Task ******************** */
1097 * Function called after we either failed or succeeded
1098 * at transmitting a query to a peer.
1100 * @param cls the requests "struct PendingRequest*"
1101 * @param tpid ID of receiving peer, 0 on transmission error
1104 transmit_query_continuation (void *cls,
1105 GNUNET_PEER_Id tpid)
1107 struct PendingRequest *pr = cls;
1111 GNUNET_PEER_change_rc (tpid, 1);
1112 if (pr->used_pids_off == pr->used_pids_size)
1113 GNUNET_array_grow (pr->used_pids,
1115 pr->used_pids_size * 2 + 2);
1116 pr->used_pids[pr->used_pids_off++] = tpid;
1121 * How many bytes should a bloomfilter be if we have already seen
1122 * entry_count responses? Note that BLOOMFILTER_K gives us the number
1123 * of bits set per entry. Furthermore, we should not re-size the
1124 * filter too often (to keep it cheap).
1126 * Since other peers will also add entries but not resize the filter,
1127 * we should generally pick a slightly larger size than what the
1128 * strict math would suggest.
1130 * @return must be a power of two and smaller or equal to 2^15.
1133 compute_bloomfilter_size (unsigned int entry_count)
1136 unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
1137 uint16_t max = 1 << 15;
1139 if (entry_count > max)
1142 while ((size < max) && (size < ideal))
1151 * Recalculate our bloom filter for filtering replies.
1153 * @param count number of entries we are filtering right now
1154 * @param mingle set to our new mingling value
1155 * @param bf_size set to the size of the bloomfilter
1156 * @param entries the entries to filter
1157 * @return updated bloomfilter, NULL for none
1159 static struct GNUNET_CONTAINER_BloomFilter *
1160 refresh_bloomfilter (unsigned int count,
1163 const GNUNET_HashCode *entries)
1165 struct GNUNET_CONTAINER_BloomFilter *bf;
1168 GNUNET_HashCode mhash;
1172 nsize = compute_bloomfilter_size (count);
1173 *mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
1175 bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1178 for (i=0;i<count;i++)
1180 mingle_hash (&entries[i], *mingle, &mhash);
1181 GNUNET_CONTAINER_bloomfilter_add (bf, &mhash);
1188 * We use a random delay to make the timing of requests less
1189 * predictable. This function returns such a random delay.
1191 * FIXME: make schedule dependent on the specifics of the request?
1192 * Or bandwidth and number of connected peers and load?
1194 * @return random delay to use for some request, between 0 and TTL_DECREMENT ms
1196 static struct GNUNET_TIME_Relative
1197 get_processing_delay ()
1199 return GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1200 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1206 * Function called after we've tried to reserve a certain amount of
1207 * bandwidth for a reply. Check if we succeeded and if so send our
1210 * @param cls the requests "struct PendingRequest*"
1211 * @param peer identifies the peer
1212 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1213 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1214 * @param amount set to the amount that was actually reserved or unreserved
1215 * @param preference current traffic preference for the given peer
1218 target_reservation_cb (void *cls,
1220 GNUNET_PeerIdentity * peer,
1221 unsigned int bpm_in,
1222 unsigned int bpm_out,
1224 uint64_t preference)
1226 struct PendingRequest *pr = cls;
1227 struct ConnectedPeer *cp;
1228 struct PendingMessage *pm;
1229 struct GetMessage *gm;
1230 GNUNET_HashCode *ext;
1238 GNUNET_assert (peer != NULL);
1239 // (3) transmit, update ttl/priority
1240 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1244 /* Peer must have just left */
1246 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1247 "Selected peer disconnected!\n");
1251 no_route = GNUNET_NO;
1252 /* FIXME: check against DBLOCK_SIZE and possibly return
1253 amount to reserve; however, this also needs to work
1254 with testcases which currently start out with a far
1255 too low per-peer bw limit, so they would never send
1256 anything. Big issue. */
1262 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1263 "Failed to reserve bandwidth for reply (got %d/%u bytes only)!\n",
1267 return; /* this target round failed */
1269 /* FIXME: if we are "quite" busy, we may still want to skip
1270 this round; need more load detection code! */
1271 no_route = GNUNET_YES;
1274 /* build message and insert message into priority queue */
1276 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1277 "Forwarding request to `%4s'!\n",
1282 if (GNUNET_YES == no_route)
1284 bm |= GET_MESSAGE_BIT_RETURN_TO;
1287 if (pr->namespace != NULL)
1289 bm |= GET_MESSAGE_BIT_SKS_NAMESPACE;
1292 if (pr->target_pid != 0)
1294 bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
1297 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
1298 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1299 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1301 gm = (struct GetMessage*) &pm[1];
1302 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
1303 gm->header.size = htons (msize);
1304 gm->type = htonl (pr->type);
1305 pr->remaining_priority /= 2;
1306 gm->priority = htonl (pr->remaining_priority);
1307 gm->ttl = htonl (pr->ttl);
1308 gm->filter_mutator = htonl(pr->mingle);
1309 gm->hash_bitmap = htonl (bm);
1310 gm->query = pr->query;
1311 ext = (GNUNET_HashCode*) &gm[1];
1313 if (GNUNET_YES == no_route)
1314 GNUNET_PEER_resolve (pr->cp->pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1315 if (pr->namespace != NULL)
1316 memcpy (&ext[k++], pr->namespace, sizeof (GNUNET_HashCode));
1317 if (pr->target_pid != 0)
1318 GNUNET_PEER_resolve (pr->target_pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1319 bfdata = (char *) &ext[k];
1321 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
1324 pm->cont = &transmit_query_continuation;
1326 add_to_pending_messages_for_peer (cp, pm, pr);
1331 * Closure used for "target_peer_select_cb".
1333 struct PeerSelectionContext
1336 * The request for which we are selecting
1339 struct PendingRequest *pr;
1342 * Current "prime" target.
1344 struct GNUNET_PeerIdentity target;
1347 * How much do we like this target?
1349 double target_score;
1355 * Function called for each connected peer to determine
1356 * which one(s) would make good targets for forwarding.
1358 * @param cls closure (struct PeerSelectionContext)
1359 * @param key current key code (peer identity)
1360 * @param value value in the hash map (struct ConnectedPeer)
1361 * @return GNUNET_YES if we should continue to
1366 target_peer_select_cb (void *cls,
1367 const GNUNET_HashCode * key,
1370 struct PeerSelectionContext *psc = cls;
1371 struct ConnectedPeer *cp = value;
1372 struct PendingRequest *pr = psc->pr;
1376 /* 1) check if we have already (recently) forwarded to this peer */
1377 for (i=0;i<pr->used_pids_off;i++)
1378 if (pr->used_pids[i] == cp->pid)
1379 return GNUNET_YES; /* skip */
1380 // 2) calculate how much we'd like to forward to this peer
1381 score = 42; // FIXME!
1382 // FIXME: also need API to gather data on responsiveness
1383 // of this peer (we have fields for that in 'cp', but
1384 // they are never set!)
1386 /* store best-fit in closure */
1387 if (score > psc->target_score)
1389 psc->target_score = score;
1390 psc->target.hashPubKey = *key;
1397 * We're processing a GET request from another peer and have decided
1398 * to forward it to other peers. This function is called periodically
1399 * and should forward the request to other peers until we have all
1400 * possible replies. If we have transmitted the *only* reply to
1401 * the initiator we should destroy the pending request. If we have
1402 * many replies in the queue to the initiator, we should delay sending
1403 * out more queries until the reply queue has shrunk some.
1405 * @param cls our "struct ProcessGetContext *"
1409 forward_request_task (void *cls,
1410 const struct GNUNET_SCHEDULER_TaskContext *tc)
1412 struct PendingRequest *pr = cls;
1413 struct PeerSelectionContext psc;
1414 struct ConnectedPeer *cp;
1416 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1417 get_processing_delay (),
1418 &forward_request_task,
1420 if (pr->irc != NULL)
1421 return; /* previous request still pending */
1422 /* (1) select target */
1424 psc.target_score = DBL_MIN;
1425 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1426 &target_peer_select_cb,
1428 if (psc.target_score == DBL_MIN)
1431 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1432 "No peer selected for forwarding!\n");
1434 return; /* nobody selected */
1437 /* (2) reserve reply bandwidth */
1438 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1439 &psc.target.hashPubKey);
1440 pr->irc = GNUNET_CORE_peer_change_preference (sched, cfg,
1442 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1443 (uint32_t) -1 /* no limit */,
1445 (uint64_t) cp->inc_preference,
1446 &target_reservation_cb,
1448 cp->inc_preference = 0.0;
1452 /* **************************** P2P PUT Handling ************************ */
1456 * Function called after we either failed or succeeded
1457 * at transmitting a reply to a peer.
1459 * @param cls the requests "struct PendingRequest*"
1460 * @param tpid ID of receiving peer, 0 on transmission error
1463 transmit_reply_continuation (void *cls,
1464 GNUNET_PEER_Id tpid)
1466 struct PendingRequest *pr = cls;
1470 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1471 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1472 /* only one reply expected, done with the request! */
1473 destroy_pending_request (pr);
1475 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1476 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1486 * Check if the given KBlock is well-formed.
1488 * @param kb the kblock data (or at least "dsize" bytes claiming to be one)
1489 * @param dsize size of "kb" in bytes; check for < sizeof(struct KBlock)!
1490 * @param query where to store the query that this block answers
1491 * @return GNUNET_OK if this is actually a well-formed KBlock
1494 check_kblock (const struct KBlock *kb,
1496 GNUNET_HashCode *query)
1498 if (dsize < sizeof (struct KBlock))
1500 GNUNET_break_op (0);
1501 return GNUNET_SYSERR;
1503 if (dsize - sizeof (struct KBlock) !=
1504 ntohs (kb->purpose.size)
1505 - sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose)
1506 - sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) )
1508 GNUNET_break_op (0);
1509 return GNUNET_SYSERR;
1512 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_KBLOCK,
1517 GNUNET_break_op (0);
1518 return GNUNET_SYSERR;
1521 GNUNET_CRYPTO_hash (&kb->keyspace,
1522 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1529 * Check if the given SBlock is well-formed.
1531 * @param sb the sblock data (or at least "dsize" bytes claiming to be one)
1532 * @param dsize size of "kb" in bytes; check for < sizeof(struct SBlock)!
1533 * @param query where to store the query that this block answers
1534 * @param namespace where to store the namespace that this block belongs to
1535 * @return GNUNET_OK if this is actually a well-formed SBlock
1538 check_sblock (const struct SBlock *sb,
1540 GNUNET_HashCode *query,
1541 GNUNET_HashCode *namespace)
1543 if (dsize < sizeof (struct SBlock))
1545 GNUNET_break_op (0);
1546 return GNUNET_SYSERR;
1549 ntohs (sb->purpose.size) + sizeof (struct GNUNET_CRYPTO_RsaSignature))
1551 GNUNET_break_op (0);
1552 return GNUNET_SYSERR;
1555 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_SBLOCK,
1560 GNUNET_break_op (0);
1561 return GNUNET_SYSERR;
1564 *query = sb->identifier;
1565 if (namespace != NULL)
1566 GNUNET_CRYPTO_hash (&sb->subspace,
1567 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1574 * Transmit the given message by copying it to the target buffer
1575 * "buf". "buf" will be NULL and "size" zero if the socket was closed
1576 * for writing in the meantime. In that case, do nothing
1577 * (the disconnect or shutdown handler will take care of the rest).
1578 * If we were able to transmit messages and there are still more
1579 * pending, ask core again for further calls to this function.
1581 * @param cls closure, pointer to the 'struct ClientList*'
1582 * @param size number of bytes available in buf
1583 * @param buf where the callee should write the message
1584 * @return number of bytes written to buf
1587 transmit_to_client (void *cls,
1588 size_t size, void *buf)
1590 struct ClientList *cl = cls;
1592 struct ClientResponseMessage *creply;
1599 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1600 "Not sending reply, client communication problem.\n");
1605 while ( (NULL != (creply = cl->res_head) ) &&
1606 (creply->msize <= size) )
1608 memcpy (&cbuf[msize], &creply[1], creply->msize);
1609 msize += creply->msize;
1610 size -= creply->msize;
1611 GNUNET_CONTAINER_DLL_remove (cl->res_head,
1614 GNUNET_free (creply);
1617 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
1619 GNUNET_TIME_UNIT_FOREVER_REL,
1620 &transmit_to_client,
1623 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1624 "Transmitted %u bytes to client\n",
1625 (unsigned int) msize);
1632 * Closure for "process_reply" function.
1634 struct ProcessReplyClosure
1637 * The data for the reply.
1641 // FIXME: add 'struct ConnectedPeer' to track 'last_xxx_replies' here!
1644 * When the reply expires.
1646 struct GNUNET_TIME_Absolute expiration;
1654 * Namespace that this reply belongs to
1655 * (if it is of type SBLOCK).
1657 GNUNET_HashCode namespace;
1660 * Type of the block.
1665 * How much was this reply worth to us?
1672 * We have received a reply; handle it!
1674 * @param cls response (struct ProcessReplyClosure)
1675 * @param key our query
1676 * @param value value in the hash map (info about the query)
1677 * @return GNUNET_YES (we should continue to iterate)
1680 process_reply (void *cls,
1681 const GNUNET_HashCode * key,
1684 struct ProcessReplyClosure *prq = cls;
1685 struct PendingRequest *pr = value;
1686 struct PendingMessage *reply;
1687 struct ClientResponseMessage *creply;
1688 struct ClientList *cl;
1689 struct PutMessage *pm;
1690 struct ConnectedPeer *cp;
1691 GNUNET_HashCode chash;
1692 GNUNET_HashCode mhash;
1698 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1699 "Matched result for query `%s' with pending request\n",
1702 do_remove = GNUNET_NO;
1703 GNUNET_CRYPTO_hash (prq->data,
1708 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1709 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1710 /* only possible reply, stop requesting! */
1711 while (NULL != pr->pending_head)
1712 destroy_pending_message_list_entry (pr->pending_head);
1713 if (pr->drq != NULL)
1715 GNUNET_FS_drq_get_cancel (pr->drq);
1718 do_remove = GNUNET_YES;
1720 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1721 if (0 != memcmp (pr->namespace,
1723 sizeof (GNUNET_HashCode)))
1724 return GNUNET_YES; /* wrong namespace */
1725 /* then: fall-through! */
1726 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1729 mingle_hash (&chash, pr->mingle, &mhash);
1730 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
1732 return GNUNET_YES; /* duplicate */
1733 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
1736 if (pr->client_request_list != NULL)
1738 if (pr->replies_seen_size == pr->replies_seen_off)
1740 GNUNET_array_grow (pr->replies_seen,
1741 pr->replies_seen_size,
1742 pr->replies_seen_size * 2 + 4);
1744 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
1745 pr->bf = refresh_bloomfilter (pr->replies_seen_off,
1750 pr->replies_seen[pr->replies_seen_off++] = chash;
1754 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
1755 // FIXME: any checks against duplicates for SKBlocks?
1761 prio = pr->priority;
1762 prq->priority += pr->remaining_priority;
1763 pr->remaining_priority = 0;
1764 if (pr->client_request_list != NULL)
1767 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1768 "Transmitting result for query `%s' to local client\n",
1771 cl = pr->client_request_list->client_list;
1772 msize = sizeof (struct PutMessage) + prq->size;
1773 creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
1774 creply->msize = msize;
1775 creply->client_list = cl;
1776 GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
1780 pm = (struct PutMessage*) &creply[1];
1781 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
1782 pm->header.size = htons (msize);
1783 pm->type = htonl (prq->type);
1784 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
1785 memcpy (&pm[1], prq->data, prq->size);
1787 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
1789 GNUNET_TIME_UNIT_FOREVER_REL,
1790 &transmit_to_client,
1792 GNUNET_break (cl->th != NULL);
1798 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1799 "Transmitting result for query `%s' to other peer (PID=%u)\n",
1801 (unsigned int) cp->pid);
1803 msize = sizeof (struct PutMessage) + prq->size;
1804 reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
1805 reply->cont = &transmit_reply_continuation;
1806 reply->cont_cls = pr;
1807 reply->msize = msize;
1808 reply->priority = (uint32_t) -1; /* send replies first! */
1809 pm = (struct PutMessage*) &reply[1];
1810 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
1811 pm->header.size = htons (msize);
1812 pm->type = htonl (prq->type);
1813 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
1814 memcpy (&pm[1], prq->data, prq->size);
1815 add_to_pending_messages_for_peer (cp, reply, pr);
1817 if (GNUNET_YES == do_remove)
1818 GNUNET_break (GNUNET_YES ==
1819 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
1823 // FIXME: implement hot-path routing statistics keeping!
1829 * Handle P2P "PUT" message.
1831 * @param cls closure, always NULL
1832 * @param other the other peer involved (sender or receiver, NULL
1833 * for loopback messages where we are both sender and receiver)
1834 * @param message the actual message
1835 * @param latency reported latency of the connection with 'other'
1836 * @param distance reported distance (DV) to 'other'
1837 * @return GNUNET_OK to keep the connection open,
1838 * GNUNET_SYSERR to close it (signal serious error)
1841 handle_p2p_put (void *cls,
1842 const struct GNUNET_PeerIdentity *other,
1843 const struct GNUNET_MessageHeader *message,
1844 struct GNUNET_TIME_Relative latency,
1847 const struct PutMessage *put;
1851 struct GNUNET_TIME_Absolute expiration;
1852 GNUNET_HashCode query;
1853 struct ProcessReplyClosure prq;
1855 msize = ntohs (message->size);
1856 if (msize < sizeof (struct PutMessage))
1859 return GNUNET_SYSERR;
1861 put = (const struct PutMessage*) message;
1862 dsize = msize - sizeof (struct PutMessage);
1863 type = ntohl (put->type);
1864 expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
1866 /* first, validate! */
1869 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1870 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1871 GNUNET_CRYPTO_hash (&put[1], dsize, &query);
1873 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1875 check_kblock ((const struct KBlock*) &put[1],
1878 return GNUNET_SYSERR;
1880 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1882 check_sblock ((const struct SBlock*) &put[1],
1886 return GNUNET_SYSERR;
1888 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
1889 // FIXME -- validate SKBLOCK!
1893 /* unknown block type */
1894 GNUNET_break_op (0);
1895 return GNUNET_SYSERR;
1899 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1900 "Received result for query `%s' from peer `%4s'\n",
1901 GNUNET_h2s (&query),
1902 GNUNET_i2s (other));
1904 /* now, lookup 'query' */
1905 prq.data = (const void*) &put[1];
1908 prq.expiration = expiration;
1910 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
1914 // FIXME: if migration is on and load is low,
1915 // queue to store data in datastore;
1916 // use "prq.priority" for that!
1921 /* **************************** P2P GET Handling ************************ */
1925 * We're processing (local) results for a search request
1926 * from another peer. Pass applicable results to the
1927 * peer and if we are done either clean up (operation
1928 * complete) or forward to other peers (more results possible).
1930 * @param cls our closure (struct LocalGetContext)
1931 * @param key key for the content
1932 * @param size number of bytes in data
1933 * @param data content stored
1934 * @param type type of the content
1935 * @param priority priority of the content
1936 * @param anonymity anonymity-level for the content
1937 * @param expiration expiration time for the content
1938 * @param uid unique identifier for the datum;
1939 * maybe 0 if no unique identifier is available
1942 process_local_reply (void *cls,
1943 const GNUNET_HashCode * key,
1949 struct GNUNET_TIME_Absolute
1953 struct PendingRequest *pr = cls;
1954 struct ProcessReplyClosure prq;
1955 GNUNET_HashCode dhash;
1956 GNUNET_HashCode mhash;
1957 GNUNET_HashCode query;
1962 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1963 "Done processing local replies, forwarding request to other peers.\n");
1966 if (pr->client_request_list != NULL)
1967 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
1969 /* no more results */
1970 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1971 pr->task = GNUNET_SCHEDULER_add_now (sched,
1972 &forward_request_task,
1976 if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
1979 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1980 "Found ONDEMAND block, performing on-demand encoding\n");
1983 GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
1984 anonymity, expiration, uid,
1985 &process_local_reply,
1987 GNUNET_FS_drq_get_next (GNUNET_YES);
1990 /* check for duplicates */
1991 GNUNET_CRYPTO_hash (data, size, &dhash);
1992 mingle_hash (&dhash,
1995 if ( (pr->bf != NULL) &&
1997 GNUNET_CONTAINER_bloomfilter_test (pr->bf,
2001 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2002 "Result from datastore filtered by bloomfilter (duplicate).\n");
2004 GNUNET_FS_drq_get_next (GNUNET_YES);
2008 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2009 "Found result for query `%s' in local datastore\n",
2012 pr->results_found++;
2013 if ( (pr->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
2014 (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
2015 (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) )
2020 pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
2024 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
2027 memset (&prq, 0, sizeof (prq));
2029 prq.expiration = expiration;
2031 if ( (type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) &&
2032 (GNUNET_OK != check_sblock ((const struct SBlock*) data,
2038 /* FIXME: consider removing the block? */
2039 GNUNET_FS_drq_get_next (GNUNET_YES);
2043 prq.priority = priority;
2044 process_reply (&prq, key, pr);
2046 if ( ( (pr->client_request_list == NULL) &&
2047 ( (GNUNET_YES == test_load_too_high()) ||
2048 (pr->results_found > 5 + 2 * pr->priority) ) ) ||
2049 (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK) )
2052 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2053 "Unique reply found or load too high, done with request\n");
2055 GNUNET_FS_drq_get_next (GNUNET_NO);
2058 GNUNET_FS_drq_get_next (GNUNET_YES);
2063 * The priority level imposes a bound on the maximum
2064 * value for the ttl that can be requested.
2066 * @param ttl_in requested ttl
2067 * @param prio given priority
2068 * @return ttl_in if ttl_in is below the limit,
2069 * otherwise the ttl-limit for the given priority
2072 bound_ttl (int32_t ttl_in, uint32_t prio)
2074 unsigned long long allowed;
2078 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
2079 if (ttl_in > allowed)
2081 if (allowed >= (1 << 30))
2090 * We've received a request with the specified priority. Bound it
2091 * according to how much we trust the given peer.
2093 * @param prio_in requested priority
2094 * @param cp the peer making the request
2095 * @return effective priority
2098 bound_priority (uint32_t prio_in,
2099 struct ConnectedPeer *cp)
2106 * Closure for 'check_duplicate_request'.
2108 struct CheckDuplicateRequestClosure
2111 * The new request we should check if it already exists.
2113 const struct PendingRequest *pr;
2116 * Existing request found by the checker, NULL if none.
2118 struct PendingRequest *have;
2123 * Iterator over entries in the 'query_request_map' that
2124 * tries to see if we have the same request pending from
2125 * the same peer already.
2127 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
2128 * @param key current key code (query, ignored, must match)
2129 * @param value value in the hash map (a 'struct PendingRequest'
2130 * that already exists)
2131 * @return GNUNET_YES if we should continue to
2132 * iterate (no match yet)
2133 * GNUNET_NO if not (match found).
2136 check_duplicate_request (void *cls,
2137 const GNUNET_HashCode * key,
2140 struct CheckDuplicateRequestClosure *cdc = cls;
2141 struct PendingRequest *have = value;
2143 if (cdc->pr->target_pid == have->target_pid)
2153 * Handle P2P "GET" request.
2155 * @param cls closure, always NULL
2156 * @param other the other peer involved (sender or receiver, NULL
2157 * for loopback messages where we are both sender and receiver)
2158 * @param message the actual message
2159 * @param latency reported latency of the connection with 'other'
2160 * @param distance reported distance (DV) to 'other'
2161 * @return GNUNET_OK to keep the connection open,
2162 * GNUNET_SYSERR to close it (signal serious error)
2165 handle_p2p_get (void *cls,
2166 const struct GNUNET_PeerIdentity *other,
2167 const struct GNUNET_MessageHeader *message,
2168 struct GNUNET_TIME_Relative latency,
2171 struct PendingRequest *pr;
2172 struct ConnectedPeer *cp;
2173 struct ConnectedPeer *cps;
2174 struct CheckDuplicateRequestClosure cdc;
2175 struct GNUNET_TIME_Relative timeout;
2177 const struct GetMessage *gm;
2179 const GNUNET_HashCode *opt;
2182 uint32_t ttl_decrement;
2187 msize = ntohs(message->size);
2188 if (msize < sizeof (struct GetMessage))
2190 GNUNET_break_op (0);
2191 return GNUNET_SYSERR;
2193 gm = (const struct GetMessage*) message;
2194 type = ntohl (gm->type);
2197 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2198 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2199 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
2200 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2203 GNUNET_break_op (0);
2204 return GNUNET_SYSERR;
2206 bm = ntohl (gm->hash_bitmap);
2214 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
2216 GNUNET_break_op (0);
2217 return GNUNET_SYSERR;
2219 opt = (const GNUNET_HashCode*) &gm[1];
2220 bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
2221 bm = ntohl (gm->hash_bitmap);
2222 if ( (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)) &&
2223 (ntohl (gm->type) == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) )
2225 GNUNET_break_op (0);
2226 return GNUNET_SYSERR;
2229 cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2230 &other->hashPubKey);
2231 GNUNET_assert (NULL != cps);
2232 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
2233 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2240 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
2241 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2242 "Failed to find RETURN-TO peer `%4s' in connection set. Dropping query.\n",
2243 GNUNET_i2s ((const struct GNUNET_PeerIdentity*) &opt[bits-1]));
2246 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2247 "Failed to find peer `%4s' in connection set. Dropping query.\n",
2248 GNUNET_i2s (other));
2250 /* FIXME: try connect? */
2253 /* note that we can really only check load here since otherwise
2254 peers could find out that we are overloaded by not being
2255 disconnected after sending us a malformed query... */
2256 if (GNUNET_YES == test_load_too_high ())
2259 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2260 "Dropping query from `%s', this peer is too busy.\n",
2261 GNUNET_i2s (other));
2267 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2268 "Received request for `%s' of type %u from peer `%4s'\n",
2269 GNUNET_h2s (&gm->query),
2270 (unsigned int) ntohl (gm->type),
2271 GNUNET_i2s (other));
2273 have_ns = (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE));
2274 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
2275 (have_ns ? sizeof(GNUNET_HashCode) : 0));
2277 pr->namespace = (GNUNET_HashCode*) &pr[1];
2279 pr->mingle = ntohl (gm->filter_mutator);
2280 if (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2281 memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
2282 else if (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)
2284 GNUNET_break_op (0);
2286 return GNUNET_SYSERR;
2288 if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
2289 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
2291 pr->anonymity_level = 1;
2292 pr->priority = bound_priority (ntohl (gm->priority), cps);
2293 pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
2294 pr->query = gm->query;
2295 /* decrement ttl (always) */
2296 ttl_decrement = 2 * TTL_DECREMENT +
2297 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2299 if ( (pr->ttl < 0) &&
2300 (pr->ttl - ttl_decrement > 0) )
2303 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2304 "Dropping query from `%s' due to TTL underflow.\n",
2305 GNUNET_i2s (other));
2307 /* integer underflow => drop (should be very rare)! */
2311 pr->ttl -= ttl_decrement;
2312 pr->start_time = GNUNET_TIME_absolute_get ();
2314 /* get bloom filter */
2317 pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
2320 pr->bf_size = bfsize;
2325 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2327 &check_duplicate_request,
2329 if (cdc.have != NULL)
2331 if (cdc.have->start_time.value + cdc.have->ttl >=
2332 pr->start_time.value + pr->ttl)
2334 /* existing request has higher TTL, drop new one! */
2335 cdc.have->priority += pr->priority;
2336 destroy_pending_request (pr);
2338 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2339 "Have existing request with higher TTL, dropping new request.\n",
2340 GNUNET_i2s (other));
2346 /* existing request has lower TTL, drop old one! */
2347 pr->priority += cdc.have->priority;
2348 /* Possible optimization: if we have applicable pending
2349 replies in 'cdc.have', we might want to move those over
2350 (this is a really rare special-case, so it is not clear
2351 that this would be worth it) */
2352 destroy_pending_request (cdc.have);
2353 /* keep processing 'pr'! */
2358 GNUNET_CONTAINER_multihashmap_put (query_request_map,
2361 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2362 GNUNET_CONTAINER_multihashmap_put (peer_request_map,
2365 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2367 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
2369 pr->start_time.value + pr->ttl);
2372 /* calculate change in traffic preference */
2373 preference = (double) pr->priority;
2374 if (preference < QUERY_BANDWIDTH_VALUE)
2375 preference = QUERY_BANDWIDTH_VALUE;
2376 cps->inc_preference += preference;
2378 /* process locally */
2379 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2380 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2381 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
2382 (pr->priority + 1));
2383 pr->drq = GNUNET_FS_drq_get (&gm->query,
2385 &process_local_reply,
2390 /* Are multiple results possible? If so, start processing remotely now! */
2393 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2394 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2395 /* only one result, wait for datastore */
2398 pr->task = GNUNET_SCHEDULER_add_now (sched,
2399 &forward_request_task,
2403 /* make sure we don't track too many requests */
2404 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
2406 pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
2407 destroy_pending_request (pr);
2413 /* **************************** CS GET Handling ************************ */
2417 * Handle START_SEARCH-message (search request from client).
2419 * @param cls closure
2420 * @param client identification of the client
2421 * @param message the actual message
2424 handle_start_search (void *cls,
2425 struct GNUNET_SERVER_Client *client,
2426 const struct GNUNET_MessageHeader *message)
2428 static GNUNET_HashCode all_zeros;
2429 const struct SearchMessage *sm;
2430 struct ClientList *cl;
2431 struct ClientRequestList *crl;
2432 struct PendingRequest *pr;
2437 msize = ntohs (message->size);
2438 if ( (msize < sizeof (struct SearchMessage)) ||
2439 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
2442 GNUNET_SERVER_receive_done (client,
2446 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
2447 sm = (const struct SearchMessage*) message;
2450 while ( (cl != NULL) &&
2451 (cl->client != client) )
2455 cl = GNUNET_malloc (sizeof (struct ClientList));
2456 cl->client = client;
2457 GNUNET_SERVER_client_keep (client);
2458 cl->next = client_list;
2461 type = ntohl (sm->type);
2464 case GNUNET_DATASTORE_BLOCKTYPE_ANY:
2465 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2466 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2467 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
2468 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2472 GNUNET_SERVER_receive_done (client,
2477 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2478 "Received request for `%s' of type %u from local client\n",
2479 GNUNET_h2s (&sm->query),
2480 (unsigned int) type);
2483 /* detect duplicate KBLOCK requests */
2484 if (type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK)
2487 while ( (crl != NULL) &&
2488 ( (0 != memcmp (&crl->req->query,
2490 sizeof (GNUNET_HashCode))) ||
2491 (crl->req->type != type) ) )
2496 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2497 "Have existing request, merging content-seen lists.\n");
2500 /* Duplicate request (used to send long list of
2501 known/blocked results); merge 'pr->replies_seen'
2502 and update bloom filter */
2503 GNUNET_array_grow (pr->replies_seen,
2504 pr->replies_seen_size,
2505 pr->replies_seen_off + sc);
2506 memcpy (&pr->replies_seen[pr->replies_seen_off],
2508 sc * sizeof (GNUNET_HashCode));
2509 pr->replies_seen_off += sc;
2511 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
2512 pr->bf = refresh_bloomfilter (pr->replies_seen_off,
2516 GNUNET_SERVER_receive_done (client,
2521 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
2522 ((type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)?sizeof(GNUNET_HashCode):0));
2523 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
2524 memset (crl, 0, sizeof (struct ClientRequestList));
2525 crl->client_list = cl;
2526 GNUNET_CONTAINER_DLL_insert (cl->rl_head,
2531 pr->client_request_list = crl;
2532 GNUNET_array_grow (pr->replies_seen,
2533 pr->replies_seen_size,
2535 memcpy (pr->replies_seen,
2537 sc * sizeof (GNUNET_HashCode));
2538 pr->replies_seen_off = sc;
2539 pr->anonymity_level = ntohl (sm->anonymity_level);
2540 pr->bf = refresh_bloomfilter (pr->replies_seen_off,
2544 pr->query = sm->query;
2547 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2548 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2549 if (0 != memcmp (&sm->target,
2551 sizeof (GNUNET_HashCode)))
2552 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
2554 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2555 pr->namespace = (GNUNET_HashCode*) &pr[1];
2556 memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
2561 GNUNET_CONTAINER_multihashmap_put (query_request_map,
2564 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2565 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2566 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* get on-demand blocks too! */
2567 pr->drq = GNUNET_FS_drq_get (&sm->query,
2569 &process_local_reply,
2571 GNUNET_TIME_UNIT_FOREVER_REL,
2576 /* **************************** Startup ************************ */
2580 * List of handlers for P2P messages
2581 * that we care about.
2583 static struct GNUNET_CORE_MessageHandler p2p_handlers[] =
2586 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
2588 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
2594 * List of handlers for the messages understood by this
2597 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2598 {&GNUNET_FS_handle_index_start, NULL,
2599 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
2600 {&GNUNET_FS_handle_index_list_get, NULL,
2601 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
2602 {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
2603 sizeof (struct UnindexMessage) },
2604 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
2611 * Process fs requests.
2613 * @param s scheduler to use
2614 * @param server the initialized server
2615 * @param c configuration to use
2618 main_init (struct GNUNET_SCHEDULER_Handle *s,
2619 struct GNUNET_SERVER_Handle *server,
2620 const struct GNUNET_CONFIGURATION_Handle *c)
2624 connected_peers = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2625 query_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2626 peer_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2627 requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2628 core = GNUNET_CORE_connect (sched,
2630 GNUNET_TIME_UNIT_FOREVER_REL,
2634 &peer_connect_handler,
2635 &peer_disconnect_handler,
2641 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2642 _("Failed to connect to `%s' service.\n"),
2644 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
2645 connected_peers = NULL;
2646 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
2647 query_request_map = NULL;
2648 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
2649 requests_by_expiration_heap = NULL;
2650 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
2651 peer_request_map = NULL;
2653 return GNUNET_SYSERR;
2655 GNUNET_SERVER_disconnect_notify (server,
2656 &handle_client_disconnect,
2658 GNUNET_SERVER_add_handlers (server, handlers);
2659 GNUNET_SCHEDULER_add_delayed (sched,
2660 GNUNET_TIME_UNIT_FOREVER_REL,
2668 * Process fs requests.
2670 * @param cls closure
2671 * @param sched scheduler to use
2672 * @param server the initialized server
2673 * @param cfg configuration to use
2677 struct GNUNET_SCHEDULER_Handle *sched,
2678 struct GNUNET_SERVER_Handle *server,
2679 const struct GNUNET_CONFIGURATION_Handle *cfg)
2681 if ( (GNUNET_OK != GNUNET_FS_drq_init (sched, cfg)) ||
2682 (GNUNET_OK != GNUNET_FS_indexing_init (sched, cfg)) ||
2683 (GNUNET_OK != main_init (sched, server, cfg)) )
2685 GNUNET_SCHEDULER_shutdown (sched);
2692 * The main function for the fs service.
2694 * @param argc number of arguments from the command line
2695 * @param argv command line arguments
2696 * @return 0 ok, 1 on error
2699 main (int argc, char *const *argv)
2701 return (GNUNET_OK ==
2702 GNUNET_SERVICE_run (argc,
2705 GNUNET_SERVICE_OPTION_NONE,
2706 &run, NULL)) ? 0 : 1;
2709 /* end of gnunet-service-fs.c */