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 reply. 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;
609 GNUNET_assert (pml->pm == pm);
610 GNUNET_assert ( (tpid == 0) || (tpid == pml->target->pid) );
611 pm->cont (pm->cont_cls, 0);
612 destroy_pending_message_list_entry (pml);
618 * We're done processing a particular request.
619 * Free all associated resources.
621 * @param pr request to destroy
624 destroy_pending_request (struct PendingRequest *pr)
626 struct GNUNET_PeerIdentity pid;
628 if (pr->hnode != NULL)
630 GNUNET_CONTAINER_heap_remove_node (requests_by_expiration_heap,
634 /* might have already been removed from map in 'process_reply' (if
635 there was a unique reply) or never inserted if it was a
636 duplicate; hence ignore the return value here */
637 (void) GNUNET_CONTAINER_multihashmap_remove (query_request_map,
642 GNUNET_FS_drq_get_cancel (pr->drq);
645 if (pr->client_request_list != NULL)
647 GNUNET_CONTAINER_DLL_remove (pr->client_request_list->client_list->rl_head,
648 pr->client_request_list->client_list->rl_tail,
649 pr->client_request_list);
650 GNUNET_free (pr->client_request_list);
651 pr->client_request_list = NULL;
655 GNUNET_PEER_resolve (pr->cp->pid,
657 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
664 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
669 GNUNET_CORE_peer_change_preference_cancel (pr->irc);
672 if (pr->replies_seen != NULL)
674 GNUNET_free (pr->replies_seen);
675 pr->replies_seen = NULL;
677 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
679 GNUNET_SCHEDULER_cancel (sched,
681 pr->task = GNUNET_SCHEDULER_NO_TASK;
683 while (NULL != pr->pending_head)
684 destroy_pending_message_list_entry (pr->pending_head);
685 GNUNET_PEER_change_rc (pr->target_pid, -1);
686 if (pr->used_pids != NULL)
688 GNUNET_PEER_decrement_rcs (pr->used_pids, pr->used_pids_off);
689 GNUNET_free (pr->used_pids);
690 pr->used_pids_off = 0;
691 pr->used_pids_size = 0;
692 pr->used_pids = NULL;
699 * Method called whenever a given peer connects.
701 * @param cls closure, not used
702 * @param peer peer identity this notification is about
703 * @param latency reported latency of the connection with 'other'
704 * @param distance reported distance (DV) to 'other'
707 peer_connect_handler (void *cls,
709 GNUNET_PeerIdentity * peer,
710 struct GNUNET_TIME_Relative latency,
713 struct ConnectedPeer *cp;
715 cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
716 cp->pid = GNUNET_PEER_intern (peer);
717 GNUNET_CONTAINER_multihashmap_put (connected_peers,
720 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
725 * Free (each) request made by the peer.
727 * @param cls closure, points to peer that the request belongs to
728 * @param key current key code
729 * @param value value in the hash map
730 * @return GNUNET_YES (we should continue to iterate)
733 destroy_request (void *cls,
734 const GNUNET_HashCode * key,
737 const struct GNUNET_PeerIdentity * peer = cls;
738 struct PendingRequest *pr = value;
740 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
743 destroy_pending_request (pr);
749 * Method called whenever a peer disconnects.
751 * @param cls closure, not used
752 * @param peer peer identity this notification is about
755 peer_disconnect_handler (void *cls,
757 GNUNET_PeerIdentity * peer)
759 struct ConnectedPeer *cp;
760 struct PendingMessage *pm;
763 GNUNET_CONTAINER_multihashmap_get_multiple (peer_request_map,
767 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
771 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
773 if (NULL != cp->last_client_replies[i])
775 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
776 cp->last_client_replies[i] = NULL;
779 GNUNET_CONTAINER_multihashmap_remove (connected_peers,
782 GNUNET_PEER_change_rc (cp->pid, -1);
783 GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
785 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
786 while (NULL != (pm = cp->pending_messages_head))
787 destroy_pending_message (pm, 0 /* delivery failed */);
788 GNUNET_break (0 == cp->pending_requests);
794 * Iterator over hash map entries that removes all occurences
795 * of the given 'client' from the 'last_client_replies' of the
796 * given connected peer.
798 * @param cls closure, the 'struct GNUNET_SERVER_Client*' to remove
799 * @param key current key code (unused)
800 * @param value value in the hash map (the 'struct ConnectedPeer*' to change)
801 * @return GNUNET_YES (we should continue to iterate)
804 remove_client_from_last_client_replies (void *cls,
805 const GNUNET_HashCode * key,
808 struct GNUNET_SERVER_Client *client = cls;
809 struct ConnectedPeer *cp = value;
812 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
814 if (cp->last_client_replies[i] == client)
816 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
817 cp->last_client_replies[i] = NULL;
825 * A client disconnected. Remove all of its pending queries.
827 * @param cls closure, NULL
828 * @param client identification of the client
831 handle_client_disconnect (void *cls,
832 struct GNUNET_SERVER_Client
835 struct ClientList *pos;
836 struct ClientList *prev;
837 struct ClientRequestList *rcl;
838 struct ClientResponseMessage *creply;
841 return; /* huh? is this allowed? */
844 while ( (NULL != pos) &&
845 (pos->client != client) )
851 return; /* no requests pending for this client */
852 while (NULL != (rcl = pos->rl_head))
853 destroy_pending_request (rcl->req);
855 client_list = pos->next;
857 prev->next = pos->next;
860 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
863 while (NULL != (creply = pos->res_head))
865 GNUNET_CONTAINER_DLL_remove (pos->res_head,
868 GNUNET_free (creply);
870 GNUNET_SERVER_client_drop (pos->client);
872 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
873 &remove_client_from_last_client_replies,
879 * Iterator to free peer entries.
881 * @param cls closure, unused
882 * @param key current key code
883 * @param value value in the hash map (peer entry)
884 * @return GNUNET_YES (we should continue to iterate)
887 clean_peer (void *cls,
888 const GNUNET_HashCode * key,
891 peer_disconnect_handler (NULL, (const struct GNUNET_PeerIdentity*) key);
897 * Task run during shutdown.
903 shutdown_task (void *cls,
904 const struct GNUNET_SCHEDULER_TaskContext *tc)
906 while (client_list != NULL)
907 handle_client_disconnect (NULL,
908 client_list->client);
909 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
912 GNUNET_break (0 == GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap));
913 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
914 requests_by_expiration_heap = 0;
915 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
916 connected_peers = NULL;
917 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (query_request_map));
918 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
919 query_request_map = NULL;
920 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (peer_request_map));
921 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
922 peer_request_map = NULL;
923 GNUNET_assert (NULL != core);
924 GNUNET_CORE_disconnect (core);
931 /* ******************* Utility functions ******************** */
935 * Transmit the given message by copying it to the target buffer
936 * "buf". "buf" will be NULL and "size" zero if the socket was closed
937 * for writing in the meantime. In that case, do nothing
938 * (the disconnect or shutdown handler will take care of the rest).
939 * If we were able to transmit messages and there are still more
940 * pending, ask core again for further calls to this function.
942 * @param cls closure, pointer to the 'struct ConnectedPeer*'
943 * @param size number of bytes available in buf
944 * @param buf where the callee should write the message
945 * @return number of bytes written to buf
948 transmit_to_peer (void *cls,
949 size_t size, void *buf)
951 struct ConnectedPeer *cp = cls;
953 struct GNUNET_PeerIdentity pid;
954 struct PendingMessage *pm;
961 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
962 "Dropping message, core too busy.\n");
967 while ( (NULL != (pm = cp->pending_messages_head) ) &&
968 (pm->msize <= size) )
970 memcpy (&cbuf[msize], &pm[1], pm->msize);
973 destroy_pending_message (pm, cp->pid);
977 GNUNET_PEER_resolve (cp->pid,
979 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
981 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
988 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
989 "Transmitting %u bytes to peer %u.\n",
998 * Add a message to the set of pending messages for the given peer.
1000 * @param cp peer to send message to
1001 * @param pm message to queue
1002 * @param pr request on which behalf this message is being queued
1005 add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
1006 struct PendingMessage *pm,
1007 struct PendingRequest *pr)
1009 struct PendingMessage *pos;
1010 struct PendingMessageList *pml;
1011 struct GNUNET_PeerIdentity pid;
1013 GNUNET_assert (pm->next == NULL);
1014 GNUNET_assert (pm->pml == NULL);
1015 pml = GNUNET_malloc (sizeof (struct PendingMessageList));
1020 GNUNET_CONTAINER_DLL_insert (pr->pending_head,
1023 pos = cp->pending_messages_head;
1024 while ( (pos != NULL) &&
1025 (pm->priority < pos->priority) )
1027 GNUNET_CONTAINER_DLL_insert_after (cp->pending_messages_head,
1028 cp->pending_messages_tail,
1031 cp->pending_requests++;
1032 if (cp->pending_requests > MAX_QUEUE_PER_PEER)
1033 destroy_pending_message (cp->pending_messages_tail, 0);
1034 if (cp->cth == NULL)
1036 /* need to schedule transmission */
1037 GNUNET_PEER_resolve (cp->pid, &pid);
1038 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1039 cp->pending_messages_head->priority,
1040 GNUNET_TIME_UNIT_FOREVER_REL,
1042 cp->pending_messages_head->msize,
1046 if (cp->cth == NULL)
1049 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1050 "Failed to schedule transmission with core!\n");
1052 /* FIXME: call stats (rare, bad case) */
1058 * Mingle hash with the mingle_number to produce different bits.
1061 mingle_hash (const GNUNET_HashCode * in,
1062 int32_t mingle_number,
1063 GNUNET_HashCode * hc)
1067 GNUNET_CRYPTO_hash (&mingle_number,
1070 GNUNET_CRYPTO_hash_xor (&m, in, hc);
1075 * Test if the load on this peer is too high
1076 * to even consider processing the query at
1079 * @return GNUNET_YES if the load is too high, GNUNET_NO otherwise
1082 test_load_too_high ()
1084 return GNUNET_NO; // FIXME
1088 /* ******************* Pending Request Refresh Task ******************** */
1092 * Function called after we either failed or succeeded
1093 * at transmitting a query to a peer.
1095 * @param cls the requests "struct PendingRequest*"
1096 * @param tpid ID of receiving peer, 0 on transmission error
1099 transmit_query_continuation (void *cls,
1100 GNUNET_PEER_Id tpid)
1102 struct PendingRequest *pr = cls;
1106 GNUNET_PEER_change_rc (tpid, 1);
1107 if (pr->used_pids_off == pr->used_pids_size)
1108 GNUNET_array_grow (pr->used_pids,
1110 pr->used_pids_size * 2 + 2);
1111 pr->used_pids[pr->used_pids_off++] = tpid;
1116 * How many bytes should a bloomfilter be if we have already seen
1117 * entry_count responses? Note that BLOOMFILTER_K gives us the number
1118 * of bits set per entry. Furthermore, we should not re-size the
1119 * filter too often (to keep it cheap).
1121 * Since other peers will also add entries but not resize the filter,
1122 * we should generally pick a slightly larger size than what the
1123 * strict math would suggest.
1125 * @return must be a power of two and smaller or equal to 2^15.
1128 compute_bloomfilter_size (unsigned int entry_count)
1131 unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
1132 uint16_t max = 1 << 15;
1134 if (entry_count > max)
1137 while ((size < max) && (size < ideal))
1146 * Recalculate our bloom filter for filtering replies.
1148 * @param count number of entries we are filtering right now
1149 * @param mingle set to our new mingling value
1150 * @param bf_size set to the size of the bloomfilter
1151 * @param entries the entries to filter
1152 * @return updated bloomfilter, NULL for none
1154 static struct GNUNET_CONTAINER_BloomFilter *
1155 refresh_bloomfilter (unsigned int count,
1158 const GNUNET_HashCode *entries)
1160 struct GNUNET_CONTAINER_BloomFilter *bf;
1163 GNUNET_HashCode mhash;
1167 nsize = compute_bloomfilter_size (count);
1168 *mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
1170 bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1173 for (i=0;i<count;i++)
1175 mingle_hash (&entries[i], *mingle, &mhash);
1176 GNUNET_CONTAINER_bloomfilter_add (bf, &mhash);
1183 * We use a random delay to make the timing of requests less
1184 * predictable. This function returns such a random delay.
1186 * FIXME: make schedule dependent on the specifics of the request?
1187 * Or bandwidth and number of connected peers and load?
1189 * @return random delay to use for some request, between 0 and TTL_DECREMENT ms
1191 static struct GNUNET_TIME_Relative
1192 get_processing_delay ()
1194 return GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1195 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1201 * Function called after we've tried to reserve a certain amount of
1202 * bandwidth for a reply. Check if we succeeded and if so send our
1205 * @param cls the requests "struct PendingRequest*"
1206 * @param peer identifies the peer
1207 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1208 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1209 * @param amount set to the amount that was actually reserved or unreserved
1210 * @param preference current traffic preference for the given peer
1213 target_reservation_cb (void *cls,
1215 GNUNET_PeerIdentity * peer,
1216 unsigned int bpm_in,
1217 unsigned int bpm_out,
1219 uint64_t preference)
1221 struct PendingRequest *pr = cls;
1222 struct ConnectedPeer *cp;
1223 struct PendingMessage *pm;
1224 struct GetMessage *gm;
1225 GNUNET_HashCode *ext;
1233 GNUNET_assert (peer != NULL);
1234 // (3) transmit, update ttl/priority
1235 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1239 /* Peer must have just left */
1241 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1242 "Selected peer disconnected!\n");
1246 no_route = GNUNET_NO;
1247 /* FIXME: check against DBLOCK_SIZE and possibly return
1248 amount to reserve; however, this also needs to work
1249 with testcases which currently start out with a far
1250 too low per-peer bw limit, so they would never send
1251 anything. Big issue. */
1257 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1258 "Failed to reserve bandwidth for reply (got %d/%u bytes only)!\n",
1262 return; /* this target round failed */
1264 /* FIXME: if we are "quite" busy, we may still want to skip
1265 this round; need more load detection code! */
1266 no_route = GNUNET_YES;
1269 /* build message and insert message into priority queue */
1271 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1272 "Forwarding request to `%4s'!\n",
1277 if (GNUNET_YES == no_route)
1279 bm |= GET_MESSAGE_BIT_RETURN_TO;
1282 if (pr->namespace != NULL)
1284 bm |= GET_MESSAGE_BIT_SKS_NAMESPACE;
1287 if (pr->target_pid != 0)
1289 bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
1292 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
1293 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1294 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1296 gm = (struct GetMessage*) &pm[1];
1297 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
1298 gm->header.size = htons (msize);
1299 gm->type = htonl (pr->type);
1300 pr->remaining_priority /= 2;
1301 gm->priority = htonl (pr->remaining_priority);
1302 gm->ttl = htonl (pr->ttl);
1303 gm->filter_mutator = htonl(pr->mingle);
1304 gm->hash_bitmap = htonl (bm);
1305 gm->query = pr->query;
1306 ext = (GNUNET_HashCode*) &gm[1];
1308 if (GNUNET_YES == no_route)
1309 GNUNET_PEER_resolve (pr->cp->pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1310 if (pr->namespace != NULL)
1311 memcpy (&ext[k++], pr->namespace, sizeof (GNUNET_HashCode));
1312 if (pr->target_pid != 0)
1313 GNUNET_PEER_resolve (pr->target_pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1314 bfdata = (char *) &ext[k];
1316 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
1319 pm->cont = &transmit_query_continuation;
1321 add_to_pending_messages_for_peer (cp, pm, pr);
1326 * Closure used for "target_peer_select_cb".
1328 struct PeerSelectionContext
1331 * The request for which we are selecting
1334 struct PendingRequest *pr;
1337 * Current "prime" target.
1339 struct GNUNET_PeerIdentity target;
1342 * How much do we like this target?
1344 double target_score;
1350 * Function called for each connected peer to determine
1351 * which one(s) would make good targets for forwarding.
1353 * @param cls closure (struct PeerSelectionContext)
1354 * @param key current key code (peer identity)
1355 * @param value value in the hash map (struct ConnectedPeer)
1356 * @return GNUNET_YES if we should continue to
1361 target_peer_select_cb (void *cls,
1362 const GNUNET_HashCode * key,
1365 struct PeerSelectionContext *psc = cls;
1366 struct ConnectedPeer *cp = value;
1367 struct PendingRequest *pr = psc->pr;
1371 /* 1) check if we have already (recently) forwarded to this peer */
1372 for (i=0;i<pr->used_pids_off;i++)
1373 if (pr->used_pids[i] == cp->pid)
1374 return GNUNET_YES; /* skip */
1375 // 2) calculate how much we'd like to forward to this peer
1376 score = 42; // FIXME!
1377 // FIXME: also need API to gather data on responsiveness
1378 // of this peer (we have fields for that in 'cp', but
1379 // they are never set!)
1381 /* store best-fit in closure */
1382 if (score > psc->target_score)
1384 psc->target_score = score;
1385 psc->target.hashPubKey = *key;
1392 * We're processing a GET request from another peer and have decided
1393 * to forward it to other peers. This function is called periodically
1394 * and should forward the request to other peers until we have all
1395 * possible replies. If we have transmitted the *only* reply to
1396 * the initiator we should destroy the pending request. If we have
1397 * many replies in the queue to the initiator, we should delay sending
1398 * out more queries until the reply queue has shrunk some.
1400 * @param cls our "struct ProcessGetContext *"
1404 forward_request_task (void *cls,
1405 const struct GNUNET_SCHEDULER_TaskContext *tc)
1407 struct PendingRequest *pr = cls;
1408 struct PeerSelectionContext psc;
1409 struct ConnectedPeer *cp;
1411 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1412 get_processing_delay (),
1413 &forward_request_task,
1415 if (pr->irc != NULL)
1416 return; /* previous request still pending */
1417 /* (1) select target */
1419 psc.target_score = DBL_MIN;
1420 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1421 &target_peer_select_cb,
1423 if (psc.target_score == DBL_MIN)
1426 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1427 "No peer selected for forwarding!\n");
1429 return; /* nobody selected */
1432 /* (2) reserve reply bandwidth */
1433 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1434 &psc.target.hashPubKey);
1435 pr->irc = GNUNET_CORE_peer_change_preference (sched, cfg,
1437 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1438 (uint32_t) -1 /* no limit */,
1440 (uint64_t) cp->inc_preference,
1441 &target_reservation_cb,
1443 cp->inc_preference = 0.0;
1447 /* **************************** P2P PUT Handling ************************ */
1451 * Function called after we either failed or succeeded
1452 * at transmitting a reply to a peer.
1454 * @param cls the requests "struct PendingRequest*"
1455 * @param tpid ID of receiving peer, 0 on transmission error
1458 transmit_reply_continuation (void *cls,
1459 GNUNET_PEER_Id tpid)
1461 struct PendingRequest *pr = cls;
1465 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1466 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1467 /* only one reply expected, done with the request! */
1468 destroy_pending_request (pr);
1470 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1471 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1481 * Check if the given KBlock is well-formed.
1483 * @param kb the kblock data (or at least "dsize" bytes claiming to be one)
1484 * @param dsize size of "kb" in bytes; check for < sizeof(struct KBlock)!
1485 * @param query where to store the query that this block answers
1486 * @return GNUNET_OK if this is actually a well-formed KBlock
1489 check_kblock (const struct KBlock *kb,
1491 GNUNET_HashCode *query)
1493 if (dsize < sizeof (struct KBlock))
1495 GNUNET_break_op (0);
1496 return GNUNET_SYSERR;
1498 if (dsize - sizeof (struct KBlock) !=
1499 ntohs (kb->purpose.size)
1500 - sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose)
1501 - sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) )
1503 GNUNET_break_op (0);
1504 return GNUNET_SYSERR;
1507 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_KBLOCK,
1512 GNUNET_break_op (0);
1513 return GNUNET_SYSERR;
1516 GNUNET_CRYPTO_hash (&kb->keyspace,
1517 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1524 * Check if the given SBlock is well-formed.
1526 * @param sb the sblock data (or at least "dsize" bytes claiming to be one)
1527 * @param dsize size of "kb" in bytes; check for < sizeof(struct SBlock)!
1528 * @param query where to store the query that this block answers
1529 * @param namespace where to store the namespace that this block belongs to
1530 * @return GNUNET_OK if this is actually a well-formed SBlock
1533 check_sblock (const struct SBlock *sb,
1535 GNUNET_HashCode *query,
1536 GNUNET_HashCode *namespace)
1538 if (dsize < sizeof (struct SBlock))
1540 GNUNET_break_op (0);
1541 return GNUNET_SYSERR;
1544 ntohs (sb->purpose.size) + sizeof (struct GNUNET_CRYPTO_RsaSignature))
1546 GNUNET_break_op (0);
1547 return GNUNET_SYSERR;
1550 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_SBLOCK,
1555 GNUNET_break_op (0);
1556 return GNUNET_SYSERR;
1559 *query = sb->identifier;
1560 if (namespace != NULL)
1561 GNUNET_CRYPTO_hash (&sb->subspace,
1562 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1569 * Transmit the given message by copying it to the target buffer
1570 * "buf". "buf" will be NULL and "size" zero if the socket was closed
1571 * for writing in the meantime. In that case, do nothing
1572 * (the disconnect or shutdown handler will take care of the rest).
1573 * If we were able to transmit messages and there are still more
1574 * pending, ask core again for further calls to this function.
1576 * @param cls closure, pointer to the 'struct ClientList*'
1577 * @param size number of bytes available in buf
1578 * @param buf where the callee should write the message
1579 * @return number of bytes written to buf
1582 transmit_to_client (void *cls,
1583 size_t size, void *buf)
1585 struct ClientList *cl = cls;
1587 struct ClientResponseMessage *creply;
1594 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1595 "Not sending reply, client communication problem.\n");
1600 while ( (NULL != (creply = cl->res_head) ) &&
1601 (creply->msize <= size) )
1603 memcpy (&cbuf[msize], &creply[1], creply->msize);
1604 msize += creply->msize;
1605 size -= creply->msize;
1606 GNUNET_CONTAINER_DLL_remove (cl->res_head,
1609 GNUNET_free (creply);
1612 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
1614 GNUNET_TIME_UNIT_FOREVER_REL,
1615 &transmit_to_client,
1618 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1619 "Transmitted %u bytes to client\n",
1620 (unsigned int) msize);
1627 * Closure for "process_reply" function.
1629 struct ProcessReplyClosure
1632 * The data for the reply.
1636 // FIXME: add 'struct ConnectedPeer' to track 'last_xxx_replies' here!
1639 * When the reply expires.
1641 struct GNUNET_TIME_Absolute expiration;
1649 * Namespace that this reply belongs to
1650 * (if it is of type SBLOCK).
1652 GNUNET_HashCode namespace;
1655 * Type of the block.
1660 * How much was this reply worth to us?
1667 * We have received a reply; handle it!
1669 * @param cls response (struct ProcessReplyClosure)
1670 * @param key our query
1671 * @param value value in the hash map (info about the query)
1672 * @return GNUNET_YES (we should continue to iterate)
1675 process_reply (void *cls,
1676 const GNUNET_HashCode * key,
1679 struct ProcessReplyClosure *prq = cls;
1680 struct PendingRequest *pr = value;
1681 struct PendingMessage *reply;
1682 struct ClientResponseMessage *creply;
1683 struct ClientList *cl;
1684 struct PutMessage *pm;
1685 struct ConnectedPeer *cp;
1686 GNUNET_HashCode chash;
1687 GNUNET_HashCode mhash;
1693 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1694 "Matched result for query `%s' with pending request\n",
1697 do_remove = GNUNET_NO;
1698 GNUNET_CRYPTO_hash (prq->data,
1703 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1704 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1705 /* only possible reply, stop requesting! */
1706 while (NULL != pr->pending_head)
1707 destroy_pending_message_list_entry (pr->pending_head);
1708 if (pr->drq != NULL)
1710 GNUNET_FS_drq_get_cancel (pr->drq);
1713 do_remove = GNUNET_YES;
1715 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1716 if (0 != memcmp (pr->namespace,
1718 sizeof (GNUNET_HashCode)))
1719 return GNUNET_YES; /* wrong namespace */
1720 /* then: fall-through! */
1721 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1724 mingle_hash (&chash, pr->mingle, &mhash);
1725 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
1727 return GNUNET_YES; /* duplicate */
1728 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
1731 if (pr->client_request_list != NULL)
1733 if (pr->replies_seen_size == pr->replies_seen_off)
1735 GNUNET_array_grow (pr->replies_seen,
1736 pr->replies_seen_size,
1737 pr->replies_seen_size * 2 + 4);
1739 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
1740 pr->bf = refresh_bloomfilter (pr->replies_seen_off,
1745 pr->replies_seen[pr->replies_seen_off++] = chash;
1749 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
1750 // FIXME: any checks against duplicates for SKBlocks?
1756 prio = pr->priority;
1757 prq->priority += pr->remaining_priority;
1758 pr->remaining_priority = 0;
1759 if (pr->client_request_list != NULL)
1762 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1763 "Transmitting result for query `%s' to local client\n",
1766 cl = pr->client_request_list->client_list;
1767 msize = sizeof (struct PutMessage) + prq->size;
1768 creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
1769 creply->msize = msize;
1770 creply->client_list = cl;
1771 GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
1775 pm = (struct PutMessage*) &creply[1];
1776 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
1777 pm->header.size = htons (msize);
1778 pm->type = htonl (prq->type);
1779 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
1780 memcpy (&pm[1], prq->data, prq->size);
1782 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
1784 GNUNET_TIME_UNIT_FOREVER_REL,
1785 &transmit_to_client,
1787 GNUNET_break (cl->th != NULL);
1793 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1794 "Transmitting result for query `%s' to other peer (PID=%u)\n",
1796 (unsigned int) cp->pid);
1798 msize = sizeof (struct PutMessage) + prq->size;
1799 reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
1800 reply->cont = &transmit_reply_continuation;
1801 reply->cont_cls = pr;
1802 reply->msize = msize;
1803 reply->priority = (uint32_t) -1; /* send replies first! */
1804 pm = (struct PutMessage*) &reply[1];
1805 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
1806 pm->header.size = htons (msize);
1807 pm->type = htonl (prq->type);
1808 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
1809 memcpy (&pm[1], prq->data, prq->size);
1810 add_to_pending_messages_for_peer (cp, reply, pr);
1812 if (GNUNET_YES == do_remove)
1813 GNUNET_break (GNUNET_YES ==
1814 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
1818 // FIXME: implement hot-path routing statistics keeping!
1824 * Handle P2P "PUT" message.
1826 * @param cls closure, always NULL
1827 * @param other the other peer involved (sender or receiver, NULL
1828 * for loopback messages where we are both sender and receiver)
1829 * @param message the actual message
1830 * @param latency reported latency of the connection with 'other'
1831 * @param distance reported distance (DV) to 'other'
1832 * @return GNUNET_OK to keep the connection open,
1833 * GNUNET_SYSERR to close it (signal serious error)
1836 handle_p2p_put (void *cls,
1837 const struct GNUNET_PeerIdentity *other,
1838 const struct GNUNET_MessageHeader *message,
1839 struct GNUNET_TIME_Relative latency,
1842 const struct PutMessage *put;
1846 struct GNUNET_TIME_Absolute expiration;
1847 GNUNET_HashCode query;
1848 struct ProcessReplyClosure prq;
1850 msize = ntohs (message->size);
1851 if (msize < sizeof (struct PutMessage))
1854 return GNUNET_SYSERR;
1856 put = (const struct PutMessage*) message;
1857 dsize = msize - sizeof (struct PutMessage);
1858 type = ntohl (put->type);
1859 expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
1861 /* first, validate! */
1864 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1865 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1866 GNUNET_CRYPTO_hash (&put[1], dsize, &query);
1868 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1870 check_kblock ((const struct KBlock*) &put[1],
1873 return GNUNET_SYSERR;
1875 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1877 check_sblock ((const struct SBlock*) &put[1],
1881 return GNUNET_SYSERR;
1883 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
1884 // FIXME -- validate SKBLOCK!
1888 /* unknown block type */
1889 GNUNET_break_op (0);
1890 return GNUNET_SYSERR;
1894 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1895 "Received result for query `%s' from peer `%4s'\n",
1896 GNUNET_h2s (&query),
1897 GNUNET_i2s (other));
1899 /* now, lookup 'query' */
1900 prq.data = (const void*) &put[1];
1903 prq.expiration = expiration;
1905 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
1909 // FIXME: if migration is on and load is low,
1910 // queue to store data in datastore;
1911 // use "prq.priority" for that!
1916 /* **************************** P2P GET Handling ************************ */
1920 * We're processing (local) results for a search request
1921 * from another peer. Pass applicable results to the
1922 * peer and if we are done either clean up (operation
1923 * complete) or forward to other peers (more results possible).
1925 * @param cls our closure (struct LocalGetContext)
1926 * @param key key for the content
1927 * @param size number of bytes in data
1928 * @param data content stored
1929 * @param type type of the content
1930 * @param priority priority of the content
1931 * @param anonymity anonymity-level for the content
1932 * @param expiration expiration time for the content
1933 * @param uid unique identifier for the datum;
1934 * maybe 0 if no unique identifier is available
1937 process_local_reply (void *cls,
1938 const GNUNET_HashCode * key,
1944 struct GNUNET_TIME_Absolute
1948 struct PendingRequest *pr = cls;
1949 struct ProcessReplyClosure prq;
1950 GNUNET_HashCode dhash;
1951 GNUNET_HashCode mhash;
1952 GNUNET_HashCode query;
1958 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1959 "Done processing local replies, forwarding request to other peers.\n");
1961 if (pr->client_request_list != NULL)
1962 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
1964 /* no more results */
1965 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1966 pr->task = GNUNET_SCHEDULER_add_now (sched,
1967 &forward_request_task,
1971 if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
1974 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1975 "Found ONDEMAND block, performing on-demand encoding\n");
1978 GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
1979 anonymity, expiration, uid,
1980 &process_local_reply,
1982 GNUNET_FS_drq_get_next (GNUNET_YES);
1985 /* check for duplicates */
1986 GNUNET_CRYPTO_hash (data, size, &dhash);
1987 mingle_hash (&dhash,
1990 if ( (pr->bf != NULL) &&
1992 GNUNET_CONTAINER_bloomfilter_test (pr->bf,
1996 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1997 "Result from datastore filtered by bloomfilter (duplicate).\n");
1999 GNUNET_FS_drq_get_next (GNUNET_YES);
2003 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2004 "Found result for query `%s' in local datastore\n",
2007 pr->results_found++;
2008 if ( (pr->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
2009 (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
2010 (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) )
2015 pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
2019 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
2022 memset (&prq, 0, sizeof (prq));
2024 prq.expiration = expiration;
2026 if ( (type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) &&
2027 (GNUNET_OK != check_sblock ((const struct SBlock*) data,
2033 /* FIXME: consider removing the block? */
2034 GNUNET_FS_drq_get_next (GNUNET_YES);
2038 prq.priority = priority;
2039 process_reply (&prq, key, pr);
2041 if ( ( (pr->client_request_list == NULL) &&
2042 ( (GNUNET_YES == test_load_too_high()) ||
2043 (pr->results_found > 5 + 2 * pr->priority) ) ) ||
2044 (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK) )
2047 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2048 "Unique reply found or load too high, done with request\n");
2050 GNUNET_FS_drq_get_next (GNUNET_NO);
2053 GNUNET_FS_drq_get_next (GNUNET_YES);
2058 * The priority level imposes a bound on the maximum
2059 * value for the ttl that can be requested.
2061 * @param ttl_in requested ttl
2062 * @param prio given priority
2063 * @return ttl_in if ttl_in is below the limit,
2064 * otherwise the ttl-limit for the given priority
2067 bound_ttl (int32_t ttl_in, uint32_t prio)
2069 unsigned long long allowed;
2073 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
2074 if (ttl_in > allowed)
2076 if (allowed >= (1 << 30))
2085 * We've received a request with the specified priority. Bound it
2086 * according to how much we trust the given peer.
2088 * @param prio_in requested priority
2089 * @param cp the peer making the request
2090 * @return effective priority
2093 bound_priority (uint32_t prio_in,
2094 struct ConnectedPeer *cp)
2101 * Closure for 'check_duplicate_request'.
2103 struct CheckDuplicateRequestClosure
2106 * The new request we should check if it already exists.
2108 const struct PendingRequest *pr;
2111 * Existing request found by the checker, NULL if none.
2113 struct PendingRequest *have;
2118 * Iterator over entries in the 'query_request_map' that
2119 * tries to see if we have the same request pending from
2120 * the same peer already.
2122 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
2123 * @param key current key code (query, ignored, must match)
2124 * @param value value in the hash map (a 'struct PendingRequest'
2125 * that already exists)
2126 * @return GNUNET_YES if we should continue to
2127 * iterate (no match yet)
2128 * GNUNET_NO if not (match found).
2131 check_duplicate_request (void *cls,
2132 const GNUNET_HashCode * key,
2135 struct CheckDuplicateRequestClosure *cdc = cls;
2136 struct PendingRequest *have = value;
2138 if (cdc->pr->target_pid == have->target_pid)
2148 * Handle P2P "GET" request.
2150 * @param cls closure, always NULL
2151 * @param other the other peer involved (sender or receiver, NULL
2152 * for loopback messages where we are both sender and receiver)
2153 * @param message the actual message
2154 * @param latency reported latency of the connection with 'other'
2155 * @param distance reported distance (DV) to 'other'
2156 * @return GNUNET_OK to keep the connection open,
2157 * GNUNET_SYSERR to close it (signal serious error)
2160 handle_p2p_get (void *cls,
2161 const struct GNUNET_PeerIdentity *other,
2162 const struct GNUNET_MessageHeader *message,
2163 struct GNUNET_TIME_Relative latency,
2166 struct PendingRequest *pr;
2167 struct ConnectedPeer *cp;
2168 struct ConnectedPeer *cps;
2169 struct CheckDuplicateRequestClosure cdc;
2170 struct GNUNET_TIME_Relative timeout;
2172 const struct GetMessage *gm;
2174 const GNUNET_HashCode *opt;
2177 uint32_t ttl_decrement;
2182 msize = ntohs(message->size);
2183 if (msize < sizeof (struct GetMessage))
2185 GNUNET_break_op (0);
2186 return GNUNET_SYSERR;
2188 gm = (const struct GetMessage*) message;
2189 type = ntohl (gm->type);
2192 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2193 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2194 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
2195 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2198 GNUNET_break_op (0);
2199 return GNUNET_SYSERR;
2201 bm = ntohl (gm->hash_bitmap);
2209 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
2211 GNUNET_break_op (0);
2212 return GNUNET_SYSERR;
2214 opt = (const GNUNET_HashCode*) &gm[1];
2215 bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
2216 bm = ntohl (gm->hash_bitmap);
2217 if ( (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)) &&
2218 (ntohl (gm->type) == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) )
2220 GNUNET_break_op (0);
2221 return GNUNET_SYSERR;
2224 cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2225 &other->hashPubKey);
2226 GNUNET_assert (NULL != cps);
2227 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
2228 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2235 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
2236 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2237 "Failed to find RETURN-TO peer `%4s' in connection set. Dropping query.\n",
2238 GNUNET_i2s ((const struct GNUNET_PeerIdentity*) &opt[bits-1]));
2241 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2242 "Failed to find peer `%4s' in connection set. Dropping query.\n",
2243 GNUNET_i2s (other));
2245 /* FIXME: try connect? */
2248 /* note that we can really only check load here since otherwise
2249 peers could find out that we are overloaded by not being
2250 disconnected after sending us a malformed query... */
2251 if (GNUNET_YES == test_load_too_high ())
2254 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2255 "Dropping query from `%s', this peer is too busy.\n",
2256 GNUNET_i2s (other));
2262 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2263 "Received request for `%s' of type %u from peer `%4s'\n",
2264 GNUNET_h2s (&gm->query),
2265 (unsigned int) ntohl (gm->type),
2266 GNUNET_i2s (other));
2268 have_ns = (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE));
2269 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
2270 (have_ns ? sizeof(GNUNET_HashCode) : 0));
2272 pr->namespace = (GNUNET_HashCode*) &pr[1];
2274 pr->mingle = ntohl (gm->filter_mutator);
2275 if (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2276 memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
2277 else if (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)
2279 GNUNET_break_op (0);
2281 return GNUNET_SYSERR;
2283 if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
2284 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
2286 pr->anonymity_level = 1;
2287 pr->priority = bound_priority (ntohl (gm->priority), cps);
2288 pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
2289 pr->query = gm->query;
2290 /* decrement ttl (always) */
2291 ttl_decrement = 2 * TTL_DECREMENT +
2292 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2294 if ( (pr->ttl < 0) &&
2295 (pr->ttl - ttl_decrement > 0) )
2298 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2299 "Dropping query from `%s' due to TTL underflow.\n",
2300 GNUNET_i2s (other));
2302 /* integer underflow => drop (should be very rare)! */
2306 pr->ttl -= ttl_decrement;
2307 pr->start_time = GNUNET_TIME_absolute_get ();
2309 /* get bloom filter */
2312 pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
2315 pr->bf_size = bfsize;
2320 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2322 &check_duplicate_request,
2324 if (cdc.have != NULL)
2326 if (cdc.have->start_time.value + cdc.have->ttl >=
2327 pr->start_time.value + pr->ttl)
2329 /* existing request has higher TTL, drop new one! */
2330 cdc.have->priority += pr->priority;
2331 destroy_pending_request (pr);
2333 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2334 "Have existing request with higher TTL, dropping new request.\n",
2335 GNUNET_i2s (other));
2341 /* existing request has lower TTL, drop old one! */
2342 pr->priority += cdc.have->priority;
2343 /* Possible optimization: if we have applicable pending
2344 replies in 'cdc.have', we might want to move those over
2345 (this is a really rare special-case, so it is not clear
2346 that this would be worth it) */
2347 destroy_pending_request (cdc.have);
2348 /* keep processing 'pr'! */
2353 GNUNET_CONTAINER_multihashmap_put (query_request_map,
2356 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2357 GNUNET_CONTAINER_multihashmap_put (peer_request_map,
2360 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2362 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
2364 pr->start_time.value + pr->ttl);
2367 /* calculate change in traffic preference */
2368 preference = (double) pr->priority;
2369 if (preference < QUERY_BANDWIDTH_VALUE)
2370 preference = QUERY_BANDWIDTH_VALUE;
2371 cps->inc_preference += preference;
2373 /* process locally */
2374 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2375 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2376 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
2377 (pr->priority + 1));
2378 pr->drq = GNUNET_FS_drq_get (&gm->query,
2380 &process_local_reply,
2385 /* Are multiple results possible? If so, start processing remotely now! */
2388 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2389 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2390 /* only one result, wait for datastore */
2393 pr->task = GNUNET_SCHEDULER_add_now (sched,
2394 &forward_request_task,
2398 /* make sure we don't track too many requests */
2399 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
2401 pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
2402 destroy_pending_request (pr);
2408 /* **************************** CS GET Handling ************************ */
2412 * Handle START_SEARCH-message (search request from client).
2414 * @param cls closure
2415 * @param client identification of the client
2416 * @param message the actual message
2419 handle_start_search (void *cls,
2420 struct GNUNET_SERVER_Client *client,
2421 const struct GNUNET_MessageHeader *message)
2423 static GNUNET_HashCode all_zeros;
2424 const struct SearchMessage *sm;
2425 struct ClientList *cl;
2426 struct ClientRequestList *crl;
2427 struct PendingRequest *pr;
2432 msize = ntohs (message->size);
2433 if ( (msize < sizeof (struct SearchMessage)) ||
2434 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
2437 GNUNET_SERVER_receive_done (client,
2441 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
2442 sm = (const struct SearchMessage*) message;
2445 while ( (cl != NULL) &&
2446 (cl->client != client) )
2450 cl = GNUNET_malloc (sizeof (struct ClientList));
2451 cl->client = client;
2452 GNUNET_SERVER_client_keep (client);
2453 cl->next = client_list;
2456 type = ntohl (sm->type);
2459 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2460 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2461 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
2462 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2466 GNUNET_SERVER_receive_done (client,
2468 return GNUNET_SYSERR;
2471 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2472 "Received request for `%s' of type %u from local client\n",
2473 GNUNET_h2s (&sm->query),
2474 (unsigned int) type);
2477 /* detect duplicate KBLOCK requests */
2478 if (type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK)
2481 while ( (crl != NULL) &&
2482 ( (0 != memcmp (&crl->req->query,
2484 sizeof (GNUNET_HashCode))) ||
2485 (crl->req->type != type) ) )
2490 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2491 "Have existing request, merging content-seen lists.\n");
2494 /* Duplicate request (used to send long list of
2495 known/blocked results); merge 'pr->replies_seen'
2496 and update bloom filter */
2497 GNUNET_array_grow (pr->replies_seen,
2498 pr->replies_seen_size,
2499 pr->replies_seen_off + sc);
2500 memcpy (&pr->replies_seen[pr->replies_seen_off],
2502 sc * sizeof (GNUNET_HashCode));
2503 pr->replies_seen_off += sc;
2505 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
2506 pr->bf = refresh_bloomfilter (pr->replies_seen_off,
2510 GNUNET_SERVER_receive_done (client,
2515 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
2516 ((type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)?sizeof(GNUNET_HashCode):0));
2517 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
2518 memset (crl, 0, sizeof (struct ClientRequestList));
2519 crl->client_list = cl;
2520 GNUNET_CONTAINER_DLL_insert (cl->rl_head,
2525 pr->client_request_list = crl;
2526 GNUNET_array_grow (pr->replies_seen,
2527 pr->replies_seen_size,
2529 memcpy (pr->replies_seen,
2531 sc * sizeof (GNUNET_HashCode));
2532 pr->replies_seen_off = sc;
2533 pr->anonymity_level = ntohl (sm->anonymity_level);
2534 pr->bf = refresh_bloomfilter (pr->replies_seen_off,
2538 pr->query = sm->query;
2541 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2542 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2543 if (0 != memcmp (&sm->target,
2545 sizeof (GNUNET_HashCode)))
2546 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
2548 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2549 pr->namespace = (GNUNET_HashCode*) &pr[1];
2550 memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
2555 GNUNET_CONTAINER_multihashmap_put (query_request_map,
2558 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2559 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2560 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* get on-demand blocks too! */
2561 pr->drq = GNUNET_FS_drq_get (&sm->query,
2563 &process_local_reply,
2565 GNUNET_TIME_UNIT_FOREVER_REL,
2570 /* **************************** Startup ************************ */
2574 * List of handlers for P2P messages
2575 * that we care about.
2577 static struct GNUNET_CORE_MessageHandler p2p_handlers[] =
2580 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
2582 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
2588 * List of handlers for the messages understood by this
2591 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2592 {&GNUNET_FS_handle_index_start, NULL,
2593 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
2594 {&GNUNET_FS_handle_index_list_get, NULL,
2595 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
2596 {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
2597 sizeof (struct UnindexMessage) },
2598 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
2605 * Process fs requests.
2607 * @param s scheduler to use
2608 * @param server the initialized server
2609 * @param c configuration to use
2612 main_init (struct GNUNET_SCHEDULER_Handle *s,
2613 struct GNUNET_SERVER_Handle *server,
2614 const struct GNUNET_CONFIGURATION_Handle *c)
2618 connected_peers = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2619 query_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2620 peer_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2621 requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2622 core = GNUNET_CORE_connect (sched,
2624 GNUNET_TIME_UNIT_FOREVER_REL,
2628 &peer_connect_handler,
2629 &peer_disconnect_handler,
2635 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2636 _("Failed to connect to `%s' service.\n"),
2638 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
2639 connected_peers = NULL;
2640 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
2641 query_request_map = NULL;
2642 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
2643 requests_by_expiration_heap = NULL;
2644 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
2645 peer_request_map = NULL;
2647 return GNUNET_SYSERR;
2649 GNUNET_SERVER_disconnect_notify (server,
2650 &handle_client_disconnect,
2652 GNUNET_SERVER_add_handlers (server, handlers);
2653 GNUNET_SCHEDULER_add_delayed (sched,
2654 GNUNET_TIME_UNIT_FOREVER_REL,
2662 * Process fs requests.
2664 * @param cls closure
2665 * @param sched scheduler to use
2666 * @param server the initialized server
2667 * @param cfg configuration to use
2671 struct GNUNET_SCHEDULER_Handle *sched,
2672 struct GNUNET_SERVER_Handle *server,
2673 const struct GNUNET_CONFIGURATION_Handle *cfg)
2675 if ( (GNUNET_OK != GNUNET_FS_drq_init (sched, cfg)) ||
2676 (GNUNET_OK != GNUNET_FS_indexing_init (sched, cfg)) ||
2677 (GNUNET_OK != main_init (sched, server, cfg)) )
2679 GNUNET_SCHEDULER_shutdown (sched);
2686 * The main function for the fs service.
2688 * @param argc number of arguments from the command line
2689 * @param argv command line arguments
2690 * @return 0 ok, 1 on error
2693 main (int argc, char *const *argv)
2695 return (GNUNET_OK ==
2696 GNUNET_SERVICE_run (argc,
2699 GNUNET_SERVICE_OPTION_NONE,
2700 &run, NULL)) ? 0 : 1;
2703 /* end of gnunet-service-fs.c */