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 * - track stats for hot-path routing
28 * - implement hot-path routing decision procedure
29 * - implement: bound_priority, test_load_too_high, validate_skblock
30 * - add content migration support (store locally)
35 #include "gnunet_constants.h"
36 #include "gnunet_core_service.h"
37 #include "gnunet_datastore_service.h"
38 #include "gnunet_peer_lib.h"
39 #include "gnunet_protocols.h"
40 #include "gnunet_signatures.h"
41 #include "gnunet_util_lib.h"
42 #include "gnunet-service-fs_drq.h"
43 #include "gnunet-service-fs_indexing.h"
46 #define DEBUG_FS GNUNET_YES
49 * Maximum number of outgoing messages we queue per peer.
50 * FIXME: set to a tiny value for testing; make configurable.
52 #define MAX_QUEUE_PER_PEER 2
56 * Maximum number of requests (from other peers) that we're
57 * willing to have pending at any given point in time.
58 * FIXME: set from configuration (and 32 is a tiny value for testing only).
60 static uint64_t max_pending_requests = 32;
64 * Information we keep for each pending reply. The
65 * actual message follows at the end of this struct.
67 struct PendingMessage;
71 * Function called upon completion of a transmission.
74 * @param pid ID of receiving peer, 0 on transmission error
76 typedef void (*TransmissionContinuation)(void * cls,
81 * Information we keep for each pending message (GET/PUT). The
82 * actual message follows at the end of this struct.
87 * This is a doubly-linked list of messages to the same peer.
89 struct PendingMessage *next;
92 * This is a doubly-linked list of messages to the same peer.
94 struct PendingMessage *prev;
97 * Entry in pending message list for this pending message.
99 struct PendingMessageList *pml;
102 * Function to call immediately once we have transmitted this
105 TransmissionContinuation cont;
113 * Size of the reply; actual reply message follows
114 * at the end of this struct.
119 * How important is this message for us?
127 * Information about a peer that we are connected to.
128 * We track data that is useful for determining which
129 * peers should receive our requests. We also keep
130 * a list of messages to transmit to this peer.
136 * List of the last clients for which this peer successfully
139 struct GNUNET_SERVER_Client *last_client_replies[CS2P_SUCCESS_LIST_SIZE];
142 * List of the last PIDs for which
143 * this peer successfully answered a query;
144 * We use 0 to indicate no successful reply.
146 GNUNET_PEER_Id last_p2p_replies[P2P_SUCCESS_LIST_SIZE];
149 * Average delay between sending the peer a request and
150 * getting a reply (only calculated over the requests for
151 * which we actually got a reply). Calculated
152 * as a moving average: new_delay = ((n-1)*last_delay+curr_delay) / n
154 struct GNUNET_TIME_Relative avg_delay;
157 * Handle for an active request for transmission to this
160 struct GNUNET_CORE_TransmitHandle *cth;
163 * Messages (replies, queries, content migration) we would like to
164 * send to this peer in the near future. Sorted by priority, head.
166 struct PendingMessage *pending_messages_head;
169 * Messages (replies, queries, content migration) we would like to
170 * send to this peer in the near future. Sorted by priority, tail.
172 struct PendingMessage *pending_messages_tail;
175 * Average priority of successful replies. Calculated
176 * as a moving average: new_avg = ((n-1)*last_avg+curr_prio) / n
181 * Increase in traffic preference still to be submitted
182 * to the core service for this peer. FIXME: double or 'uint64_t'?
184 double inc_preference;
187 * The peer's identity.
192 * Size of the linked list of 'pending_messages'.
194 unsigned int pending_requests;
197 * Which offset in "last_p2p_replies" will be updated next?
198 * (we go round-robin).
200 unsigned int last_p2p_replies_woff;
203 * Which offset in "last_client_replies" will be updated next?
204 * (we go round-robin).
206 unsigned int last_client_replies_woff;
212 * Information we keep for each pending request. We should try to
213 * keep this struct as small as possible since its memory consumption
214 * is key to how many requests we can have pending at once.
216 struct PendingRequest;
220 * Doubly-linked list of requests we are performing
221 * on behalf of the same client.
223 struct ClientRequestList
227 * This is a doubly-linked list.
229 struct ClientRequestList *next;
232 * This is a doubly-linked list.
234 struct ClientRequestList *prev;
237 * Request this entry represents.
239 struct PendingRequest *req;
242 * Client list this request belongs to.
244 struct ClientList *client_list;
250 * Replies to be transmitted to the client. The actual
251 * response message is allocated after this struct.
253 struct ClientResponseMessage
256 * This is a doubly-linked list.
258 struct ClientResponseMessage *next;
261 * This is a doubly-linked list.
263 struct ClientResponseMessage *prev;
266 * Client list entry this response belongs to.
268 struct ClientList *client_list;
271 * Number of bytes in the response.
278 * Linked list of clients we are performing requests
284 * This is a linked list.
286 struct ClientList *next;
289 * ID of a client making a request, NULL if this entry is for a
292 struct GNUNET_SERVER_Client *client;
295 * Head of list of requests performed on behalf
296 * of this client right now.
298 struct ClientRequestList *rl_head;
301 * Tail of list of requests performed on behalf
302 * of this client right now.
304 struct ClientRequestList *rl_tail;
307 * Head of linked list of responses.
309 struct ClientResponseMessage *res_head;
312 * Tail of linked list of responses.
314 struct ClientResponseMessage *res_tail;
317 * Context for sending replies.
319 struct GNUNET_CONNECTION_TransmitHandle *th;
325 * Doubly-linked list of messages we are performing
326 * due to a pending request.
328 struct PendingMessageList
332 * This is a doubly-linked list of messages on behalf of the same request.
334 struct PendingMessageList *next;
337 * This is a doubly-linked list of messages on behalf of the same request.
339 struct PendingMessageList *prev;
342 * Message this entry represents.
344 struct PendingMessage *pm;
347 * Request this entry belongs to.
349 struct PendingRequest *req;
352 * Peer this message is targeted for.
354 struct ConnectedPeer *target;
360 * Information we keep for each pending request. We should try to
361 * keep this struct as small as possible since its memory consumption
362 * is key to how many requests we can have pending at once.
364 struct PendingRequest
368 * If this request was made by a client, this is our entry in the
369 * client request list; otherwise NULL.
371 struct ClientRequestList *client_request_list;
374 * Entry of peer responsible for this entry (if this request
375 * was made by a peer).
377 struct ConnectedPeer *cp;
380 * If this is a namespace query, pointer to the hash of the public
381 * key of the namespace; otherwise NULL. Pointer will be to the
382 * end of this struct (so no need to free it).
384 const GNUNET_HashCode *namespace;
387 * Bloomfilter we use to filter out replies that we don't care about
388 * (anymore). NULL as long as we are interested in all replies.
390 struct GNUNET_CONTAINER_BloomFilter *bf;
393 * Context of our GNUNET_CORE_peer_change_preference call.
395 struct GNUNET_CORE_InformationRequestContext *irc;
398 * Hash code of all replies that we have seen so far (only valid
399 * if client is not NULL since we only track replies like this for
402 GNUNET_HashCode *replies_seen;
405 * Node in the heap representing this entry; NULL
406 * if we have no heap node.
408 struct GNUNET_CONTAINER_HeapNode *hnode;
411 * Head of list of messages being performed on behalf of this
414 struct PendingMessageList *pending_head;
417 * Tail of list of messages being performed on behalf of this
420 struct PendingMessageList *pending_tail;
423 * When did we first see this request (form this peer), or, if our
424 * client is initiating, when did we last initiate a search?
426 struct GNUNET_TIME_Absolute start_time;
429 * The query that this request is for.
431 GNUNET_HashCode query;
434 * The task responsible for transmitting queries
437 GNUNET_SCHEDULER_TaskIdentifier task;
440 * (Interned) Peer identifier that identifies a preferred target
443 GNUNET_PEER_Id target_pid;
446 * (Interned) Peer identifiers of peers that have already
447 * received our query for this content.
449 GNUNET_PEER_Id *used_pids;
452 * Our entry in the DRQ (non-NULL while we wait for our
453 * turn to interact with the local database).
455 struct DatastoreRequestQueue *drq;
458 * Size of the 'bf' (in bytes).
463 * Desired anonymity level; only valid for requests from a local client.
465 uint32_t anonymity_level;
468 * How many entries in "used_pids" are actually valid?
470 unsigned int used_pids_off;
473 * How long is the "used_pids" array?
475 unsigned int used_pids_size;
478 * Number of results found for this request.
480 unsigned int results_found;
483 * How many entries in "replies_seen" are actually valid?
485 unsigned int replies_seen_off;
488 * How long is the "replies_seen" array?
490 unsigned int replies_seen_size;
493 * Priority with which this request was made. If one of our clients
494 * made the request, then this is the current priority that we are
495 * using when initiating the request. This value is used when
496 * we decide to reward other peers with trust for providing a reply.
501 * Priority points left for us to spend when forwarding this request
504 uint32_t remaining_priority;
507 * Number to mingle hashes for bloom-filter tests with.
512 * TTL with which we saw this request (or, if we initiated, TTL that
513 * we used for the request).
518 * Type of the content that this request is for.
528 static struct GNUNET_SCHEDULER_Handle *sched;
533 static const struct GNUNET_CONFIGURATION_Handle *cfg;
536 * Map of peer identifiers to "struct ConnectedPeer" (for that peer).
538 static struct GNUNET_CONTAINER_MultiHashMap *connected_peers;
541 * Map of peer identifiers to "struct PendingRequest" (for that peer).
543 static struct GNUNET_CONTAINER_MultiHashMap *peer_request_map;
546 * Map of query identifiers to "struct PendingRequest" (for that query).
548 static struct GNUNET_CONTAINER_MultiHashMap *query_request_map;
551 * Heap with the request that will expire next at the top. Contains
552 * pointers of type "struct PendingRequest*"; these will *also* be
553 * aliased from the "requests_by_peer" data structures and the
554 * "requests_by_query" table. Note that requests from our clients
555 * don't expire and are thus NOT in the "requests_by_expiration"
556 * (or the "requests_by_peer" tables).
558 static struct GNUNET_CONTAINER_Heap *requests_by_expiration_heap;
561 * Linked list of clients we are currently processing requests for.
563 struct ClientList *client_list;
566 * Pointer to handle to the core service (points to NULL until we've
569 struct GNUNET_CORE_Handle *core;
572 /* ******************* clean up functions ************************ */
576 * We're done with a particular message list entry.
577 * Free all associated resources.
579 * @param pml entry to destroy
582 destroy_pending_message_list_entry (struct PendingMessageList *pml)
584 GNUNET_CONTAINER_DLL_remove (pml->req->pending_head,
585 pml->req->pending_tail,
587 GNUNET_CONTAINER_DLL_remove (pml->target->pending_messages_head,
588 pml->target->pending_messages_tail,
590 pml->target->pending_requests--;
591 GNUNET_free (pml->pm);
597 * Destroy the given pending message (and call the respective
600 * @param pm message to destroy
601 * @param tpid id of peer that the message was delivered to, or 0 for none
604 destroy_pending_message (struct PendingMessage *pm,
607 struct PendingMessageList *pml = pm->pml;
608 TransmissionContinuation cont;
611 GNUNET_assert (pml->pm == pm);
612 GNUNET_assert ( (tpid == 0) || (tpid == pml->target->pid) );
614 cont_cls = pm->cont_cls;
615 destroy_pending_message_list_entry (pml);
622 * We're done processing a particular request.
623 * Free all associated resources.
625 * @param pr request to destroy
628 destroy_pending_request (struct PendingRequest *pr)
630 struct GNUNET_PeerIdentity pid;
632 if (pr->hnode != NULL)
634 GNUNET_CONTAINER_heap_remove_node (requests_by_expiration_heap,
638 /* might have already been removed from map in 'process_reply' (if
639 there was a unique reply) or never inserted if it was a
640 duplicate; hence ignore the return value here */
641 (void) GNUNET_CONTAINER_multihashmap_remove (query_request_map,
646 GNUNET_FS_drq_get_cancel (pr->drq);
649 if (pr->client_request_list != NULL)
651 GNUNET_CONTAINER_DLL_remove (pr->client_request_list->client_list->rl_head,
652 pr->client_request_list->client_list->rl_tail,
653 pr->client_request_list);
654 GNUNET_free (pr->client_request_list);
655 pr->client_request_list = NULL;
659 GNUNET_PEER_resolve (pr->cp->pid,
661 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
668 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
673 GNUNET_CORE_peer_change_preference_cancel (pr->irc);
676 if (pr->replies_seen != NULL)
678 GNUNET_free (pr->replies_seen);
679 pr->replies_seen = NULL;
681 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
683 GNUNET_SCHEDULER_cancel (sched,
685 pr->task = GNUNET_SCHEDULER_NO_TASK;
687 while (NULL != pr->pending_head)
688 destroy_pending_message_list_entry (pr->pending_head);
689 GNUNET_PEER_change_rc (pr->target_pid, -1);
690 if (pr->used_pids != NULL)
692 GNUNET_PEER_decrement_rcs (pr->used_pids, pr->used_pids_off);
693 GNUNET_free (pr->used_pids);
694 pr->used_pids_off = 0;
695 pr->used_pids_size = 0;
696 pr->used_pids = NULL;
703 * Method called whenever a given peer connects.
705 * @param cls closure, not used
706 * @param peer peer identity this notification is about
707 * @param latency reported latency of the connection with 'other'
708 * @param distance reported distance (DV) to 'other'
711 peer_connect_handler (void *cls,
713 GNUNET_PeerIdentity * peer,
714 struct GNUNET_TIME_Relative latency,
717 struct ConnectedPeer *cp;
719 cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
720 cp->pid = GNUNET_PEER_intern (peer);
721 GNUNET_CONTAINER_multihashmap_put (connected_peers,
724 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
729 * Free (each) request made by the peer.
731 * @param cls closure, points to peer that the request belongs to
732 * @param key current key code
733 * @param value value in the hash map
734 * @return GNUNET_YES (we should continue to iterate)
737 destroy_request (void *cls,
738 const GNUNET_HashCode * key,
741 const struct GNUNET_PeerIdentity * peer = cls;
742 struct PendingRequest *pr = value;
744 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
747 destroy_pending_request (pr);
753 * Method called whenever a peer disconnects.
755 * @param cls closure, not used
756 * @param peer peer identity this notification is about
759 peer_disconnect_handler (void *cls,
761 GNUNET_PeerIdentity * peer)
763 struct ConnectedPeer *cp;
764 struct PendingMessage *pm;
767 GNUNET_CONTAINER_multihashmap_get_multiple (peer_request_map,
771 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
775 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
777 if (NULL != cp->last_client_replies[i])
779 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
780 cp->last_client_replies[i] = NULL;
783 GNUNET_CONTAINER_multihashmap_remove (connected_peers,
786 GNUNET_PEER_change_rc (cp->pid, -1);
787 GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
789 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
790 while (NULL != (pm = cp->pending_messages_head))
791 destroy_pending_message (pm, 0 /* delivery failed */);
792 GNUNET_break (0 == cp->pending_requests);
798 * Iterator over hash map entries that removes all occurences
799 * of the given 'client' from the 'last_client_replies' of the
800 * given connected peer.
802 * @param cls closure, the 'struct GNUNET_SERVER_Client*' to remove
803 * @param key current key code (unused)
804 * @param value value in the hash map (the 'struct ConnectedPeer*' to change)
805 * @return GNUNET_YES (we should continue to iterate)
808 remove_client_from_last_client_replies (void *cls,
809 const GNUNET_HashCode * key,
812 struct GNUNET_SERVER_Client *client = cls;
813 struct ConnectedPeer *cp = value;
816 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
818 if (cp->last_client_replies[i] == client)
820 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
821 cp->last_client_replies[i] = NULL;
829 * A client disconnected. Remove all of its pending queries.
831 * @param cls closure, NULL
832 * @param client identification of the client
835 handle_client_disconnect (void *cls,
836 struct GNUNET_SERVER_Client
839 struct ClientList *pos;
840 struct ClientList *prev;
841 struct ClientRequestList *rcl;
842 struct ClientResponseMessage *creply;
848 while ( (NULL != pos) &&
849 (pos->client != client) )
855 return; /* no requests pending for this client */
856 while (NULL != (rcl = pos->rl_head))
857 destroy_pending_request (rcl->req);
859 client_list = pos->next;
861 prev->next = pos->next;
864 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
867 while (NULL != (creply = pos->res_head))
869 GNUNET_CONTAINER_DLL_remove (pos->res_head,
872 GNUNET_free (creply);
874 GNUNET_SERVER_client_drop (pos->client);
876 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
877 &remove_client_from_last_client_replies,
883 * Iterator to free peer entries.
885 * @param cls closure, unused
886 * @param key current key code
887 * @param value value in the hash map (peer entry)
888 * @return GNUNET_YES (we should continue to iterate)
891 clean_peer (void *cls,
892 const GNUNET_HashCode * key,
895 peer_disconnect_handler (NULL, (const struct GNUNET_PeerIdentity*) key);
901 * Task run during shutdown.
907 shutdown_task (void *cls,
908 const struct GNUNET_SCHEDULER_TaskContext *tc)
910 while (client_list != NULL)
911 handle_client_disconnect (NULL,
912 client_list->client);
913 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
916 GNUNET_break (0 == GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap));
917 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
918 requests_by_expiration_heap = 0;
919 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
920 connected_peers = NULL;
921 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (query_request_map));
922 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
923 query_request_map = NULL;
924 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (peer_request_map));
925 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
926 peer_request_map = NULL;
927 GNUNET_assert (NULL != core);
928 GNUNET_CORE_disconnect (core);
935 /* ******************* Utility functions ******************** */
939 * Transmit the given message by copying it to the target buffer
940 * "buf". "buf" will be NULL and "size" zero if the socket was closed
941 * for writing in the meantime. In that case, do nothing
942 * (the disconnect or shutdown handler will take care of the rest).
943 * If we were able to transmit messages and there are still more
944 * pending, ask core again for further calls to this function.
946 * @param cls closure, pointer to the 'struct ConnectedPeer*'
947 * @param size number of bytes available in buf
948 * @param buf where the callee should write the message
949 * @return number of bytes written to buf
952 transmit_to_peer (void *cls,
953 size_t size, void *buf)
955 struct ConnectedPeer *cp = cls;
957 struct GNUNET_PeerIdentity pid;
958 struct PendingMessage *pm;
965 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
966 "Dropping message, core too busy.\n");
971 while ( (NULL != (pm = cp->pending_messages_head) ) &&
972 (pm->msize <= size) )
974 memcpy (&cbuf[msize], &pm[1], pm->msize);
977 destroy_pending_message (pm, cp->pid);
981 GNUNET_PEER_resolve (cp->pid,
983 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
985 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
992 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
993 "Transmitting %u bytes to peer %u.\n",
1002 * Add a message to the set of pending messages for the given peer.
1004 * @param cp peer to send message to
1005 * @param pm message to queue
1006 * @param pr request on which behalf this message is being queued
1009 add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
1010 struct PendingMessage *pm,
1011 struct PendingRequest *pr)
1013 struct PendingMessage *pos;
1014 struct PendingMessageList *pml;
1015 struct GNUNET_PeerIdentity pid;
1017 GNUNET_assert (pm->next == NULL);
1018 GNUNET_assert (pm->pml == NULL);
1019 pml = GNUNET_malloc (sizeof (struct PendingMessageList));
1024 GNUNET_CONTAINER_DLL_insert (pr->pending_head,
1027 pos = cp->pending_messages_head;
1028 while ( (pos != NULL) &&
1029 (pm->priority < pos->priority) )
1031 GNUNET_CONTAINER_DLL_insert_after (cp->pending_messages_head,
1032 cp->pending_messages_tail,
1035 cp->pending_requests++;
1036 if (cp->pending_requests > MAX_QUEUE_PER_PEER)
1037 destroy_pending_message (cp->pending_messages_tail, 0);
1038 if (cp->cth == NULL)
1040 /* need to schedule transmission */
1041 GNUNET_PEER_resolve (cp->pid, &pid);
1042 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1043 cp->pending_messages_head->priority,
1044 GNUNET_TIME_UNIT_FOREVER_REL,
1046 cp->pending_messages_head->msize,
1050 if (cp->cth == NULL)
1053 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1054 "Failed to schedule transmission with core!\n");
1056 /* FIXME: call stats (rare, bad case) */
1062 * Mingle hash with the mingle_number to produce different bits.
1065 mingle_hash (const GNUNET_HashCode * in,
1066 int32_t mingle_number,
1067 GNUNET_HashCode * hc)
1071 GNUNET_CRYPTO_hash (&mingle_number,
1074 GNUNET_CRYPTO_hash_xor (&m, in, hc);
1079 * Test if the load on this peer is too high
1080 * to even consider processing the query at
1083 * @return GNUNET_YES if the load is too high, GNUNET_NO otherwise
1086 test_load_too_high ()
1088 return GNUNET_NO; // FIXME
1092 /* ******************* Pending Request Refresh Task ******************** */
1096 * Function called after we either failed or succeeded
1097 * at transmitting a query to a peer.
1099 * @param cls the requests "struct PendingRequest*"
1100 * @param tpid ID of receiving peer, 0 on transmission error
1103 transmit_query_continuation (void *cls,
1104 GNUNET_PEER_Id tpid)
1106 struct PendingRequest *pr = cls;
1110 GNUNET_PEER_change_rc (tpid, 1);
1111 if (pr->used_pids_off == pr->used_pids_size)
1112 GNUNET_array_grow (pr->used_pids,
1114 pr->used_pids_size * 2 + 2);
1115 pr->used_pids[pr->used_pids_off++] = tpid;
1120 * How many bytes should a bloomfilter be if we have already seen
1121 * entry_count responses? Note that BLOOMFILTER_K gives us the number
1122 * of bits set per entry. Furthermore, we should not re-size the
1123 * filter too often (to keep it cheap).
1125 * Since other peers will also add entries but not resize the filter,
1126 * we should generally pick a slightly larger size than what the
1127 * strict math would suggest.
1129 * @return must be a power of two and smaller or equal to 2^15.
1132 compute_bloomfilter_size (unsigned int entry_count)
1135 unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
1136 uint16_t max = 1 << 15;
1138 if (entry_count > max)
1141 while ((size < max) && (size < ideal))
1150 * Recalculate our bloom filter for filtering replies.
1152 * @param count number of entries we are filtering right now
1153 * @param mingle set to our new mingling value
1154 * @param bf_size set to the size of the bloomfilter
1155 * @param entries the entries to filter
1156 * @return updated bloomfilter, NULL for none
1158 static struct GNUNET_CONTAINER_BloomFilter *
1159 refresh_bloomfilter (unsigned int count,
1162 const GNUNET_HashCode *entries)
1164 struct GNUNET_CONTAINER_BloomFilter *bf;
1167 GNUNET_HashCode mhash;
1171 nsize = compute_bloomfilter_size (count);
1172 *mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
1174 bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1177 for (i=0;i<count;i++)
1179 mingle_hash (&entries[i], *mingle, &mhash);
1180 GNUNET_CONTAINER_bloomfilter_add (bf, &mhash);
1187 * We use a random delay to make the timing of requests less
1188 * predictable. This function returns such a random delay.
1190 * FIXME: make schedule dependent on the specifics of the request?
1191 * Or bandwidth and number of connected peers and load?
1193 * @return random delay to use for some request, between 0 and TTL_DECREMENT ms
1195 static struct GNUNET_TIME_Relative
1196 get_processing_delay ()
1198 return GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1199 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1205 * Function called after we've tried to reserve a certain amount of
1206 * bandwidth for a reply. Check if we succeeded and if so send our
1209 * @param cls the requests "struct PendingRequest*"
1210 * @param peer identifies the peer
1211 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1212 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1213 * @param amount set to the amount that was actually reserved or unreserved
1214 * @param preference current traffic preference for the given peer
1217 target_reservation_cb (void *cls,
1219 GNUNET_PeerIdentity * peer,
1220 unsigned int bpm_in,
1221 unsigned int bpm_out,
1223 uint64_t preference)
1225 struct PendingRequest *pr = cls;
1226 struct ConnectedPeer *cp;
1227 struct PendingMessage *pm;
1228 struct GetMessage *gm;
1229 GNUNET_HashCode *ext;
1237 GNUNET_assert (peer != NULL);
1238 // (3) transmit, update ttl/priority
1239 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1243 /* Peer must have just left */
1245 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1246 "Selected peer disconnected!\n");
1250 no_route = GNUNET_NO;
1251 /* FIXME: check against DBLOCK_SIZE and possibly return
1252 amount to reserve; however, this also needs to work
1253 with testcases which currently start out with a far
1254 too low per-peer bw limit, so they would never send
1255 anything. Big issue. */
1261 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1262 "Failed to reserve bandwidth for reply (got %d/%u bytes only)!\n",
1266 return; /* this target round failed */
1268 /* FIXME: if we are "quite" busy, we may still want to skip
1269 this round; need more load detection code! */
1270 no_route = GNUNET_YES;
1273 /* build message and insert message into priority queue */
1275 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1276 "Forwarding request to `%4s'!\n",
1281 if (GNUNET_YES == no_route)
1283 bm |= GET_MESSAGE_BIT_RETURN_TO;
1286 if (pr->namespace != NULL)
1288 bm |= GET_MESSAGE_BIT_SKS_NAMESPACE;
1291 if (pr->target_pid != 0)
1293 bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
1296 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
1297 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1298 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1300 gm = (struct GetMessage*) &pm[1];
1301 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
1302 gm->header.size = htons (msize);
1303 gm->type = htonl (pr->type);
1304 pr->remaining_priority /= 2;
1305 gm->priority = htonl (pr->remaining_priority);
1306 gm->ttl = htonl (pr->ttl);
1307 gm->filter_mutator = htonl(pr->mingle);
1308 gm->hash_bitmap = htonl (bm);
1309 gm->query = pr->query;
1310 ext = (GNUNET_HashCode*) &gm[1];
1312 if (GNUNET_YES == no_route)
1313 GNUNET_PEER_resolve (pr->cp->pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1314 if (pr->namespace != NULL)
1315 memcpy (&ext[k++], pr->namespace, sizeof (GNUNET_HashCode));
1316 if (pr->target_pid != 0)
1317 GNUNET_PEER_resolve (pr->target_pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1318 bfdata = (char *) &ext[k];
1320 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
1323 pm->cont = &transmit_query_continuation;
1325 add_to_pending_messages_for_peer (cp, pm, pr);
1330 * Closure used for "target_peer_select_cb".
1332 struct PeerSelectionContext
1335 * The request for which we are selecting
1338 struct PendingRequest *pr;
1341 * Current "prime" target.
1343 struct GNUNET_PeerIdentity target;
1346 * How much do we like this target?
1348 double target_score;
1354 * Function called for each connected peer to determine
1355 * which one(s) would make good targets for forwarding.
1357 * @param cls closure (struct PeerSelectionContext)
1358 * @param key current key code (peer identity)
1359 * @param value value in the hash map (struct ConnectedPeer)
1360 * @return GNUNET_YES if we should continue to
1365 target_peer_select_cb (void *cls,
1366 const GNUNET_HashCode * key,
1369 struct PeerSelectionContext *psc = cls;
1370 struct ConnectedPeer *cp = value;
1371 struct PendingRequest *pr = psc->pr;
1375 /* 1) check if we have already (recently) forwarded to this peer */
1376 for (i=0;i<pr->used_pids_off;i++)
1377 if (pr->used_pids[i] == cp->pid)
1378 return GNUNET_YES; /* skip */
1379 // 2) calculate how much we'd like to forward to this peer
1380 score = 42; // FIXME!
1381 // FIXME: also need API to gather data on responsiveness
1382 // of this peer (we have fields for that in 'cp', but
1383 // they are never set!)
1385 /* store best-fit in closure */
1386 if (score > psc->target_score)
1388 psc->target_score = score;
1389 psc->target.hashPubKey = *key;
1396 * We're processing a GET request from another peer and have decided
1397 * to forward it to other peers. This function is called periodically
1398 * and should forward the request to other peers until we have all
1399 * possible replies. If we have transmitted the *only* reply to
1400 * the initiator we should destroy the pending request. If we have
1401 * many replies in the queue to the initiator, we should delay sending
1402 * out more queries until the reply queue has shrunk some.
1404 * @param cls our "struct ProcessGetContext *"
1408 forward_request_task (void *cls,
1409 const struct GNUNET_SCHEDULER_TaskContext *tc)
1411 struct PendingRequest *pr = cls;
1412 struct PeerSelectionContext psc;
1413 struct ConnectedPeer *cp;
1415 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1416 get_processing_delay (),
1417 &forward_request_task,
1419 if (pr->irc != NULL)
1420 return; /* previous request still pending */
1421 /* (1) select target */
1423 psc.target_score = DBL_MIN;
1424 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1425 &target_peer_select_cb,
1427 if (psc.target_score == DBL_MIN)
1430 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1431 "No peer selected for forwarding!\n");
1433 return; /* nobody selected */
1436 /* (2) reserve reply bandwidth */
1437 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1438 &psc.target.hashPubKey);
1439 pr->irc = GNUNET_CORE_peer_change_preference (sched, cfg,
1441 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1442 (uint32_t) -1 /* no limit */,
1444 (uint64_t) cp->inc_preference,
1445 &target_reservation_cb,
1447 cp->inc_preference = 0.0;
1451 /* **************************** P2P PUT Handling ************************ */
1455 * Function called after we either failed or succeeded
1456 * at transmitting a reply to a peer.
1458 * @param cls the requests "struct PendingRequest*"
1459 * @param tpid ID of receiving peer, 0 on transmission error
1462 transmit_reply_continuation (void *cls,
1463 GNUNET_PEER_Id tpid)
1465 struct PendingRequest *pr = cls;
1469 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1470 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1471 /* only one reply expected, done with the request! */
1472 destroy_pending_request (pr);
1474 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1475 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1485 * Check if the given KBlock is well-formed.
1487 * @param kb the kblock data (or at least "dsize" bytes claiming to be one)
1488 * @param dsize size of "kb" in bytes; check for < sizeof(struct KBlock)!
1489 * @param query where to store the query that this block answers
1490 * @return GNUNET_OK if this is actually a well-formed KBlock
1493 check_kblock (const struct KBlock *kb,
1495 GNUNET_HashCode *query)
1497 if (dsize < sizeof (struct KBlock))
1499 GNUNET_break_op (0);
1500 return GNUNET_SYSERR;
1502 if (dsize - sizeof (struct KBlock) !=
1503 ntohs (kb->purpose.size)
1504 - sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose)
1505 - sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) )
1507 GNUNET_break_op (0);
1508 return GNUNET_SYSERR;
1511 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_KBLOCK,
1516 GNUNET_break_op (0);
1517 return GNUNET_SYSERR;
1520 GNUNET_CRYPTO_hash (&kb->keyspace,
1521 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1528 * Check if the given SBlock is well-formed.
1530 * @param sb the sblock data (or at least "dsize" bytes claiming to be one)
1531 * @param dsize size of "kb" in bytes; check for < sizeof(struct SBlock)!
1532 * @param query where to store the query that this block answers
1533 * @param namespace where to store the namespace that this block belongs to
1534 * @return GNUNET_OK if this is actually a well-formed SBlock
1537 check_sblock (const struct SBlock *sb,
1539 GNUNET_HashCode *query,
1540 GNUNET_HashCode *namespace)
1542 if (dsize < sizeof (struct SBlock))
1544 GNUNET_break_op (0);
1545 return GNUNET_SYSERR;
1548 ntohs (sb->purpose.size) + sizeof (struct GNUNET_CRYPTO_RsaSignature))
1550 GNUNET_break_op (0);
1551 return GNUNET_SYSERR;
1554 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_SBLOCK,
1559 GNUNET_break_op (0);
1560 return GNUNET_SYSERR;
1563 *query = sb->identifier;
1564 if (namespace != NULL)
1565 GNUNET_CRYPTO_hash (&sb->subspace,
1566 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1573 * Transmit the given message by copying it to the target buffer
1574 * "buf". "buf" will be NULL and "size" zero if the socket was closed
1575 * for writing in the meantime. In that case, do nothing
1576 * (the disconnect or shutdown handler will take care of the rest).
1577 * If we were able to transmit messages and there are still more
1578 * pending, ask core again for further calls to this function.
1580 * @param cls closure, pointer to the 'struct ClientList*'
1581 * @param size number of bytes available in buf
1582 * @param buf where the callee should write the message
1583 * @return number of bytes written to buf
1586 transmit_to_client (void *cls,
1587 size_t size, void *buf)
1589 struct ClientList *cl = cls;
1591 struct ClientResponseMessage *creply;
1598 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1599 "Not sending reply, client communication problem.\n");
1604 while ( (NULL != (creply = cl->res_head) ) &&
1605 (creply->msize <= size) )
1607 memcpy (&cbuf[msize], &creply[1], creply->msize);
1608 msize += creply->msize;
1609 size -= creply->msize;
1610 GNUNET_CONTAINER_DLL_remove (cl->res_head,
1613 GNUNET_free (creply);
1616 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
1618 GNUNET_TIME_UNIT_FOREVER_REL,
1619 &transmit_to_client,
1622 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1623 "Transmitted %u bytes to client\n",
1624 (unsigned int) msize);
1631 * Closure for "process_reply" function.
1633 struct ProcessReplyClosure
1636 * The data for the reply.
1640 // FIXME: add 'struct ConnectedPeer' to track 'last_xxx_replies' here!
1643 * When the reply expires.
1645 struct GNUNET_TIME_Absolute expiration;
1653 * Namespace that this reply belongs to
1654 * (if it is of type SBLOCK).
1656 GNUNET_HashCode namespace;
1659 * Type of the block.
1664 * How much was this reply worth to us?
1671 * We have received a reply; handle it!
1673 * @param cls response (struct ProcessReplyClosure)
1674 * @param key our query
1675 * @param value value in the hash map (info about the query)
1676 * @return GNUNET_YES (we should continue to iterate)
1679 process_reply (void *cls,
1680 const GNUNET_HashCode * key,
1683 struct ProcessReplyClosure *prq = cls;
1684 struct PendingRequest *pr = value;
1685 struct PendingMessage *reply;
1686 struct ClientResponseMessage *creply;
1687 struct ClientList *cl;
1688 struct PutMessage *pm;
1689 struct ConnectedPeer *cp;
1690 GNUNET_HashCode chash;
1691 GNUNET_HashCode mhash;
1697 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1698 "Matched result for query `%s' with pending request\n",
1701 do_remove = GNUNET_NO;
1702 GNUNET_CRYPTO_hash (prq->data,
1707 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1708 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1709 /* only possible reply, stop requesting! */
1710 while (NULL != pr->pending_head)
1711 destroy_pending_message_list_entry (pr->pending_head);
1712 if (pr->drq != NULL)
1714 GNUNET_FS_drq_get_cancel (pr->drq);
1717 do_remove = GNUNET_YES;
1719 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1720 if (0 != memcmp (pr->namespace,
1722 sizeof (GNUNET_HashCode)))
1723 return GNUNET_YES; /* wrong namespace */
1724 /* then: fall-through! */
1725 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1728 mingle_hash (&chash, pr->mingle, &mhash);
1729 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
1731 return GNUNET_YES; /* duplicate */
1732 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
1735 if (pr->client_request_list != NULL)
1737 if (pr->replies_seen_size == pr->replies_seen_off)
1739 GNUNET_array_grow (pr->replies_seen,
1740 pr->replies_seen_size,
1741 pr->replies_seen_size * 2 + 4);
1743 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
1744 pr->bf = refresh_bloomfilter (pr->replies_seen_off,
1749 pr->replies_seen[pr->replies_seen_off++] = chash;
1753 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
1754 // FIXME: any checks against duplicates for SKBlocks?
1760 prio = pr->priority;
1761 prq->priority += pr->remaining_priority;
1762 pr->remaining_priority = 0;
1763 if (pr->client_request_list != NULL)
1766 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1767 "Transmitting result for query `%s' to local client\n",
1770 cl = pr->client_request_list->client_list;
1771 msize = sizeof (struct PutMessage) + prq->size;
1772 creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
1773 creply->msize = msize;
1774 creply->client_list = cl;
1775 GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
1779 pm = (struct PutMessage*) &creply[1];
1780 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
1781 pm->header.size = htons (msize);
1782 pm->type = htonl (prq->type);
1783 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
1784 memcpy (&pm[1], prq->data, prq->size);
1786 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
1788 GNUNET_TIME_UNIT_FOREVER_REL,
1789 &transmit_to_client,
1791 GNUNET_break (cl->th != NULL);
1797 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1798 "Transmitting result for query `%s' to other peer (PID=%u)\n",
1800 (unsigned int) cp->pid);
1802 msize = sizeof (struct PutMessage) + prq->size;
1803 reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
1804 reply->cont = &transmit_reply_continuation;
1805 reply->cont_cls = pr;
1806 reply->msize = msize;
1807 reply->priority = (uint32_t) -1; /* send replies first! */
1808 pm = (struct PutMessage*) &reply[1];
1809 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
1810 pm->header.size = htons (msize);
1811 pm->type = htonl (prq->type);
1812 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
1813 memcpy (&pm[1], prq->data, prq->size);
1814 add_to_pending_messages_for_peer (cp, reply, pr);
1816 if (GNUNET_YES == do_remove)
1817 GNUNET_break (GNUNET_YES ==
1818 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
1822 // FIXME: implement hot-path routing statistics keeping!
1828 * Handle P2P "PUT" message.
1830 * @param cls closure, always NULL
1831 * @param other the other peer involved (sender or receiver, NULL
1832 * for loopback messages where we are both sender and receiver)
1833 * @param message the actual message
1834 * @param latency reported latency of the connection with 'other'
1835 * @param distance reported distance (DV) to 'other'
1836 * @return GNUNET_OK to keep the connection open,
1837 * GNUNET_SYSERR to close it (signal serious error)
1840 handle_p2p_put (void *cls,
1841 const struct GNUNET_PeerIdentity *other,
1842 const struct GNUNET_MessageHeader *message,
1843 struct GNUNET_TIME_Relative latency,
1846 const struct PutMessage *put;
1850 struct GNUNET_TIME_Absolute expiration;
1851 GNUNET_HashCode query;
1852 struct ProcessReplyClosure prq;
1854 msize = ntohs (message->size);
1855 if (msize < sizeof (struct PutMessage))
1858 return GNUNET_SYSERR;
1860 put = (const struct PutMessage*) message;
1861 dsize = msize - sizeof (struct PutMessage);
1862 type = ntohl (put->type);
1863 expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
1865 /* first, validate! */
1868 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1869 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1870 GNUNET_CRYPTO_hash (&put[1], dsize, &query);
1872 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1874 check_kblock ((const struct KBlock*) &put[1],
1877 return GNUNET_SYSERR;
1879 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1881 check_sblock ((const struct SBlock*) &put[1],
1885 return GNUNET_SYSERR;
1887 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
1888 // FIXME -- validate SKBLOCK!
1892 /* unknown block type */
1893 GNUNET_break_op (0);
1894 return GNUNET_SYSERR;
1898 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1899 "Received result for query `%s' from peer `%4s'\n",
1900 GNUNET_h2s (&query),
1901 GNUNET_i2s (other));
1903 /* now, lookup 'query' */
1904 prq.data = (const void*) &put[1];
1907 prq.expiration = expiration;
1909 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
1913 // FIXME: if migration is on and load is low,
1914 // queue to store data in datastore;
1915 // use "prq.priority" for that!
1920 /* **************************** P2P GET Handling ************************ */
1924 * We're processing (local) results for a search request
1925 * from another peer. Pass applicable results to the
1926 * peer and if we are done either clean up (operation
1927 * complete) or forward to other peers (more results possible).
1929 * @param cls our closure (struct LocalGetContext)
1930 * @param key key for the content
1931 * @param size number of bytes in data
1932 * @param data content stored
1933 * @param type type of the content
1934 * @param priority priority of the content
1935 * @param anonymity anonymity-level for the content
1936 * @param expiration expiration time for the content
1937 * @param uid unique identifier for the datum;
1938 * maybe 0 if no unique identifier is available
1941 process_local_reply (void *cls,
1942 const GNUNET_HashCode * key,
1948 struct GNUNET_TIME_Absolute
1952 struct PendingRequest *pr = cls;
1953 struct ProcessReplyClosure prq;
1954 GNUNET_HashCode dhash;
1955 GNUNET_HashCode mhash;
1956 GNUNET_HashCode query;
1961 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1962 "Done processing local replies, forwarding request to other peers.\n");
1965 if (pr->client_request_list != NULL)
1966 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
1968 /* no more results */
1969 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1970 pr->task = GNUNET_SCHEDULER_add_now (sched,
1971 &forward_request_task,
1975 if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
1978 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1979 "Found ONDEMAND block, performing on-demand encoding\n");
1982 GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
1983 anonymity, expiration, uid,
1984 &process_local_reply,
1986 GNUNET_FS_drq_get_next (GNUNET_YES);
1989 /* check for duplicates */
1990 GNUNET_CRYPTO_hash (data, size, &dhash);
1991 mingle_hash (&dhash,
1994 if ( (pr->bf != NULL) &&
1996 GNUNET_CONTAINER_bloomfilter_test (pr->bf,
2000 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2001 "Result from datastore filtered by bloomfilter (duplicate).\n");
2003 GNUNET_FS_drq_get_next (GNUNET_YES);
2007 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2008 "Found result for query `%s' in local datastore\n",
2011 pr->results_found++;
2012 if ( (pr->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
2013 (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
2014 (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) )
2019 pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
2023 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
2026 memset (&prq, 0, sizeof (prq));
2028 prq.expiration = expiration;
2030 if ( (type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) &&
2031 (GNUNET_OK != check_sblock ((const struct SBlock*) data,
2037 /* FIXME: consider removing the block? */
2038 GNUNET_FS_drq_get_next (GNUNET_YES);
2042 prq.priority = priority;
2043 process_reply (&prq, key, pr);
2045 if ( ( (pr->client_request_list == NULL) &&
2046 ( (GNUNET_YES == test_load_too_high()) ||
2047 (pr->results_found > 5 + 2 * pr->priority) ) ) ||
2048 (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK) )
2051 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2052 "Unique reply found or load too high, done with request\n");
2054 GNUNET_FS_drq_get_next (GNUNET_NO);
2057 GNUNET_FS_drq_get_next (GNUNET_YES);
2062 * The priority level imposes a bound on the maximum
2063 * value for the ttl that can be requested.
2065 * @param ttl_in requested ttl
2066 * @param prio given priority
2067 * @return ttl_in if ttl_in is below the limit,
2068 * otherwise the ttl-limit for the given priority
2071 bound_ttl (int32_t ttl_in, uint32_t prio)
2073 unsigned long long allowed;
2077 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
2078 if (ttl_in > allowed)
2080 if (allowed >= (1 << 30))
2089 * We've received a request with the specified priority. Bound it
2090 * according to how much we trust the given peer.
2092 * @param prio_in requested priority
2093 * @param cp the peer making the request
2094 * @return effective priority
2097 bound_priority (uint32_t prio_in,
2098 struct ConnectedPeer *cp)
2105 * Closure for 'check_duplicate_request'.
2107 struct CheckDuplicateRequestClosure
2110 * The new request we should check if it already exists.
2112 const struct PendingRequest *pr;
2115 * Existing request found by the checker, NULL if none.
2117 struct PendingRequest *have;
2122 * Iterator over entries in the 'query_request_map' that
2123 * tries to see if we have the same request pending from
2124 * the same peer already.
2126 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
2127 * @param key current key code (query, ignored, must match)
2128 * @param value value in the hash map (a 'struct PendingRequest'
2129 * that already exists)
2130 * @return GNUNET_YES if we should continue to
2131 * iterate (no match yet)
2132 * GNUNET_NO if not (match found).
2135 check_duplicate_request (void *cls,
2136 const GNUNET_HashCode * key,
2139 struct CheckDuplicateRequestClosure *cdc = cls;
2140 struct PendingRequest *have = value;
2142 if (cdc->pr->target_pid == have->target_pid)
2152 * Handle P2P "GET" request.
2154 * @param cls closure, always NULL
2155 * @param other the other peer involved (sender or receiver, NULL
2156 * for loopback messages where we are both sender and receiver)
2157 * @param message the actual message
2158 * @param latency reported latency of the connection with 'other'
2159 * @param distance reported distance (DV) to 'other'
2160 * @return GNUNET_OK to keep the connection open,
2161 * GNUNET_SYSERR to close it (signal serious error)
2164 handle_p2p_get (void *cls,
2165 const struct GNUNET_PeerIdentity *other,
2166 const struct GNUNET_MessageHeader *message,
2167 struct GNUNET_TIME_Relative latency,
2170 struct PendingRequest *pr;
2171 struct ConnectedPeer *cp;
2172 struct ConnectedPeer *cps;
2173 struct CheckDuplicateRequestClosure cdc;
2174 struct GNUNET_TIME_Relative timeout;
2176 const struct GetMessage *gm;
2178 const GNUNET_HashCode *opt;
2181 uint32_t ttl_decrement;
2186 msize = ntohs(message->size);
2187 if (msize < sizeof (struct GetMessage))
2189 GNUNET_break_op (0);
2190 return GNUNET_SYSERR;
2192 gm = (const struct GetMessage*) message;
2193 type = ntohl (gm->type);
2196 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2197 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2198 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
2199 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2202 GNUNET_break_op (0);
2203 return GNUNET_SYSERR;
2205 bm = ntohl (gm->hash_bitmap);
2213 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
2215 GNUNET_break_op (0);
2216 return GNUNET_SYSERR;
2218 opt = (const GNUNET_HashCode*) &gm[1];
2219 bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
2220 bm = ntohl (gm->hash_bitmap);
2221 if ( (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)) &&
2222 (ntohl (gm->type) == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) )
2224 GNUNET_break_op (0);
2225 return GNUNET_SYSERR;
2228 cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2229 &other->hashPubKey);
2230 GNUNET_assert (NULL != cps);
2231 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
2232 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2239 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
2240 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2241 "Failed to find RETURN-TO peer `%4s' in connection set. Dropping query.\n",
2242 GNUNET_i2s ((const struct GNUNET_PeerIdentity*) &opt[bits-1]));
2245 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2246 "Failed to find peer `%4s' in connection set. Dropping query.\n",
2247 GNUNET_i2s (other));
2249 /* FIXME: try connect? */
2252 /* note that we can really only check load here since otherwise
2253 peers could find out that we are overloaded by not being
2254 disconnected after sending us a malformed query... */
2255 if (GNUNET_YES == test_load_too_high ())
2258 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2259 "Dropping query from `%s', this peer is too busy.\n",
2260 GNUNET_i2s (other));
2266 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2267 "Received request for `%s' of type %u from peer `%4s'\n",
2268 GNUNET_h2s (&gm->query),
2269 (unsigned int) ntohl (gm->type),
2270 GNUNET_i2s (other));
2272 have_ns = (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE));
2273 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
2274 (have_ns ? sizeof(GNUNET_HashCode) : 0));
2276 pr->namespace = (GNUNET_HashCode*) &pr[1];
2278 pr->mingle = ntohl (gm->filter_mutator);
2279 if (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2280 memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
2281 else if (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)
2283 GNUNET_break_op (0);
2285 return GNUNET_SYSERR;
2287 if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
2288 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
2290 pr->anonymity_level = 1;
2291 pr->priority = bound_priority (ntohl (gm->priority), cps);
2292 pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
2293 pr->query = gm->query;
2294 /* decrement ttl (always) */
2295 ttl_decrement = 2 * TTL_DECREMENT +
2296 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2298 if ( (pr->ttl < 0) &&
2299 (pr->ttl - ttl_decrement > 0) )
2302 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2303 "Dropping query from `%s' due to TTL underflow.\n",
2304 GNUNET_i2s (other));
2306 /* integer underflow => drop (should be very rare)! */
2310 pr->ttl -= ttl_decrement;
2311 pr->start_time = GNUNET_TIME_absolute_get ();
2313 /* get bloom filter */
2316 pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
2319 pr->bf_size = bfsize;
2324 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2326 &check_duplicate_request,
2328 if (cdc.have != NULL)
2330 if (cdc.have->start_time.value + cdc.have->ttl >=
2331 pr->start_time.value + pr->ttl)
2333 /* existing request has higher TTL, drop new one! */
2334 cdc.have->priority += pr->priority;
2335 destroy_pending_request (pr);
2337 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2338 "Have existing request with higher TTL, dropping new request.\n",
2339 GNUNET_i2s (other));
2345 /* existing request has lower TTL, drop old one! */
2346 pr->priority += cdc.have->priority;
2347 /* Possible optimization: if we have applicable pending
2348 replies in 'cdc.have', we might want to move those over
2349 (this is a really rare special-case, so it is not clear
2350 that this would be worth it) */
2351 destroy_pending_request (cdc.have);
2352 /* keep processing 'pr'! */
2357 GNUNET_CONTAINER_multihashmap_put (query_request_map,
2360 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2361 GNUNET_CONTAINER_multihashmap_put (peer_request_map,
2364 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2366 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
2368 pr->start_time.value + pr->ttl);
2371 /* calculate change in traffic preference */
2372 preference = (double) pr->priority;
2373 if (preference < QUERY_BANDWIDTH_VALUE)
2374 preference = QUERY_BANDWIDTH_VALUE;
2375 cps->inc_preference += preference;
2377 /* process locally */
2378 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2379 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2380 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
2381 (pr->priority + 1));
2382 pr->drq = GNUNET_FS_drq_get (&gm->query,
2384 &process_local_reply,
2389 /* Are multiple results possible? If so, start processing remotely now! */
2392 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2393 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2394 /* only one result, wait for datastore */
2397 pr->task = GNUNET_SCHEDULER_add_now (sched,
2398 &forward_request_task,
2402 /* make sure we don't track too many requests */
2403 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
2405 pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
2406 destroy_pending_request (pr);
2412 /* **************************** CS GET Handling ************************ */
2416 * Handle START_SEARCH-message (search request from client).
2418 * @param cls closure
2419 * @param client identification of the client
2420 * @param message the actual message
2423 handle_start_search (void *cls,
2424 struct GNUNET_SERVER_Client *client,
2425 const struct GNUNET_MessageHeader *message)
2427 static GNUNET_HashCode all_zeros;
2428 const struct SearchMessage *sm;
2429 struct ClientList *cl;
2430 struct ClientRequestList *crl;
2431 struct PendingRequest *pr;
2436 msize = ntohs (message->size);
2437 if ( (msize < sizeof (struct SearchMessage)) ||
2438 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
2441 GNUNET_SERVER_receive_done (client,
2445 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
2446 sm = (const struct SearchMessage*) message;
2449 while ( (cl != NULL) &&
2450 (cl->client != client) )
2454 cl = GNUNET_malloc (sizeof (struct ClientList));
2455 cl->client = client;
2456 GNUNET_SERVER_client_keep (client);
2457 cl->next = client_list;
2460 type = ntohl (sm->type);
2463 case GNUNET_DATASTORE_BLOCKTYPE_ANY:
2464 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2465 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2466 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
2467 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2471 GNUNET_SERVER_receive_done (client,
2476 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2477 "Received request for `%s' of type %u from local client\n",
2478 GNUNET_h2s (&sm->query),
2479 (unsigned int) type);
2482 /* detect duplicate KBLOCK requests */
2483 if (type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK)
2486 while ( (crl != NULL) &&
2487 ( (0 != memcmp (&crl->req->query,
2489 sizeof (GNUNET_HashCode))) ||
2490 (crl->req->type != type) ) )
2495 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2496 "Have existing request, merging content-seen lists.\n");
2499 /* Duplicate request (used to send long list of
2500 known/blocked results); merge 'pr->replies_seen'
2501 and update bloom filter */
2502 GNUNET_array_grow (pr->replies_seen,
2503 pr->replies_seen_size,
2504 pr->replies_seen_off + sc);
2505 memcpy (&pr->replies_seen[pr->replies_seen_off],
2507 sc * sizeof (GNUNET_HashCode));
2508 pr->replies_seen_off += sc;
2510 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
2511 pr->bf = refresh_bloomfilter (pr->replies_seen_off,
2515 GNUNET_SERVER_receive_done (client,
2520 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
2521 ((type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)?sizeof(GNUNET_HashCode):0));
2522 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
2523 memset (crl, 0, sizeof (struct ClientRequestList));
2524 crl->client_list = cl;
2525 GNUNET_CONTAINER_DLL_insert (cl->rl_head,
2530 pr->client_request_list = crl;
2531 GNUNET_array_grow (pr->replies_seen,
2532 pr->replies_seen_size,
2534 memcpy (pr->replies_seen,
2536 sc * sizeof (GNUNET_HashCode));
2537 pr->replies_seen_off = sc;
2538 pr->anonymity_level = ntohl (sm->anonymity_level);
2539 pr->bf = refresh_bloomfilter (pr->replies_seen_off,
2543 pr->query = sm->query;
2546 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2547 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2548 if (0 != memcmp (&sm->target,
2550 sizeof (GNUNET_HashCode)))
2551 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
2553 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2554 pr->namespace = (GNUNET_HashCode*) &pr[1];
2555 memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
2560 GNUNET_CONTAINER_multihashmap_put (query_request_map,
2563 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2564 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2565 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* get on-demand blocks too! */
2566 pr->drq = GNUNET_FS_drq_get (&sm->query,
2568 &process_local_reply,
2570 GNUNET_TIME_UNIT_FOREVER_REL,
2575 /* **************************** Startup ************************ */
2579 * List of handlers for P2P messages
2580 * that we care about.
2582 static struct GNUNET_CORE_MessageHandler p2p_handlers[] =
2585 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
2587 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
2593 * List of handlers for the messages understood by this
2596 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2597 {&GNUNET_FS_handle_index_start, NULL,
2598 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
2599 {&GNUNET_FS_handle_index_list_get, NULL,
2600 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
2601 {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
2602 sizeof (struct UnindexMessage) },
2603 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
2610 * Process fs requests.
2612 * @param s scheduler to use
2613 * @param server the initialized server
2614 * @param c configuration to use
2617 main_init (struct GNUNET_SCHEDULER_Handle *s,
2618 struct GNUNET_SERVER_Handle *server,
2619 const struct GNUNET_CONFIGURATION_Handle *c)
2623 connected_peers = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2624 query_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2625 peer_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2626 requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2627 core = GNUNET_CORE_connect (sched,
2629 GNUNET_TIME_UNIT_FOREVER_REL,
2633 &peer_connect_handler,
2634 &peer_disconnect_handler,
2640 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2641 _("Failed to connect to `%s' service.\n"),
2643 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
2644 connected_peers = NULL;
2645 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
2646 query_request_map = NULL;
2647 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
2648 requests_by_expiration_heap = NULL;
2649 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
2650 peer_request_map = NULL;
2652 return GNUNET_SYSERR;
2654 GNUNET_SERVER_disconnect_notify (server,
2655 &handle_client_disconnect,
2657 GNUNET_SERVER_add_handlers (server, handlers);
2658 GNUNET_SCHEDULER_add_delayed (sched,
2659 GNUNET_TIME_UNIT_FOREVER_REL,
2667 * Process fs requests.
2669 * @param cls closure
2670 * @param sched scheduler to use
2671 * @param server the initialized server
2672 * @param cfg configuration to use
2676 struct GNUNET_SCHEDULER_Handle *sched,
2677 struct GNUNET_SERVER_Handle *server,
2678 const struct GNUNET_CONFIGURATION_Handle *cfg)
2680 if ( (GNUNET_OK != GNUNET_FS_drq_init (sched, cfg)) ||
2681 (GNUNET_OK != GNUNET_FS_indexing_init (sched, cfg)) ||
2682 (GNUNET_OK != main_init (sched, server, cfg)) )
2684 GNUNET_SCHEDULER_shutdown (sched);
2691 * The main function for the fs service.
2693 * @param argc number of arguments from the command line
2694 * @param argv command line arguments
2695 * @return 0 ok, 1 on error
2698 main (int argc, char *const *argv)
2700 return (GNUNET_OK ==
2701 GNUNET_SERVICE_run (argc,
2704 GNUNET_SERVICE_OPTION_NONE,
2705 &run, NULL)) ? 0 : 1;
2708 /* end of gnunet-service-fs.c */