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_NO
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 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 reply, 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,
992 * Add a message to the set of pending messages for the given peer.
994 * @param cp peer to send message to
995 * @param pm message to queue
996 * @param pr request on which behalf this message is being queued
999 add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
1000 struct PendingMessage *pm,
1001 struct PendingRequest *pr)
1003 struct PendingMessage *pos;
1004 struct PendingMessageList *pml;
1005 struct GNUNET_PeerIdentity pid;
1007 GNUNET_assert (pm->next == NULL);
1008 GNUNET_assert (pm->pml == NULL);
1009 pml = GNUNET_malloc (sizeof (struct PendingMessageList));
1014 GNUNET_CONTAINER_DLL_insert (pr->pending_head,
1017 pos = cp->pending_messages_head;
1018 while ( (pos != NULL) &&
1019 (pm->priority < pos->priority) )
1021 GNUNET_CONTAINER_DLL_insert_after (cp->pending_messages_head,
1022 cp->pending_messages_tail,
1025 cp->pending_requests++;
1026 if (cp->pending_requests > MAX_QUEUE_PER_PEER)
1027 destroy_pending_message (cp->pending_messages_tail, 0);
1028 if (cp->cth == NULL)
1030 /* need to schedule transmission */
1031 GNUNET_PEER_resolve (cp->pid, &pid);
1032 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1033 cp->pending_messages_head->priority,
1034 GNUNET_TIME_UNIT_FOREVER_REL,
1036 cp->pending_messages_head->msize,
1040 if (cp->cth == NULL)
1042 /* FIXME: call stats (rare, bad case) */
1048 * Mingle hash with the mingle_number to produce different bits.
1051 mingle_hash (const GNUNET_HashCode * in,
1052 int32_t mingle_number,
1053 GNUNET_HashCode * hc)
1057 GNUNET_CRYPTO_hash (&mingle_number,
1060 GNUNET_CRYPTO_hash_xor (&m, in, hc);
1065 * Test if the load on this peer is too high
1066 * to even consider processing the query at
1069 * @return GNUNET_YES if the load is too high, GNUNET_NO otherwise
1072 test_load_too_high ()
1074 return GNUNET_NO; // FIXME
1078 /* ******************* Pending Request Refresh Task ******************** */
1082 * Function called after we either failed or succeeded
1083 * at transmitting a query to a peer.
1085 * @param cls the requests "struct PendingRequest*"
1086 * @param pid ID of receiving peer, 0 on transmission error
1089 transmit_query_continuation (void *cls,
1090 GNUNET_PEER_Id tpid)
1092 struct PendingRequest *pr = cls;
1096 GNUNET_PEER_change_rc (tpid, 1);
1097 if (pr->used_pids_off == pr->used_pids_size)
1098 GNUNET_array_grow (pr->used_pids,
1100 pr->used_pids_size * 2 + 2);
1101 pr->used_pids[pr->used_pids_off++] = tpid;
1106 * How many bytes should a bloomfilter be if we have already seen
1107 * entry_count responses? Note that BLOOMFILTER_K gives us the number
1108 * of bits set per entry. Furthermore, we should not re-size the
1109 * filter too often (to keep it cheap).
1111 * Since other peers will also add entries but not resize the filter,
1112 * we should generally pick a slightly larger size than what the
1113 * strict math would suggest.
1115 * @return must be a power of two and smaller or equal to 2^15.
1118 compute_bloomfilter_size (unsigned int entry_count)
1121 unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
1122 uint16_t max = 1 << 15;
1124 if (entry_count > max)
1127 while ((size < max) && (size < ideal))
1136 * Recalculate our bloom filter for filtering replies.
1138 * @param count number of entries we are filtering right now
1139 * @param mingle set to our new mingling value
1140 * @param bf_size set to the size of the bloomfilter
1141 * @param entries the entries to filter
1142 * @return updated bloomfilter, NULL for none
1144 static struct GNUNET_CONTAINER_BloomFilter *
1145 refresh_bloomfilter (unsigned int count,
1148 const GNUNET_HashCode *entries)
1150 struct GNUNET_CONTAINER_BloomFilter *bf;
1153 GNUNET_HashCode mhash;
1157 nsize = compute_bloomfilter_size (count);
1158 *mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
1160 bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1163 for (i=0;i<count;i++)
1165 mingle_hash (&entries[i], *mingle, &mhash);
1166 GNUNET_CONTAINER_bloomfilter_add (bf, &mhash);
1173 * We use a random delay to make the timing of requests less
1174 * predictable. This function returns such a random delay.
1176 * FIXME: make schedule dependent on the specifics of the request?
1177 * Or bandwidth and number of connected peers and load?
1179 * @return random delay to use for some request, between 0 and TTL_DECREMENT ms
1181 static struct GNUNET_TIME_Relative
1182 get_processing_delay ()
1184 return GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1185 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1191 * Function called after we've tried to reserve a certain amount of
1192 * bandwidth for a reply. Check if we succeeded and if so send our
1195 * @param cls the requests "struct PendingRequest*"
1196 * @param peer identifies the peer
1197 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1198 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1199 * @param amount set to the amount that was actually reserved or unreserved
1200 * @param preference current traffic preference for the given peer
1203 target_reservation_cb (void *cls,
1205 GNUNET_PeerIdentity * peer,
1206 unsigned int bpm_in,
1207 unsigned int bpm_out,
1209 uint64_t preference)
1211 struct PendingRequest *pr = cls;
1212 struct ConnectedPeer *cp;
1213 struct PendingMessage *pm;
1214 struct GetMessage *gm;
1215 GNUNET_HashCode *ext;
1223 GNUNET_assert (peer != NULL);
1224 // (3) transmit, update ttl/priority
1225 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1229 /* Peer must have just left */
1232 no_route = GNUNET_NO;
1233 if (amount != DBLOCK_SIZE)
1236 return; /* this target round failed */
1237 /* FIXME: if we are "quite" busy, we may still want to skip
1238 this round; need more load detection code! */
1239 no_route = GNUNET_YES;
1242 /* build message and insert message into priority queue */
1245 if (GNUNET_YES == no_route)
1247 bm |= GET_MESSAGE_BIT_RETURN_TO;
1250 if (pr->namespace != NULL)
1252 bm |= GET_MESSAGE_BIT_SKS_NAMESPACE;
1255 if (pr->target_pid != 0)
1257 bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
1260 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
1261 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1262 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1264 gm = (struct GetMessage*) &pm[1];
1265 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
1266 gm->header.size = htons (msize);
1267 gm->type = htonl (pr->type);
1268 pr->remaining_priority /= 2;
1269 gm->priority = htonl (pr->remaining_priority);
1270 gm->ttl = htonl (pr->ttl);
1271 gm->filter_mutator = htonl(pr->mingle);
1272 gm->hash_bitmap = htonl (bm);
1273 gm->query = pr->query;
1274 ext = (GNUNET_HashCode*) &gm[1];
1276 if (GNUNET_YES == no_route)
1277 GNUNET_PEER_resolve (pr->cp->pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1278 if (pr->namespace != NULL)
1279 memcpy (&ext[k++], pr->namespace, sizeof (GNUNET_HashCode));
1280 if (pr->target_pid != 0)
1281 GNUNET_PEER_resolve (pr->target_pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1282 bfdata = (char *) &ext[k];
1284 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
1287 pm->cont = &transmit_query_continuation;
1289 add_to_pending_messages_for_peer (cp, pm, pr);
1294 * Closure used for "target_peer_select_cb".
1296 struct PeerSelectionContext
1299 * The request for which we are selecting
1302 struct PendingRequest *pr;
1305 * Current "prime" target.
1307 struct GNUNET_PeerIdentity target;
1310 * How much do we like this target?
1312 double target_score;
1318 * Function called for each connected peer to determine
1319 * which one(s) would make good targets for forwarding.
1321 * @param cls closure (struct PeerSelectionContext)
1322 * @param key current key code (peer identity)
1323 * @param value value in the hash map (struct ConnectedPeer)
1324 * @return GNUNET_YES if we should continue to
1329 target_peer_select_cb (void *cls,
1330 const GNUNET_HashCode * key,
1333 struct PeerSelectionContext *psc = cls;
1334 struct ConnectedPeer *cp = value;
1335 struct PendingRequest *pr = psc->pr;
1339 /* 1) check if we have already (recently) forwarded to this peer */
1340 for (i=0;i<pr->used_pids_off;i++)
1341 if (pr->used_pids[i] == cp->pid)
1342 return GNUNET_YES; /* skip */
1343 // 2) calculate how much we'd like to forward to this peer
1344 score = 42; // FIXME!
1345 // FIXME: also need API to gather data on responsiveness
1346 // of this peer (we have fields for that in 'cp', but
1347 // they are never set!)
1349 /* store best-fit in closure */
1350 if (score > psc->target_score)
1352 psc->target_score = score;
1353 psc->target.hashPubKey = *key;
1360 * We're processing a GET request from another peer and have decided
1361 * to forward it to other peers. This function is called periodically
1362 * and should forward the request to other peers until we have all
1363 * possible replies. If we have transmitted the *only* reply to
1364 * the initiator we should destroy the pending request. If we have
1365 * many replies in the queue to the initiator, we should delay sending
1366 * out more queries until the reply queue has shrunk some.
1368 * @param cls our "struct ProcessGetContext *"
1372 forward_request_task (void *cls,
1373 const struct GNUNET_SCHEDULER_TaskContext *tc)
1375 struct PendingRequest *pr = cls;
1376 struct PeerSelectionContext psc;
1377 struct ConnectedPeer *cp;
1379 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1380 get_processing_delay (),
1381 &forward_request_task,
1383 if (pr->irc != NULL)
1384 return; /* previous request still pending */
1385 /* (1) select target */
1387 psc.target_score = DBL_MIN;
1388 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1389 &target_peer_select_cb,
1391 if (psc.target_score == DBL_MIN)
1392 return; /* nobody selected */
1394 /* (2) reserve reply bandwidth */
1395 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1396 &psc.target.hashPubKey);
1397 pr->irc = GNUNET_CORE_peer_change_preference (sched, cfg,
1399 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1400 (uint32_t) -1 /* no limit */,
1402 (uint64_t) cp->inc_preference,
1403 &target_reservation_cb,
1405 cp->inc_preference = 0.0;
1409 /* **************************** P2P PUT Handling ************************ */
1413 * Function called after we either failed or succeeded
1414 * at transmitting a reply to a peer.
1416 * @param cls the requests "struct PendingRequest*"
1417 * @param pid ID of receiving peer, 0 on transmission error
1420 transmit_reply_continuation (void *cls,
1421 GNUNET_PEER_Id tpid)
1423 struct PendingRequest *pr = cls;
1427 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1428 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1429 /* only one reply expected, done with the request! */
1430 destroy_pending_request (pr);
1432 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1433 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1443 * Check if the given KBlock is well-formed.
1445 * @param kb the kblock data (or at least "dsize" bytes claiming to be one)
1446 * @param dsize size of "kb" in bytes; check for < sizeof(struct KBlock)!
1447 * @param query where to store the query that this block answers
1448 * @return GNUNET_OK if this is actually a well-formed KBlock
1451 check_kblock (const struct KBlock *kb,
1453 GNUNET_HashCode *query)
1455 if (dsize < sizeof (struct KBlock))
1457 GNUNET_break_op (0);
1458 return GNUNET_SYSERR;
1460 if (dsize - sizeof (struct KBlock) !=
1461 ntohs (kb->purpose.size)
1462 - sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose)
1463 - sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) )
1465 GNUNET_break_op (0);
1466 return GNUNET_SYSERR;
1469 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_KBLOCK,
1474 GNUNET_break_op (0);
1475 return GNUNET_SYSERR;
1478 GNUNET_CRYPTO_hash (&kb->keyspace,
1479 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1486 * Check if the given SBlock is well-formed.
1488 * @param sb the sblock data (or at least "dsize" bytes claiming to be one)
1489 * @param dsize size of "kb" in bytes; check for < sizeof(struct SBlock)!
1490 * @param query where to store the query that this block answers
1491 * @param namespace where to store the namespace that this block belongs to
1492 * @return GNUNET_OK if this is actually a well-formed SBlock
1495 check_sblock (const struct SBlock *sb,
1497 GNUNET_HashCode *query,
1498 GNUNET_HashCode *namespace)
1500 if (dsize < sizeof (struct SBlock))
1502 GNUNET_break_op (0);
1503 return GNUNET_SYSERR;
1506 ntohs (sb->purpose.size) + sizeof (struct GNUNET_CRYPTO_RsaSignature))
1508 GNUNET_break_op (0);
1509 return GNUNET_SYSERR;
1512 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_SBLOCK,
1517 GNUNET_break_op (0);
1518 return GNUNET_SYSERR;
1521 *query = sb->identifier;
1522 if (namespace != NULL)
1523 GNUNET_CRYPTO_hash (&sb->subspace,
1524 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1531 * Transmit the given message by copying it to the target buffer
1532 * "buf". "buf" will be NULL and "size" zero if the socket was closed
1533 * for writing in the meantime. In that case, do nothing
1534 * (the disconnect or shutdown handler will take care of the rest).
1535 * If we were able to transmit messages and there are still more
1536 * pending, ask core again for further calls to this function.
1538 * @param cls closure, pointer to the 'struct ClientList*'
1539 * @param size number of bytes available in buf
1540 * @param buf where the callee should write the message
1541 * @return number of bytes written to buf
1544 transmit_to_client (void *cls,
1545 size_t size, void *buf)
1547 struct ClientList *cl = cls;
1549 struct ClientResponseMessage *creply;
1556 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1557 "Not sending reply, client communication problem.\n");
1562 while ( (NULL != (creply = cl->res_head) ) &&
1563 (creply->msize <= size) )
1565 memcpy (&cbuf[msize], &creply[1], creply->msize);
1566 msize += creply->msize;
1567 size -= creply->msize;
1568 GNUNET_CONTAINER_DLL_remove (cl->res_head,
1571 GNUNET_free (creply);
1574 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
1576 GNUNET_TIME_UNIT_FOREVER_REL,
1577 &transmit_to_client,
1580 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1581 "Transmitted %u bytes to client\n",
1582 (unsigned int) msize);
1589 * Closure for "process_reply" function.
1591 struct ProcessReplyClosure
1594 * The data for the reply.
1598 // FIXME: add 'struct ConnectedPeer' to track 'last_xxx_replies' here!
1601 * When the reply expires.
1603 struct GNUNET_TIME_Absolute expiration;
1611 * Namespace that this reply belongs to
1612 * (if it is of type SBLOCK).
1614 GNUNET_HashCode namespace;
1617 * Type of the block.
1622 * How much was this reply worth to us?
1629 * We have received a reply; handle it!
1631 * @param cls response (struct ProcessReplyClosure)
1632 * @param key our query
1633 * @param value value in the hash map (info about the query)
1634 * @return GNUNET_YES (we should continue to iterate)
1637 process_reply (void *cls,
1638 const GNUNET_HashCode * key,
1641 struct ProcessReplyClosure *prq = cls;
1642 struct PendingRequest *pr = value;
1643 struct PendingMessage *reply;
1644 struct ClientResponseMessage *creply;
1645 struct ClientList *cl;
1646 struct PutMessage *pm;
1647 struct ConnectedPeer *cp;
1648 GNUNET_HashCode chash;
1649 GNUNET_HashCode mhash;
1654 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1655 "Matched result for query `%s' with pending request\n",
1658 GNUNET_CRYPTO_hash (prq->data,
1663 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1664 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1665 /* only possible reply, stop requesting! */
1666 while (NULL != pr->pending_head)
1667 destroy_pending_message_list_entry (pr->pending_head);
1668 GNUNET_break (GNUNET_YES ==
1669 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
1673 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1674 if (0 != memcmp (pr->namespace,
1676 sizeof (GNUNET_HashCode)))
1677 return GNUNET_YES; /* wrong namespace */
1678 /* then: fall-through! */
1679 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1682 mingle_hash (&chash, pr->mingle, &mhash);
1683 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
1685 return GNUNET_YES; /* duplicate */
1686 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
1689 if (pr->client_request_list != NULL)
1691 if (pr->replies_seen_size == pr->replies_seen_off)
1693 GNUNET_array_grow (pr->replies_seen,
1694 pr->replies_seen_size,
1695 pr->replies_seen_size * 2 + 4);
1697 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
1698 pr->bf = refresh_bloomfilter (pr->replies_seen_off,
1703 pr->replies_seen[pr->replies_seen_off++] = chash;
1707 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
1708 // FIXME: any checks against duplicates for SKBlocks?
1714 prio = pr->priority;
1715 prq->priority += pr->remaining_priority;
1716 pr->remaining_priority = 0;
1717 if (pr->client_request_list != NULL)
1720 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1721 "Transmitting result for query `%s' to local client\n",
1724 cl = pr->client_request_list->client_list;
1725 msize = sizeof (struct PutMessage) + prq->size;
1726 creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
1727 creply->msize = msize;
1728 creply->client_list = cl;
1729 GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
1733 pm = (struct PutMessage*) &creply[1];
1734 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
1735 pm->header.size = htons (msize);
1736 pm->type = htonl (prq->type);
1737 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
1738 memcpy (&pm[1], prq->data, prq->size);
1740 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
1742 GNUNET_TIME_UNIT_FOREVER_REL,
1743 &transmit_to_client,
1745 GNUNET_break (cl->th != NULL);
1751 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1752 "Transmitting result for query `%s' to other peer (PID=%u)\n",
1754 (unsigned int) cp->pid);
1756 msize = sizeof (struct PutMessage) + prq->size;
1757 reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
1758 reply->cont = &transmit_reply_continuation;
1759 reply->cont_cls = pr;
1760 reply->msize = msize;
1761 reply->priority = (uint32_t) -1; /* send replies first! */
1762 pm = (struct PutMessage*) &reply[1];
1763 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
1764 pm->header.size = htons (msize);
1765 pm->type = htonl (prq->type);
1766 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
1767 memcpy (&pm[1], prq->data, prq->size);
1768 add_to_pending_messages_for_peer (cp, reply, pr);
1772 // FIXME: implement hot-path routing statistics keeping!
1778 * Handle P2P "PUT" message.
1780 * @param cls closure, always NULL
1781 * @param other the other peer involved (sender or receiver, NULL
1782 * for loopback messages where we are both sender and receiver)
1783 * @param message the actual message
1784 * @param latency reported latency of the connection with 'other'
1785 * @param distance reported distance (DV) to 'other'
1786 * @return GNUNET_OK to keep the connection open,
1787 * GNUNET_SYSERR to close it (signal serious error)
1790 handle_p2p_put (void *cls,
1791 const struct GNUNET_PeerIdentity *other,
1792 const struct GNUNET_MessageHeader *message,
1793 struct GNUNET_TIME_Relative latency,
1796 const struct PutMessage *put;
1800 struct GNUNET_TIME_Absolute expiration;
1801 GNUNET_HashCode query;
1802 struct ProcessReplyClosure prq;
1804 msize = ntohs (message->size);
1805 if (msize < sizeof (struct PutMessage))
1808 return GNUNET_SYSERR;
1810 put = (const struct PutMessage*) message;
1811 dsize = msize - sizeof (struct PutMessage);
1812 type = ntohl (put->type);
1813 expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
1815 /* first, validate! */
1818 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1819 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1820 GNUNET_CRYPTO_hash (&put[1], dsize, &query);
1822 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1824 check_kblock ((const struct KBlock*) &put[1],
1827 return GNUNET_SYSERR;
1829 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1831 check_sblock ((const struct SBlock*) &put[1],
1835 return GNUNET_SYSERR;
1837 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
1838 // FIXME -- validate SKBLOCK!
1842 /* unknown block type */
1843 GNUNET_break_op (0);
1844 return GNUNET_SYSERR;
1848 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1849 "Received result for query `%s' from peer `%4s'\n",
1850 GNUNET_h2s (&query),
1851 GNUNET_i2s (other));
1853 /* now, lookup 'query' */
1854 prq.data = (const void*) &put[1];
1857 prq.expiration = expiration;
1859 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
1863 // FIXME: if migration is on and load is low,
1864 // queue to store data in datastore;
1865 // use "prq.priority" for that!
1870 /* **************************** P2P GET Handling ************************ */
1874 * We're processing (local) results for a search request
1875 * from another peer. Pass applicable results to the
1876 * peer and if we are done either clean up (operation
1877 * complete) or forward to other peers (more results possible).
1879 * @param cls our closure (struct LocalGetContext)
1880 * @param key key for the content
1881 * @param size number of bytes in data
1882 * @param data content stored
1883 * @param type type of the content
1884 * @param priority priority of the content
1885 * @param anonymity anonymity-level for the content
1886 * @param expiration expiration time for the content
1887 * @param uid unique identifier for the datum;
1888 * maybe 0 if no unique identifier is available
1891 process_local_reply (void *cls,
1892 const GNUNET_HashCode * key,
1898 struct GNUNET_TIME_Absolute
1902 struct PendingRequest *pr = cls;
1903 struct ProcessReplyClosure prq;
1904 GNUNET_HashCode dhash;
1905 GNUNET_HashCode mhash;
1906 GNUNET_HashCode query;
1911 if (pr->client_request_list != NULL)
1912 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
1914 /* no more results */
1915 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1916 pr->task = GNUNET_SCHEDULER_add_now (sched,
1917 &forward_request_task,
1921 if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
1924 GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
1925 anonymity, expiration, uid,
1926 &process_local_reply,
1928 GNUNET_FS_drq_get_next (GNUNET_YES);
1931 /* check for duplicates */
1932 GNUNET_CRYPTO_hash (data, size, &dhash);
1933 mingle_hash (&dhash,
1936 if ( (pr->bf != NULL) &&
1938 GNUNET_CONTAINER_bloomfilter_test (pr->bf,
1942 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1943 "Result from datastore filtered by bloomfilter (duplicate).\n");
1945 GNUNET_FS_drq_get_next (GNUNET_YES);
1949 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1950 "Found result for query `%s' in local datastore\n",
1953 pr->results_found++;
1954 if ( (pr->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
1955 (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
1956 (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) )
1961 pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1965 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
1968 memset (&prq, 0, sizeof (prq));
1970 prq.expiration = expiration;
1972 if ( (type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) &&
1973 (GNUNET_OK != check_sblock ((const struct SBlock*) data,
1979 /* FIXME: consider removing the block? */
1980 GNUNET_FS_drq_get_next (GNUNET_YES);
1984 prq.priority = priority;
1985 process_reply (&prq, key, pr);
1987 if ( (GNUNET_YES == test_load_too_high()) ||
1988 (pr->results_found > 5 + 2 * pr->priority) )
1990 GNUNET_FS_drq_get_next (GNUNET_NO);
1993 GNUNET_FS_drq_get_next (GNUNET_YES);
1998 * The priority level imposes a bound on the maximum
1999 * value for the ttl that can be requested.
2001 * @param ttl_in requested ttl
2002 * @param prio given priority
2003 * @return ttl_in if ttl_in is below the limit,
2004 * otherwise the ttl-limit for the given priority
2007 bound_ttl (int32_t ttl_in, uint32_t prio)
2009 unsigned long long allowed;
2013 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
2014 if (ttl_in > allowed)
2016 if (allowed >= (1 << 30))
2025 * We've received a request with the specified priority. Bound it
2026 * according to how much we trust the given peer.
2028 * @param prio_in requested priority
2029 * @param cp the peer making the request
2030 * @return effective priority
2033 bound_priority (uint32_t prio_in,
2034 struct ConnectedPeer *cp)
2041 * Closure for 'check_duplicate_request'.
2043 struct CheckDuplicateRequestClosure
2046 * The new request we should check if it already exists.
2048 const struct PendingRequest *pr;
2051 * Existing request found by the checker, NULL if none.
2053 struct PendingRequest *have;
2058 * Iterator over entries in the 'query_request_map' that
2059 * tries to see if we have the same request pending from
2060 * the same peer already.
2062 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
2063 * @param key current key code (query, ignored, must match)
2064 * @param value value in the hash map (a 'struct PendingRequest'
2065 * that already exists)
2066 * @return GNUNET_YES if we should continue to
2067 * iterate (no match yet)
2068 * GNUNET_NO if not (match found).
2071 check_duplicate_request (void *cls,
2072 const GNUNET_HashCode * key,
2075 struct CheckDuplicateRequestClosure *cdc = cls;
2076 struct PendingRequest *have = value;
2078 if (cdc->pr->target_pid == have->target_pid)
2088 * Handle P2P "GET" request.
2090 * @param cls closure, always NULL
2091 * @param other the other peer involved (sender or receiver, NULL
2092 * for loopback messages where we are both sender and receiver)
2093 * @param message the actual message
2094 * @param latency reported latency of the connection with 'other'
2095 * @param distance reported distance (DV) to 'other'
2096 * @return GNUNET_OK to keep the connection open,
2097 * GNUNET_SYSERR to close it (signal serious error)
2100 handle_p2p_get (void *cls,
2101 const struct GNUNET_PeerIdentity *other,
2102 const struct GNUNET_MessageHeader *message,
2103 struct GNUNET_TIME_Relative latency,
2106 struct PendingRequest *pr;
2107 struct ConnectedPeer *cp;
2108 struct ConnectedPeer *cps;
2109 struct CheckDuplicateRequestClosure cdc;
2110 struct GNUNET_TIME_Relative timeout;
2112 const struct GetMessage *gm;
2114 const GNUNET_HashCode *opt;
2117 uint32_t ttl_decrement;
2121 msize = ntohs(message->size);
2122 if (msize < sizeof (struct GetMessage))
2124 GNUNET_break_op (0);
2125 return GNUNET_SYSERR;
2127 gm = (const struct GetMessage*) message;
2128 bm = ntohl (gm->hash_bitmap);
2136 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
2138 GNUNET_break_op (0);
2139 return GNUNET_SYSERR;
2141 opt = (const GNUNET_HashCode*) &gm[1];
2142 bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
2143 bm = ntohl (gm->hash_bitmap);
2144 if ( (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)) &&
2145 (ntohl (gm->type) == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) )
2147 GNUNET_break_op (0);
2148 return GNUNET_SYSERR;
2151 cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2152 &other->hashPubKey);
2153 GNUNET_assert (NULL != cps);
2154 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
2155 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2161 /* FIXME: try connect? */
2164 /* note that we can really only check load here since otherwise
2165 peers could find out that we are overloaded by not being
2166 disconnected after sending us a malformed query... */
2167 if (GNUNET_YES == test_load_too_high ())
2170 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2171 "Dropping query from `%s', this peer is too busy.\n",
2172 GNUNET_i2s (other));
2178 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2179 "Received request for `%s' of type %u from peer `%4s'\n",
2180 GNUNET_h2s (&gm->query),
2181 (unsigned int) ntohl (gm->type),
2182 GNUNET_i2s (other));
2184 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
2185 (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)?sizeof(GNUNET_HashCode):0);
2186 if ((bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2187 pr->namespace = (GNUNET_HashCode*) &pr[1];
2188 pr->type = ntohl (gm->type);
2189 pr->mingle = ntohl (gm->filter_mutator);
2190 if (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2191 memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
2192 else if (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)
2194 GNUNET_break_op (0);
2196 return GNUNET_SYSERR;
2198 if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
2199 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
2201 pr->anonymity_level = 1;
2202 pr->priority = bound_priority (ntohl (gm->priority), cps);
2203 pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
2204 pr->query = gm->query;
2205 /* decrement ttl (always) */
2206 ttl_decrement = 2 * TTL_DECREMENT +
2207 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2209 if ( (pr->ttl < 0) &&
2210 (pr->ttl - ttl_decrement > 0) )
2213 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2214 "Dropping query from `%s' due to TTL underflow.\n",
2215 GNUNET_i2s (other));
2217 /* integer underflow => drop (should be very rare)! */
2221 pr->ttl -= ttl_decrement;
2222 pr->start_time = GNUNET_TIME_absolute_get ();
2224 /* get bloom filter */
2227 pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
2230 pr->bf_size = bfsize;
2235 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2237 &check_duplicate_request,
2239 if (cdc.have != NULL)
2241 if (cdc.have->start_time.value + cdc.have->ttl >=
2242 pr->start_time.value + pr->ttl)
2244 /* existing request has higher TTL, drop new one! */
2245 cdc.have->priority += pr->priority;
2246 destroy_pending_request (pr);
2251 /* existing request has lower TTL, drop old one! */
2252 pr->priority += cdc.have->priority;
2253 /* Possible optimization: if we have applicable pending
2254 replies in 'cdc.have', we might want to move those over
2255 (this is a really rare special-case, so it is not clear
2256 that this would be worth it) */
2257 destroy_pending_request (cdc.have);
2258 /* keep processing 'pr'! */
2263 GNUNET_CONTAINER_multihashmap_put (query_request_map,
2266 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2267 GNUNET_CONTAINER_multihashmap_put (peer_request_map,
2270 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2272 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
2274 pr->start_time.value + pr->ttl);
2277 /* calculate change in traffic preference */
2278 preference = (double) pr->priority;
2279 if (preference < QUERY_BANDWIDTH_VALUE)
2280 preference = QUERY_BANDWIDTH_VALUE;
2281 cps->inc_preference += preference;
2283 /* process locally */
2285 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2286 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2287 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
2288 (pr->priority + 1));
2289 pr->drq = GNUNET_FS_drq_get (&gm->query,
2291 &process_local_reply,
2296 /* Are multiple results possible? If so, start processing remotely now! */
2299 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2300 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2301 /* only one result, wait for datastore */
2304 pr->task = GNUNET_SCHEDULER_add_now (sched,
2305 &forward_request_task,
2309 /* make sure we don't track too many requests */
2310 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
2312 pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
2313 destroy_pending_request (pr);
2319 /* **************************** CS GET Handling ************************ */
2323 * Handle START_SEARCH-message (search request from client).
2325 * @param cls closure
2326 * @param client identification of the client
2327 * @param message the actual message
2330 handle_start_search (void *cls,
2331 struct GNUNET_SERVER_Client *client,
2332 const struct GNUNET_MessageHeader *message)
2334 static GNUNET_HashCode all_zeros;
2335 const struct SearchMessage *sm;
2336 struct ClientList *cl;
2337 struct ClientRequestList *crl;
2338 struct PendingRequest *pr;
2343 msize = ntohs (message->size);
2344 if ( (msize < sizeof (struct SearchMessage)) ||
2345 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
2348 GNUNET_SERVER_receive_done (client,
2352 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
2353 sm = (const struct SearchMessage*) message;
2356 while ( (cl != NULL) &&
2357 (cl->client != client) )
2361 cl = GNUNET_malloc (sizeof (struct ClientList));
2362 cl->client = client;
2363 GNUNET_SERVER_client_keep (client);
2364 cl->next = client_list;
2367 type = ntohl (sm->type);
2369 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2370 "Received request for `%s' of type %u from local client\n",
2371 GNUNET_h2s (&sm->query),
2372 (unsigned int) type);
2375 /* detect duplicate KBLOCK requests */
2376 if (type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK)
2379 while ( (crl != NULL) &&
2380 ( (0 != memcmp (&crl->req->query,
2382 sizeof (GNUNET_HashCode))) ||
2383 (crl->req->type != type) ) )
2388 /* Duplicate request (used to send long list of
2389 known/blocked results); merge 'pr->replies_seen'
2390 and update bloom filter */
2391 GNUNET_array_grow (pr->replies_seen,
2392 pr->replies_seen_size,
2393 pr->replies_seen_off + sc);
2394 memcpy (&pr->replies_seen[pr->replies_seen_off],
2396 sc * sizeof (GNUNET_HashCode));
2397 pr->replies_seen_off += sc;
2399 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
2400 pr->bf = refresh_bloomfilter (pr->replies_seen_off,
2404 GNUNET_SERVER_receive_done (client,
2409 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
2410 ((type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)?sizeof(GNUNET_HashCode):0));
2411 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
2412 memset (crl, 0, sizeof (struct ClientRequestList));
2413 crl->client_list = cl;
2414 GNUNET_CONTAINER_DLL_insert (cl->rl_head,
2419 pr->client_request_list = crl;
2420 GNUNET_array_grow (pr->replies_seen,
2421 pr->replies_seen_size,
2423 memcpy (pr->replies_seen,
2425 sc * sizeof (GNUNET_HashCode));
2426 pr->replies_seen_off = sc;
2427 pr->anonymity_level = ntohl (sm->anonymity_level);
2428 pr->bf = refresh_bloomfilter (pr->replies_seen_off,
2432 pr->query = sm->query;
2435 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2436 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2437 if (0 != memcmp (&sm->target,
2439 sizeof (GNUNET_HashCode)))
2440 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
2442 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2443 pr->namespace = (GNUNET_HashCode*) &pr[1];
2444 memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
2449 GNUNET_CONTAINER_multihashmap_put (query_request_map,
2452 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2453 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2454 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* get on-demand blocks too! */
2455 pr->drq = GNUNET_FS_drq_get (&sm->query,
2457 &process_local_reply,
2459 GNUNET_TIME_UNIT_FOREVER_REL,
2464 /* **************************** Startup ************************ */
2468 * List of handlers for P2P messages
2469 * that we care about.
2471 static struct GNUNET_CORE_MessageHandler p2p_handlers[] =
2474 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
2476 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
2482 * List of handlers for the messages understood by this
2485 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2486 {&GNUNET_FS_handle_index_start, NULL,
2487 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
2488 {&GNUNET_FS_handle_index_list_get, NULL,
2489 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
2490 {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
2491 sizeof (struct UnindexMessage) },
2492 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
2499 * Process fs requests.
2501 * @param cls closure
2502 * @param s scheduler to use
2503 * @param server the initialized server
2504 * @param c configuration to use
2507 main_init (struct GNUNET_SCHEDULER_Handle *s,
2508 struct GNUNET_SERVER_Handle *server,
2509 const struct GNUNET_CONFIGURATION_Handle *c)
2513 connected_peers = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2514 query_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2515 peer_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2516 requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2517 core = GNUNET_CORE_connect (sched,
2519 GNUNET_TIME_UNIT_FOREVER_REL,
2523 &peer_connect_handler,
2524 &peer_disconnect_handler,
2530 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2531 _("Failed to connect to `%s' service.\n"),
2533 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
2534 connected_peers = NULL;
2535 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
2536 query_request_map = NULL;
2537 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
2538 requests_by_expiration_heap = NULL;
2539 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
2540 peer_request_map = NULL;
2542 return GNUNET_SYSERR;
2544 GNUNET_SERVER_disconnect_notify (server,
2545 &handle_client_disconnect,
2547 GNUNET_SERVER_add_handlers (server, handlers);
2548 GNUNET_SCHEDULER_add_delayed (sched,
2549 GNUNET_TIME_UNIT_FOREVER_REL,
2557 * Process fs requests.
2559 * @param cls closure
2560 * @param sched scheduler to use
2561 * @param server the initialized server
2562 * @param cfg configuration to use
2566 struct GNUNET_SCHEDULER_Handle *sched,
2567 struct GNUNET_SERVER_Handle *server,
2568 const struct GNUNET_CONFIGURATION_Handle *cfg)
2570 if ( (GNUNET_OK != GNUNET_FS_drq_init (sched, cfg)) ||
2571 (GNUNET_OK != GNUNET_FS_indexing_init (sched, cfg)) ||
2572 (GNUNET_OK != main_init (sched, server, cfg)) )
2574 GNUNET_SCHEDULER_shutdown (sched);
2581 * The main function for the fs service.
2583 * @param argc number of arguments from the command line
2584 * @param argv command line arguments
2585 * @return 0 ok, 1 on error
2588 main (int argc, char *const *argv)
2590 return (GNUNET_OK ==
2591 GNUNET_SERVICE_run (argc,
2594 GNUNET_SERVICE_OPTION_NONE,
2595 &run, NULL)) ? 0 : 1;
2598 /* end of gnunet-service-fs.c */