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 * Hash map entry of requests we are performing
326 * on behalf of the same peer.
328 struct PeerRequestEntry
332 * Request this entry represents.
334 struct PendingRequest *req;
337 * Entry of peer responsible for this entry.
339 struct ConnectedPeer *cp;
345 * Doubly-linked list of messages we are performing
346 * due to a pending request.
348 struct PendingMessageList
352 * This is a doubly-linked list of messages on behalf of the same request.
354 struct PendingMessageList *next;
357 * This is a doubly-linked list of messages on behalf of the same request.
359 struct PendingMessageList *prev;
362 * Message this entry represents.
364 struct PendingMessage *pm;
367 * Request this entry belongs to.
369 struct PendingRequest *req;
372 * Peer this message is targeted for.
374 struct ConnectedPeer *target;
380 * Information we keep for each pending request. We should try to
381 * keep this struct as small as possible since its memory consumption
382 * is key to how many requests we can have pending at once.
384 struct PendingRequest
388 * If this request was made by a client, this is our entry in the
389 * client request list; otherwise NULL.
391 struct ClientRequestList *client_request_list;
394 * If this request was made by a peer, this is our entry in the
395 * per-peer multi-hash map; otherwise NULL.
397 struct PeerRequestEntry *pht_entry;
400 * If this is a namespace query, pointer to the hash of the public
401 * key of the namespace; otherwise NULL. Pointer will be to the
402 * end of this struct (so no need to free it).
404 const GNUNET_HashCode *namespace;
407 * Bloomfilter we use to filter out replies that we don't care about
408 * (anymore). NULL as long as we are interested in all replies.
410 struct GNUNET_CONTAINER_BloomFilter *bf;
413 * Context of our GNUNET_CORE_peer_change_preference call.
415 struct GNUNET_CORE_InformationRequestContext *irc;
418 * Hash code of all replies that we have seen so far (only valid
419 * if client is not NULL since we only track replies like this for
422 GNUNET_HashCode *replies_seen;
425 * Node in the heap representing this entry; NULL
426 * if we have no heap node.
428 struct GNUNET_CONTAINER_HeapNode *hnode;
431 * Head of list of messages being performed on behalf of this
434 struct PendingMessageList *pending_head;
437 * Tail of list of messages being performed on behalf of this
440 struct PendingMessageList *pending_tail;
443 * When did we first see this request (form this peer), or, if our
444 * client is initiating, when did we last initiate a search?
446 struct GNUNET_TIME_Absolute start_time;
449 * The query that this request is for.
451 GNUNET_HashCode query;
454 * The task responsible for transmitting queries
457 GNUNET_SCHEDULER_TaskIdentifier task;
460 * (Interned) Peer identifier that identifies a preferred target
463 GNUNET_PEER_Id target_pid;
466 * (Interned) Peer identifiers of peers that have already
467 * received our query for this content.
469 GNUNET_PEER_Id *used_pids;
472 * Our entry in the DRQ (non-NULL while we wait for our
473 * turn to interact with the local database).
475 struct DatastoreRequestQueue *drq;
478 * Size of the 'bf' (in bytes).
483 * Desired anonymity level; only valid for requests from a local client.
485 uint32_t anonymity_level;
488 * How many entries in "used_pids" are actually valid?
490 unsigned int used_pids_off;
493 * How long is the "used_pids" array?
495 unsigned int used_pids_size;
498 * Number of results found for this request.
500 unsigned int results_found;
503 * How many entries in "replies_seen" are actually valid?
505 unsigned int replies_seen_off;
508 * How long is the "replies_seen" array?
510 unsigned int replies_seen_size;
513 * Priority with which this request was made. If one of our clients
514 * made the request, then this is the current priority that we are
515 * using when initiating the request. This value is used when
516 * we decide to reward other peers with trust for providing a reply.
521 * Priority points left for us to spend when forwarding this request
524 uint32_t remaining_priority;
527 * Number to mingle hashes for bloom-filter tests with.
532 * TTL with which we saw this request (or, if we initiated, TTL that
533 * we used for the request).
538 * Type of the content that this request is for.
548 static struct GNUNET_SCHEDULER_Handle *sched;
553 const struct GNUNET_CONFIGURATION_Handle *cfg;
556 * Map of peer identifiers to "struct ConnectedPeer" (for that peer).
558 static struct GNUNET_CONTAINER_MultiHashMap *connected_peers;
561 * Map of peer identifiers to "struct PendingRequest" (for that peer).
563 static struct GNUNET_CONTAINER_MultiHashMap *peer_request_map;
566 * Map of query identifiers to "struct PendingRequest" (for that query).
568 static struct GNUNET_CONTAINER_MultiHashMap *query_request_map;
571 * Heap with the request that will expire next at the top. Contains
572 * pointers of type "struct PendingRequest*"; these will *also* be
573 * aliased from the "requests_by_peer" data structures and the
574 * "requests_by_query" table. Note that requests from our clients
575 * don't expire and are thus NOT in the "requests_by_expiration"
576 * (or the "requests_by_peer" tables).
578 static struct GNUNET_CONTAINER_Heap *requests_by_expiration_heap;
581 * Linked list of clients we are currently processing requests for.
583 struct ClientList *client_list;
586 * Pointer to handle to the core service (points to NULL until we've
589 struct GNUNET_CORE_Handle *core;
592 /* ******************* clean up functions ************************ */
596 * We're done with a particular message list entry.
597 * Free all associated resources.
599 * @param pml entry to destroy
602 destroy_pending_message_list_entry (struct PendingMessageList *pml)
604 GNUNET_CONTAINER_DLL_remove (pml->req->pending_head,
605 pml->req->pending_tail,
607 GNUNET_CONTAINER_DLL_remove (pml->target->pending_messages_head,
608 pml->target->pending_messages_tail,
610 pml->target->pending_requests--;
611 GNUNET_free (pml->pm);
617 * Destroy the given pending message (and call the respective
620 * @param pm message to destroy
621 * @param tpid id of peer that the message was delivered to, or 0 for none
624 destroy_pending_message (struct PendingMessage *pm,
627 struct PendingMessageList *pml = pm->pml;
629 GNUNET_assert (pml->pm == pm);
630 GNUNET_assert ( (tpid == 0) || (tpid == pml->target->pid) );
631 pm->cont (pm->cont_cls, 0);
632 destroy_pending_message_list_entry (pml);
638 * We're done processing a particular request.
639 * Free all associated resources.
641 * @param pr request to destroy
644 destroy_pending_request (struct PendingRequest *pr)
646 struct GNUNET_PeerIdentity pid;
648 if (pr->hnode != NULL)
650 GNUNET_CONTAINER_heap_remove_node (requests_by_expiration_heap,
654 /* might have already been removed from map in 'process_reply' (if
655 there was a unique reply) or never inserted if it was a
656 duplicate; hence ignore the return value here */
657 (void) GNUNET_CONTAINER_multihashmap_remove (query_request_map,
662 GNUNET_FS_drq_get_cancel (pr->drq);
665 if (pr->client_request_list != NULL)
667 GNUNET_CONTAINER_DLL_remove (pr->client_request_list->client_list->rl_head,
668 pr->client_request_list->client_list->rl_tail,
669 pr->client_request_list);
670 GNUNET_free (pr->client_request_list);
671 pr->client_request_list = NULL;
673 if (pr->pht_entry != NULL)
675 GNUNET_PEER_resolve (pr->pht_entry->cp->pid,
677 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
680 GNUNET_free (pr->pht_entry);
681 pr->pht_entry = NULL;
685 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
690 GNUNET_CORE_peer_change_preference_cancel (pr->irc);
693 if (pr->replies_seen != NULL)
695 GNUNET_free (pr->replies_seen);
696 pr->replies_seen = NULL;
698 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
700 GNUNET_SCHEDULER_cancel (sched,
702 pr->task = GNUNET_SCHEDULER_NO_TASK;
704 while (NULL != pr->pending_head)
705 destroy_pending_message_list_entry (pr->pending_head);
706 GNUNET_PEER_change_rc (pr->target_pid, -1);
707 if (pr->used_pids != NULL)
709 GNUNET_PEER_decrement_rcs (pr->used_pids, pr->used_pids_off);
710 GNUNET_free (pr->used_pids);
711 pr->used_pids_off = 0;
712 pr->used_pids_size = 0;
713 pr->used_pids = NULL;
720 * Method called whenever a given peer connects.
722 * @param cls closure, not used
723 * @param peer peer identity this notification is about
724 * @param latency reported latency of the connection with 'other'
725 * @param distance reported distance (DV) to 'other'
728 peer_connect_handler (void *cls,
730 GNUNET_PeerIdentity * peer,
731 struct GNUNET_TIME_Relative latency,
734 struct ConnectedPeer *cp;
736 cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
737 cp->pid = GNUNET_PEER_intern (peer);
738 GNUNET_CONTAINER_multihashmap_put (connected_peers,
741 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
746 * Free (each) request made by the peer.
748 * @param cls closure, points to peer that the request belongs to
749 * @param key current key code
750 * @param value value in the hash map
751 * @return GNUNET_YES (we should continue to iterate)
754 destroy_request (void *cls,
755 const GNUNET_HashCode * key,
758 const struct GNUNET_PeerIdentity * peer = cls;
759 struct PendingRequest *pr = value;
761 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
764 destroy_pending_request (pr);
770 * Method called whenever a peer disconnects.
772 * @param cls closure, not used
773 * @param peer peer identity this notification is about
776 peer_disconnect_handler (void *cls,
778 GNUNET_PeerIdentity * peer)
780 struct ConnectedPeer *cp;
781 struct PendingMessage *pm;
784 GNUNET_CONTAINER_multihashmap_get_multiple (peer_request_map,
788 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
792 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
794 if (NULL != cp->last_client_replies[i])
796 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
797 cp->last_client_replies[i] = NULL;
800 GNUNET_CONTAINER_multihashmap_remove (connected_peers,
803 GNUNET_PEER_change_rc (cp->pid, -1);
804 GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
806 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
807 while (NULL != (pm = cp->pending_messages_head))
808 destroy_pending_message (pm, 0 /* delivery failed */);
809 GNUNET_break (0 == cp->pending_requests);
815 * Iterator over hash map entries that removes all occurences
816 * of the given 'client' from the 'last_client_replies' of the
817 * given connected peer.
819 * @param cls closure, the 'struct GNUNET_SERVER_Client*' to remove
820 * @param key current key code (unused)
821 * @param value value in the hash map (the 'struct ConnectedPeer*' to change)
822 * @return GNUNET_YES (we should continue to iterate)
825 remove_client_from_last_client_replies (void *cls,
826 const GNUNET_HashCode * key,
829 struct GNUNET_SERVER_Client *client = cls;
830 struct ConnectedPeer *cp = value;
833 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
835 if (cp->last_client_replies[i] == client)
837 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
838 cp->last_client_replies[i] = NULL;
846 * A client disconnected. Remove all of its pending queries.
848 * @param cls closure, NULL
849 * @param client identification of the client
852 handle_client_disconnect (void *cls,
853 struct GNUNET_SERVER_Client
856 struct ClientList *pos;
857 struct ClientList *prev;
858 struct ClientRequestList *rcl;
859 struct ClientResponseMessage *creply;
862 return; /* huh? is this allowed? */
865 while ( (NULL != pos) &&
866 (pos->client != client) )
872 return; /* no requests pending for this client */
873 while (NULL != (rcl = pos->rl_head))
874 destroy_pending_request (rcl->req);
876 client_list = pos->next;
878 prev->next = pos->next;
881 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
884 while (NULL != (creply = pos->res_head))
886 GNUNET_CONTAINER_DLL_remove (pos->res_head,
889 GNUNET_free (creply);
891 GNUNET_SERVER_client_drop (pos->client);
893 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
894 &remove_client_from_last_client_replies,
900 * Iterator to free peer entries.
902 * @param cls closure, unused
903 * @param key current key code
904 * @param value value in the hash map (peer entry)
905 * @return GNUNET_YES (we should continue to iterate)
908 clean_peer (void *cls,
909 const GNUNET_HashCode * key,
912 peer_disconnect_handler (NULL, (const struct GNUNET_PeerIdentity*) key);
918 * Task run during shutdown.
924 shutdown_task (void *cls,
925 const struct GNUNET_SCHEDULER_TaskContext *tc)
927 while (client_list != NULL)
928 handle_client_disconnect (NULL,
929 client_list->client);
930 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
933 GNUNET_break (0 == GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap));
934 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
935 requests_by_expiration_heap = 0;
936 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
937 connected_peers = NULL;
938 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (query_request_map));
939 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
940 query_request_map = NULL;
941 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (peer_request_map));
942 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
943 peer_request_map = NULL;
944 GNUNET_assert (NULL != core);
945 GNUNET_CORE_disconnect (core);
952 /* ******************* Utility functions ******************** */
956 * Transmit the given message by copying it to the target buffer
957 * "buf". "buf" will be NULL and "size" zero if the socket was closed
958 * for writing in the meantime. In that case, do nothing
959 * (the disconnect or shutdown handler will take care of the rest).
960 * If we were able to transmit messages and there are still more
961 * pending, ask core again for further calls to this function.
963 * @param cls closure, pointer to the 'struct ConnectedPeer*'
964 * @param size number of bytes available in buf
965 * @param buf where the callee should write the message
966 * @return number of bytes written to buf
969 transmit_to_peer (void *cls,
970 size_t size, void *buf)
972 struct ConnectedPeer *cp = cls;
974 struct GNUNET_PeerIdentity pid;
975 struct PendingMessage *pm;
982 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
983 "Dropping reply, core too busy.\n");
988 while ( (NULL != (pm = cp->pending_messages_head) ) &&
989 (pm->msize <= size) )
991 memcpy (&cbuf[msize], &pm[1], pm->msize);
994 destroy_pending_message (pm, cp->pid);
998 GNUNET_PEER_resolve (cp->pid,
1000 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1002 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1013 * Add a message to the set of pending messages for the given peer.
1015 * @param cp peer to send message to
1016 * @param pm message to queue
1017 * @param pr request on which behalf this message is being queued
1020 add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
1021 struct PendingMessage *pm,
1022 struct PendingRequest *pr)
1024 struct PendingMessage *pos;
1025 struct PendingMessageList *pml;
1026 struct GNUNET_PeerIdentity pid;
1028 GNUNET_assert (pm->next == NULL);
1029 GNUNET_assert (pm->pml == NULL);
1030 pml = GNUNET_malloc (sizeof (struct PendingMessageList));
1035 GNUNET_CONTAINER_DLL_insert (pr->pending_head,
1038 pos = cp->pending_messages_head;
1039 while ( (pos != NULL) &&
1040 (pm->priority < pos->priority) )
1042 GNUNET_CONTAINER_DLL_insert_after (cp->pending_messages_head,
1043 cp->pending_messages_tail,
1046 cp->pending_requests++;
1047 if (cp->pending_requests > MAX_QUEUE_PER_PEER)
1048 destroy_pending_message (cp->pending_messages_tail, 0);
1049 if (cp->cth == NULL)
1051 /* need to schedule transmission */
1052 GNUNET_PEER_resolve (cp->pid, &pid);
1053 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1054 cp->pending_messages_head->priority,
1055 GNUNET_TIME_UNIT_FOREVER_REL,
1057 cp->pending_messages_head->msize,
1061 if (cp->cth == NULL)
1063 /* FIXME: call stats (rare, bad case) */
1069 * Mingle hash with the mingle_number to produce different bits.
1072 mingle_hash (const GNUNET_HashCode * in,
1073 int32_t mingle_number,
1074 GNUNET_HashCode * hc)
1078 GNUNET_CRYPTO_hash (&mingle_number,
1081 GNUNET_CRYPTO_hash_xor (&m, in, hc);
1086 * Test if the load on this peer is too high
1087 * to even consider processing the query at
1090 * @return GNUNET_YES if the load is too high, GNUNET_NO otherwise
1093 test_load_too_high ()
1095 return GNUNET_NO; // FIXME
1099 /* ******************* Pending Request Refresh Task ******************** */
1103 * Function called after we either failed or succeeded
1104 * at transmitting a query to a peer.
1106 * @param cls the requests "struct PendingRequest*"
1107 * @param pid ID of receiving peer, 0 on transmission error
1110 transmit_query_continuation (void *cls,
1111 GNUNET_PEER_Id tpid)
1113 struct PendingRequest *pr = cls;
1117 GNUNET_PEER_change_rc (tpid, 1);
1118 if (pr->used_pids_off == pr->used_pids_size)
1119 GNUNET_array_grow (pr->used_pids,
1121 pr->used_pids_size * 2 + 2);
1122 pr->used_pids[pr->used_pids_off++] = tpid;
1127 * How many bytes should a bloomfilter be if we have already seen
1128 * entry_count responses? Note that BLOOMFILTER_K gives us the number
1129 * of bits set per entry. Furthermore, we should not re-size the
1130 * filter too often (to keep it cheap).
1132 * Since other peers will also add entries but not resize the filter,
1133 * we should generally pick a slightly larger size than what the
1134 * strict math would suggest.
1136 * @return must be a power of two and smaller or equal to 2^15.
1139 compute_bloomfilter_size (unsigned int entry_count)
1142 unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
1143 uint16_t max = 1 << 15;
1145 if (entry_count > max)
1148 while ((size < max) && (size < ideal))
1157 * Recalculate our bloom filter for filtering replies.
1159 * @param count number of entries we are filtering right now
1160 * @param mingle set to our new mingling value
1161 * @param bf_size set to the size of the bloomfilter
1162 * @param entries the entries to filter
1163 * @return updated bloomfilter, NULL for none
1165 static struct GNUNET_CONTAINER_BloomFilter *
1166 refresh_bloomfilter (unsigned int count,
1169 const GNUNET_HashCode *entries)
1171 struct GNUNET_CONTAINER_BloomFilter *bf;
1174 GNUNET_HashCode mhash;
1178 nsize = compute_bloomfilter_size (count);
1179 *mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
1181 bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1184 for (i=0;i<count;i++)
1186 mingle_hash (&entries[i], *mingle, &mhash);
1187 GNUNET_CONTAINER_bloomfilter_add (bf, &mhash);
1194 * We use a random delay to make the timing of requests less
1195 * predictable. This function returns such a random delay.
1197 * FIXME: make schedule dependent on the specifics of the request?
1198 * Or bandwidth and number of connected peers and load?
1200 * @return random delay to use for some request, between 0 and TTL_DECREMENT ms
1202 static struct GNUNET_TIME_Relative
1203 get_processing_delay ()
1205 return GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1206 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1212 * Function called after we've tried to reserve a certain amount of
1213 * bandwidth for a reply. Check if we succeeded and if so send our
1216 * @param cls the requests "struct PendingRequest*"
1217 * @param peer identifies the peer
1218 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1219 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1220 * @param amount set to the amount that was actually reserved or unreserved
1221 * @param preference current traffic preference for the given peer
1224 target_reservation_cb (void *cls,
1226 GNUNET_PeerIdentity * peer,
1227 unsigned int bpm_in,
1228 unsigned int bpm_out,
1230 uint64_t preference)
1232 struct PendingRequest *pr = cls;
1233 struct ConnectedPeer *cp;
1234 struct PendingMessage *pm;
1235 struct GetMessage *gm;
1236 GNUNET_HashCode *ext;
1244 GNUNET_assert (peer != NULL);
1245 // (3) transmit, update ttl/priority
1246 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1250 /* Peer must have just left */
1253 no_route = GNUNET_NO;
1254 if (amount != DBLOCK_SIZE)
1256 if (pr->pht_entry == NULL)
1257 return; /* this target round failed */
1258 /* FIXME: if we are "quite" busy, we may still want to skip
1259 this round; need more load detection code! */
1260 no_route = GNUNET_YES;
1263 /* build message and insert message into priority queue */
1266 if (GNUNET_YES == no_route)
1268 bm |= GET_MESSAGE_BIT_RETURN_TO;
1271 if (pr->namespace != NULL)
1273 bm |= GET_MESSAGE_BIT_SKS_NAMESPACE;
1276 if (pr->target_pid != 0)
1278 bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
1281 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
1282 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1283 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1285 gm = (struct GetMessage*) &pm[1];
1286 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
1287 gm->header.size = htons (msize);
1288 gm->type = htonl (pr->type);
1289 pr->remaining_priority /= 2;
1290 gm->priority = htonl (pr->remaining_priority);
1291 gm->ttl = htonl (pr->ttl);
1292 gm->filter_mutator = htonl(pr->mingle);
1293 gm->hash_bitmap = htonl (bm);
1294 gm->query = pr->query;
1295 ext = (GNUNET_HashCode*) &gm[1];
1297 if (GNUNET_YES == no_route)
1298 GNUNET_PEER_resolve (pr->pht_entry->cp->pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1299 if (pr->namespace != NULL)
1300 memcpy (&ext[k++], pr->namespace, sizeof (GNUNET_HashCode));
1301 if (pr->target_pid != 0)
1302 GNUNET_PEER_resolve (pr->target_pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1303 bfdata = (char *) &ext[k];
1305 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
1308 pm->cont = &transmit_query_continuation;
1310 add_to_pending_messages_for_peer (cp, pm, pr);
1315 * Closure used for "target_peer_select_cb".
1317 struct PeerSelectionContext
1320 * The request for which we are selecting
1323 struct PendingRequest *pr;
1326 * Current "prime" target.
1328 struct GNUNET_PeerIdentity target;
1331 * How much do we like this target?
1333 double target_score;
1339 * Function called for each connected peer to determine
1340 * which one(s) would make good targets for forwarding.
1342 * @param cls closure (struct PeerSelectionContext)
1343 * @param key current key code (peer identity)
1344 * @param value value in the hash map (struct ConnectedPeer)
1345 * @return GNUNET_YES if we should continue to
1350 target_peer_select_cb (void *cls,
1351 const GNUNET_HashCode * key,
1354 struct PeerSelectionContext *psc = cls;
1355 struct ConnectedPeer *cp = value;
1356 struct PendingRequest *pr = psc->pr;
1360 /* 1) check if we have already (recently) forwarded to this peer */
1361 for (i=0;i<pr->used_pids_off;i++)
1362 if (pr->used_pids[i] == cp->pid)
1363 return GNUNET_YES; /* skip */
1364 // 2) calculate how much we'd like to forward to this peer
1365 score = 42; // FIXME!
1366 // FIXME: also need API to gather data on responsiveness
1367 // of this peer (we have fields for that in 'cp', but
1368 // they are never set!)
1370 /* store best-fit in closure */
1371 if (score > psc->target_score)
1373 psc->target_score = score;
1374 psc->target.hashPubKey = *key;
1381 * We're processing a GET request from another peer and have decided
1382 * to forward it to other peers. This function is called periodically
1383 * and should forward the request to other peers until we have all
1384 * possible replies. If we have transmitted the *only* reply to
1385 * the initiator we should destroy the pending request. If we have
1386 * many replies in the queue to the initiator, we should delay sending
1387 * out more queries until the reply queue has shrunk some.
1389 * @param cls our "struct ProcessGetContext *"
1393 forward_request_task (void *cls,
1394 const struct GNUNET_SCHEDULER_TaskContext *tc)
1396 struct PendingRequest *pr = cls;
1397 struct PeerSelectionContext psc;
1398 struct ConnectedPeer *cp;
1400 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1401 get_processing_delay (),
1402 &forward_request_task,
1404 if (pr->irc != NULL)
1405 return; /* previous request still pending */
1406 /* (1) select target */
1408 psc.target_score = DBL_MIN;
1409 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1410 &target_peer_select_cb,
1412 if (psc.target_score == DBL_MIN)
1413 return; /* nobody selected */
1415 /* (2) reserve reply bandwidth */
1416 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1417 &psc.target.hashPubKey);
1418 pr->irc = GNUNET_CORE_peer_change_preference (sched, cfg,
1420 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1421 (uint32_t) -1 /* no limit */,
1423 (uint64_t) cp->inc_preference,
1424 &target_reservation_cb,
1426 cp->inc_preference = 0.0;
1430 /* **************************** P2P PUT Handling ************************ */
1434 * Function called after we either failed or succeeded
1435 * at transmitting a reply to a peer.
1437 * @param cls the requests "struct PendingRequest*"
1438 * @param pid ID of receiving peer, 0 on transmission error
1441 transmit_reply_continuation (void *cls,
1442 GNUNET_PEER_Id tpid)
1444 struct PendingRequest *pr = cls;
1448 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1449 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1450 /* only one reply expected, done with the request! */
1451 destroy_pending_request (pr);
1453 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1454 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1464 * Check if the given KBlock is well-formed.
1466 * @param kb the kblock data (or at least "dsize" bytes claiming to be one)
1467 * @param dsize size of "kb" in bytes; check for < sizeof(struct KBlock)!
1468 * @param query where to store the query that this block answers
1469 * @return GNUNET_OK if this is actually a well-formed KBlock
1472 check_kblock (const struct KBlock *kb,
1474 GNUNET_HashCode *query)
1476 if (dsize < sizeof (struct KBlock))
1478 GNUNET_break_op (0);
1479 return GNUNET_SYSERR;
1481 if (dsize - sizeof (struct KBlock) !=
1482 ntohs (kb->purpose.size)
1483 - sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose)
1484 - sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) )
1486 GNUNET_break_op (0);
1487 return GNUNET_SYSERR;
1490 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_KBLOCK,
1495 GNUNET_break_op (0);
1496 return GNUNET_SYSERR;
1499 GNUNET_CRYPTO_hash (&kb->keyspace,
1500 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1507 * Check if the given SBlock is well-formed.
1509 * @param sb the sblock data (or at least "dsize" bytes claiming to be one)
1510 * @param dsize size of "kb" in bytes; check for < sizeof(struct SBlock)!
1511 * @param query where to store the query that this block answers
1512 * @param namespace where to store the namespace that this block belongs to
1513 * @return GNUNET_OK if this is actually a well-formed SBlock
1516 check_sblock (const struct SBlock *sb,
1518 GNUNET_HashCode *query,
1519 GNUNET_HashCode *namespace)
1521 if (dsize < sizeof (struct SBlock))
1523 GNUNET_break_op (0);
1524 return GNUNET_SYSERR;
1527 ntohs (sb->purpose.size) + sizeof (struct GNUNET_CRYPTO_RsaSignature))
1529 GNUNET_break_op (0);
1530 return GNUNET_SYSERR;
1533 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_SBLOCK,
1538 GNUNET_break_op (0);
1539 return GNUNET_SYSERR;
1542 *query = sb->identifier;
1543 if (namespace != NULL)
1544 GNUNET_CRYPTO_hash (&sb->subspace,
1545 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1552 * Transmit the given message by copying it to the target buffer
1553 * "buf". "buf" will be NULL and "size" zero if the socket was closed
1554 * for writing in the meantime. In that case, do nothing
1555 * (the disconnect or shutdown handler will take care of the rest).
1556 * If we were able to transmit messages and there are still more
1557 * pending, ask core again for further calls to this function.
1559 * @param cls closure, pointer to the 'struct ClientList*'
1560 * @param size number of bytes available in buf
1561 * @param buf where the callee should write the message
1562 * @return number of bytes written to buf
1565 transmit_to_client (void *cls,
1566 size_t size, void *buf)
1568 struct ClientList *cl = cls;
1570 struct ClientResponseMessage *creply;
1577 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1578 "Not sending reply, client communication problem.\n");
1583 while ( (NULL != (creply = cl->res_head) ) &&
1584 (creply->msize <= size) )
1586 memcpy (&cbuf[msize], &creply[1], creply->msize);
1587 msize += creply->msize;
1588 size -= creply->msize;
1589 GNUNET_CONTAINER_DLL_remove (cl->res_head,
1592 GNUNET_free (creply);
1595 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
1597 GNUNET_TIME_UNIT_FOREVER_REL,
1598 &transmit_to_client,
1601 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1602 "Transmitted %u bytes to client\n",
1603 (unsigned int) msize);
1610 * Closure for "process_reply" function.
1612 struct ProcessReplyClosure
1615 * The data for the reply.
1619 // FIXME: add 'struct ConnectedPeer' to track 'last_xxx_replies' here!
1622 * When the reply expires.
1624 struct GNUNET_TIME_Absolute expiration;
1632 * Namespace that this reply belongs to
1633 * (if it is of type SBLOCK).
1635 GNUNET_HashCode namespace;
1638 * Type of the block.
1643 * How much was this reply worth to us?
1650 * We have received a reply; handle it!
1652 * @param cls response (struct ProcessReplyClosure)
1653 * @param key our query
1654 * @param value value in the hash map (info about the query)
1655 * @return GNUNET_YES (we should continue to iterate)
1658 process_reply (void *cls,
1659 const GNUNET_HashCode * key,
1662 struct ProcessReplyClosure *prq = cls;
1663 struct PendingRequest *pr = value;
1664 struct PendingMessage *reply;
1665 struct ClientResponseMessage *creply;
1666 struct ClientList *cl;
1667 struct PutMessage *pm;
1668 struct ConnectedPeer *cp;
1669 GNUNET_HashCode chash;
1670 GNUNET_HashCode mhash;
1675 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1676 "Matched result for query `%s' with pending request\n",
1679 GNUNET_CRYPTO_hash (prq->data,
1684 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1685 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1686 /* only possible reply, stop requesting! */
1687 while (NULL != pr->pending_head)
1688 destroy_pending_message_list_entry (pr->pending_head);
1689 GNUNET_break (GNUNET_YES ==
1690 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
1694 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1695 if (0 != memcmp (pr->namespace,
1697 sizeof (GNUNET_HashCode)))
1698 return GNUNET_YES; /* wrong namespace */
1699 /* then: fall-through! */
1700 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1703 mingle_hash (&chash, pr->mingle, &mhash);
1704 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
1706 return GNUNET_YES; /* duplicate */
1707 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
1710 if (pr->client_request_list != NULL)
1712 if (pr->replies_seen_size == pr->replies_seen_off)
1714 GNUNET_array_grow (pr->replies_seen,
1715 pr->replies_seen_size,
1716 pr->replies_seen_size * 2 + 4);
1718 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
1719 pr->bf = refresh_bloomfilter (pr->replies_seen_off,
1724 pr->replies_seen[pr->replies_seen_off++] = chash;
1728 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
1729 // FIXME: any checks against duplicates for SKBlocks?
1735 prio = pr->priority;
1736 prq->priority += pr->remaining_priority;
1737 pr->remaining_priority = 0;
1738 if (pr->client_request_list != NULL)
1741 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1742 "Transmitting result for query `%s' to local client\n",
1745 cl = pr->client_request_list->client_list;
1746 msize = sizeof (struct PutMessage) + prq->size;
1747 creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
1748 creply->msize = msize;
1749 creply->client_list = cl;
1750 GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
1754 pm = (struct PutMessage*) &creply[1];
1755 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
1756 pm->header.size = htons (msize);
1757 pm->type = htonl (prq->type);
1758 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
1759 memcpy (&pm[1], prq->data, prq->size);
1761 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
1763 GNUNET_TIME_UNIT_FOREVER_REL,
1764 &transmit_to_client,
1766 GNUNET_break (cl->th != NULL);
1770 cp = pr->pht_entry->cp;
1772 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1773 "Transmitting result for query `%s' to other peer (PID=%u)\n",
1775 (unsigned int) cp->pid);
1777 msize = sizeof (struct PutMessage) + prq->size;
1778 reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
1779 reply->cont = &transmit_reply_continuation;
1780 reply->cont_cls = pr;
1781 reply->msize = msize;
1782 reply->priority = (uint32_t) -1; /* send replies first! */
1783 pm = (struct PutMessage*) &reply[1];
1784 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
1785 pm->header.size = htons (msize);
1786 pm->type = htonl (prq->type);
1787 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
1788 memcpy (&pm[1], prq->data, prq->size);
1789 add_to_pending_messages_for_peer (cp, reply, pr);
1793 // FIXME: implement hot-path routing statistics keeping!
1799 * Handle P2P "PUT" message.
1801 * @param cls closure, always NULL
1802 * @param other the other peer involved (sender or receiver, NULL
1803 * for loopback messages where we are both sender and receiver)
1804 * @param message the actual message
1805 * @param latency reported latency of the connection with 'other'
1806 * @param distance reported distance (DV) to 'other'
1807 * @return GNUNET_OK to keep the connection open,
1808 * GNUNET_SYSERR to close it (signal serious error)
1811 handle_p2p_put (void *cls,
1812 const struct GNUNET_PeerIdentity *other,
1813 const struct GNUNET_MessageHeader *message,
1814 struct GNUNET_TIME_Relative latency,
1817 const struct PutMessage *put;
1821 struct GNUNET_TIME_Absolute expiration;
1822 GNUNET_HashCode query;
1823 struct ProcessReplyClosure prq;
1825 msize = ntohs (message->size);
1826 if (msize < sizeof (struct PutMessage))
1829 return GNUNET_SYSERR;
1831 put = (const struct PutMessage*) message;
1832 dsize = msize - sizeof (struct PutMessage);
1833 type = ntohl (put->type);
1834 expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
1836 /* first, validate! */
1839 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1840 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1841 GNUNET_CRYPTO_hash (&put[1], dsize, &query);
1843 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1845 check_kblock ((const struct KBlock*) &put[1],
1848 return GNUNET_SYSERR;
1850 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1852 check_sblock ((const struct SBlock*) &put[1],
1856 return GNUNET_SYSERR;
1858 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
1859 // FIXME -- validate SKBLOCK!
1863 /* unknown block type */
1864 GNUNET_break_op (0);
1865 return GNUNET_SYSERR;
1869 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1870 "Received result for query `%s' from peer `%4s'\n",
1871 GNUNET_h2s (&query),
1872 GNUNET_i2s (other));
1874 /* now, lookup 'query' */
1875 prq.data = (const void*) &put[1];
1878 prq.expiration = expiration;
1880 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
1884 // FIXME: if migration is on and load is low,
1885 // queue to store data in datastore;
1886 // use "prq.priority" for that!
1891 /* **************************** P2P GET Handling ************************ */
1895 * We're processing (local) results for a search request
1896 * from another peer. Pass applicable results to the
1897 * peer and if we are done either clean up (operation
1898 * complete) or forward to other peers (more results possible).
1900 * @param cls our closure (struct LocalGetContext)
1901 * @param key key for the content
1902 * @param size number of bytes in data
1903 * @param data content stored
1904 * @param type type of the content
1905 * @param priority priority of the content
1906 * @param anonymity anonymity-level for the content
1907 * @param expiration expiration time for the content
1908 * @param uid unique identifier for the datum;
1909 * maybe 0 if no unique identifier is available
1912 process_local_reply (void *cls,
1913 const GNUNET_HashCode * key,
1919 struct GNUNET_TIME_Absolute
1923 struct PendingRequest *pr = cls;
1924 struct ProcessReplyClosure prq;
1925 GNUNET_HashCode dhash;
1926 GNUNET_HashCode mhash;
1927 GNUNET_HashCode query;
1932 if (pr->client_request_list != NULL)
1933 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
1935 /* no more results */
1936 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1937 pr->task = GNUNET_SCHEDULER_add_now (sched,
1938 &forward_request_task,
1942 if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
1945 GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
1946 anonymity, expiration, uid,
1947 &process_local_reply,
1949 GNUNET_FS_drq_get_next (GNUNET_YES);
1952 /* check for duplicates */
1953 GNUNET_CRYPTO_hash (data, size, &dhash);
1954 mingle_hash (&dhash,
1957 if ( (pr->bf != NULL) &&
1959 GNUNET_CONTAINER_bloomfilter_test (pr->bf,
1963 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1964 "Result from datastore filtered by bloomfilter (duplicate).\n");
1966 GNUNET_FS_drq_get_next (GNUNET_YES);
1970 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1971 "Found result for query `%s' in local datastore\n",
1974 pr->results_found++;
1975 if ( (pr->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
1976 (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
1977 (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) )
1982 pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1986 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
1989 memset (&prq, 0, sizeof (prq));
1991 prq.expiration = expiration;
1993 if ( (type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) &&
1994 (GNUNET_OK != check_sblock ((const struct SBlock*) data,
2000 /* FIXME: consider removing the block? */
2001 GNUNET_FS_drq_get_next (GNUNET_YES);
2005 prq.priority = priority;
2006 process_reply (&prq, key, pr);
2008 if ( (GNUNET_YES == test_load_too_high()) ||
2009 (pr->results_found > 5 + 2 * pr->priority) )
2011 GNUNET_FS_drq_get_next (GNUNET_NO);
2014 GNUNET_FS_drq_get_next (GNUNET_YES);
2019 * The priority level imposes a bound on the maximum
2020 * value for the ttl that can be requested.
2022 * @param ttl_in requested ttl
2023 * @param prio given priority
2024 * @return ttl_in if ttl_in is below the limit,
2025 * otherwise the ttl-limit for the given priority
2028 bound_ttl (int32_t ttl_in, uint32_t prio)
2030 unsigned long long allowed;
2034 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
2035 if (ttl_in > allowed)
2037 if (allowed >= (1 << 30))
2046 * We've received a request with the specified priority. Bound it
2047 * according to how much we trust the given peer.
2049 * @param prio_in requested priority
2050 * @param cp the peer making the request
2051 * @return effective priority
2054 bound_priority (uint32_t prio_in,
2055 struct ConnectedPeer *cp)
2062 * Closure for 'check_duplicate_request'.
2064 struct CheckDuplicateRequestClosure
2067 * The new request we should check if it already exists.
2069 const struct PendingRequest *pr;
2072 * Existing request found by the checker, NULL if none.
2074 struct PendingRequest *have;
2079 * Iterator over entries in the 'query_request_map' that
2080 * tries to see if we have the same request pending from
2081 * the same peer already.
2083 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
2084 * @param key current key code (query, ignored, must match)
2085 * @param value value in the hash map (a 'struct PendingRequest'
2086 * that already exists)
2087 * @return GNUNET_YES if we should continue to
2088 * iterate (no match yet)
2089 * GNUNET_NO if not (match found).
2092 check_duplicate_request (void *cls,
2093 const GNUNET_HashCode * key,
2096 struct CheckDuplicateRequestClosure *cdc = cls;
2097 struct PendingRequest *have = value;
2099 if (cdc->pr->target_pid == have->target_pid)
2109 * Handle P2P "GET" request.
2111 * @param cls closure, always NULL
2112 * @param other the other peer involved (sender or receiver, NULL
2113 * for loopback messages where we are both sender and receiver)
2114 * @param message the actual message
2115 * @param latency reported latency of the connection with 'other'
2116 * @param distance reported distance (DV) to 'other'
2117 * @return GNUNET_OK to keep the connection open,
2118 * GNUNET_SYSERR to close it (signal serious error)
2121 handle_p2p_get (void *cls,
2122 const struct GNUNET_PeerIdentity *other,
2123 const struct GNUNET_MessageHeader *message,
2124 struct GNUNET_TIME_Relative latency,
2127 struct PendingRequest *pr;
2128 struct PeerRequestEntry *pre;
2129 struct ConnectedPeer *cp;
2130 struct ConnectedPeer *cps;
2131 struct CheckDuplicateRequestClosure cdc;
2132 struct GNUNET_TIME_Relative timeout;
2134 const struct GetMessage *gm;
2136 const GNUNET_HashCode *opt;
2139 uint32_t ttl_decrement;
2143 msize = ntohs(message->size);
2144 if (msize < sizeof (struct GetMessage))
2146 GNUNET_break_op (0);
2147 return GNUNET_SYSERR;
2149 gm = (const struct GetMessage*) message;
2150 bm = ntohl (gm->hash_bitmap);
2158 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
2160 GNUNET_break_op (0);
2161 return GNUNET_SYSERR;
2163 opt = (const GNUNET_HashCode*) &gm[1];
2164 bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
2165 bm = ntohl (gm->hash_bitmap);
2166 if ( (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)) &&
2167 (ntohl (gm->type) == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) )
2169 GNUNET_break_op (0);
2170 return GNUNET_SYSERR;
2173 cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2174 &other->hashPubKey);
2175 GNUNET_assert (NULL != cps);
2176 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
2177 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2183 /* FIXME: try connect? */
2186 /* note that we can really only check load here since otherwise
2187 peers could find out that we are overloaded by not being
2188 disconnected after sending us a malformed query... */
2189 if (GNUNET_YES == test_load_too_high ())
2192 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2193 "Dropping query from `%s', this peer is too busy.\n",
2194 GNUNET_i2s (other));
2200 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2201 "Received request for `%s' of type %u from peer `%4s'\n",
2202 GNUNET_h2s (&gm->query),
2203 (unsigned int) ntohl (gm->type),
2204 GNUNET_i2s (other));
2206 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
2207 (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)?sizeof(GNUNET_HashCode):0);
2208 if ((bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2209 pr->namespace = (GNUNET_HashCode*) &pr[1];
2210 pr->type = ntohl (gm->type);
2211 pr->mingle = ntohl (gm->filter_mutator);
2212 if (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2213 memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
2214 else if (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)
2216 GNUNET_break_op (0);
2218 return GNUNET_SYSERR;
2220 if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
2221 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
2223 pr->anonymity_level = 1;
2224 pr->priority = bound_priority (ntohl (gm->priority), cps);
2225 pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
2226 pr->query = gm->query;
2227 /* decrement ttl (always) */
2228 ttl_decrement = 2 * TTL_DECREMENT +
2229 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2231 if ( (pr->ttl < 0) &&
2232 (pr->ttl - ttl_decrement > 0) )
2235 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2236 "Dropping query from `%s' due to TTL underflow.\n",
2237 GNUNET_i2s (other));
2239 /* integer underflow => drop (should be very rare)! */
2243 pr->ttl -= ttl_decrement;
2244 pr->start_time = GNUNET_TIME_absolute_get ();
2246 /* get bloom filter */
2249 pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
2252 pr->bf_size = bfsize;
2257 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2259 &check_duplicate_request,
2261 if (cdc.have != NULL)
2263 if (cdc.have->start_time.value + cdc.have->ttl >=
2264 pr->start_time.value + pr->ttl)
2266 /* existing request has higher TTL, drop new one! */
2267 cdc.have->priority += pr->priority;
2268 destroy_pending_request (pr);
2273 /* existing request has lower TTL, drop old one! */
2274 pr->priority += cdc.have->priority;
2275 /* Possible optimization: if we have applicable pending
2276 replies in 'cdc.have', we might want to move those over
2277 (this is a really rare special-case, so it is not clear
2278 that this would be worth it) */
2279 destroy_pending_request (cdc.have);
2280 /* keep processing 'pr'! */
2284 pre = GNUNET_malloc (sizeof (struct PeerRequestEntry));
2287 GNUNET_CONTAINER_multihashmap_put (query_request_map,
2290 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2292 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
2294 pr->start_time.value + pr->ttl);
2297 /* calculate change in traffic preference */
2298 preference = (double) pr->priority;
2299 if (preference < QUERY_BANDWIDTH_VALUE)
2300 preference = QUERY_BANDWIDTH_VALUE;
2301 cps->inc_preference += preference;
2303 /* process locally */
2305 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2306 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2307 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
2308 (pr->priority + 1));
2309 pr->drq = GNUNET_FS_drq_get (&gm->query,
2311 &process_local_reply,
2316 /* Are multiple results possible? If so, start processing remotely now! */
2319 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2320 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2321 /* only one result, wait for datastore */
2324 pr->task = GNUNET_SCHEDULER_add_now (sched,
2325 &forward_request_task,
2329 /* make sure we don't track too many requests */
2330 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
2332 pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
2333 destroy_pending_request (pr);
2339 /* **************************** CS GET Handling ************************ */
2343 * Handle START_SEARCH-message (search request from client).
2345 * @param cls closure
2346 * @param client identification of the client
2347 * @param message the actual message
2350 handle_start_search (void *cls,
2351 struct GNUNET_SERVER_Client *client,
2352 const struct GNUNET_MessageHeader *message)
2354 static GNUNET_HashCode all_zeros;
2355 const struct SearchMessage *sm;
2356 struct ClientList *cl;
2357 struct ClientRequestList *crl;
2358 struct PendingRequest *pr;
2363 msize = ntohs (message->size);
2364 if ( (msize < sizeof (struct SearchMessage)) ||
2365 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
2368 GNUNET_SERVER_receive_done (client,
2372 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
2373 sm = (const struct SearchMessage*) message;
2376 while ( (cl != NULL) &&
2377 (cl->client != client) )
2381 cl = GNUNET_malloc (sizeof (struct ClientList));
2382 cl->client = client;
2383 GNUNET_SERVER_client_keep (client);
2384 cl->next = client_list;
2387 type = ntohl (sm->type);
2389 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2390 "Received request for `%s' of type %u from local client\n",
2391 GNUNET_h2s (&sm->query),
2392 (unsigned int) type);
2395 /* detect duplicate KBLOCK requests */
2396 if (type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK)
2399 while ( (crl != NULL) &&
2400 ( (0 != memcmp (&crl->req->query,
2402 sizeof (GNUNET_HashCode))) ||
2403 (crl->req->type != type) ) )
2408 /* Duplicate request (used to send long list of
2409 known/blocked results); merge 'pr->replies_seen'
2410 and update bloom filter */
2411 GNUNET_array_grow (pr->replies_seen,
2412 pr->replies_seen_size,
2413 pr->replies_seen_off + sc);
2414 memcpy (&pr->replies_seen[pr->replies_seen_off],
2416 sc * sizeof (GNUNET_HashCode));
2417 pr->replies_seen_off += sc;
2419 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
2420 pr->bf = refresh_bloomfilter (pr->replies_seen_off,
2424 GNUNET_SERVER_receive_done (client,
2429 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
2430 ((type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)?sizeof(GNUNET_HashCode):0));
2431 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
2432 memset (crl, 0, sizeof (struct ClientRequestList));
2433 crl->client_list = cl;
2434 GNUNET_CONTAINER_DLL_insert (cl->rl_head,
2439 pr->client_request_list = crl;
2440 GNUNET_array_grow (pr->replies_seen,
2441 pr->replies_seen_size,
2443 memcpy (pr->replies_seen,
2445 sc * sizeof (GNUNET_HashCode));
2446 pr->replies_seen_off = sc;
2447 pr->anonymity_level = ntohl (sm->anonymity_level);
2448 pr->bf = refresh_bloomfilter (pr->replies_seen_off,
2452 pr->query = sm->query;
2455 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2456 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2457 if (0 != memcmp (&sm->target,
2459 sizeof (GNUNET_HashCode)))
2460 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
2462 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2463 pr->namespace = (GNUNET_HashCode*) &pr[1];
2464 memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
2469 GNUNET_CONTAINER_multihashmap_put (query_request_map,
2472 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2473 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2474 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* get on-demand blocks too! */
2475 pr->drq = GNUNET_FS_drq_get (&sm->query,
2477 &process_local_reply,
2479 GNUNET_TIME_UNIT_FOREVER_REL,
2484 /* **************************** Startup ************************ */
2488 * List of handlers for P2P messages
2489 * that we care about.
2491 static struct GNUNET_CORE_MessageHandler p2p_handlers[] =
2494 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
2496 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
2502 * List of handlers for the messages understood by this
2505 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2506 {&GNUNET_FS_handle_index_start, NULL,
2507 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
2508 {&GNUNET_FS_handle_index_list_get, NULL,
2509 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
2510 {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
2511 sizeof (struct UnindexMessage) },
2512 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
2519 * Process fs requests.
2521 * @param cls closure
2522 * @param s scheduler to use
2523 * @param server the initialized server
2524 * @param c configuration to use
2527 main_init (struct GNUNET_SCHEDULER_Handle *s,
2528 struct GNUNET_SERVER_Handle *server,
2529 const struct GNUNET_CONFIGURATION_Handle *c)
2533 connected_peers = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2534 query_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2535 peer_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2536 requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2537 core = GNUNET_CORE_connect (sched,
2539 GNUNET_TIME_UNIT_FOREVER_REL,
2543 &peer_connect_handler,
2544 &peer_disconnect_handler,
2550 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2551 _("Failed to connect to `%s' service.\n"),
2553 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
2554 connected_peers = NULL;
2555 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
2556 query_request_map = NULL;
2557 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
2558 requests_by_expiration_heap = NULL;
2559 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
2560 peer_request_map = NULL;
2562 return GNUNET_SYSERR;
2564 GNUNET_SERVER_disconnect_notify (server,
2565 &handle_client_disconnect,
2567 GNUNET_SERVER_add_handlers (server, handlers);
2568 GNUNET_SCHEDULER_add_delayed (sched,
2569 GNUNET_TIME_UNIT_FOREVER_REL,
2577 * Process fs requests.
2579 * @param cls closure
2580 * @param sched scheduler to use
2581 * @param server the initialized server
2582 * @param cfg configuration to use
2586 struct GNUNET_SCHEDULER_Handle *sched,
2587 struct GNUNET_SERVER_Handle *server,
2588 const struct GNUNET_CONFIGURATION_Handle *cfg)
2590 if ( (GNUNET_OK != GNUNET_FS_drq_init (sched, cfg)) ||
2591 (GNUNET_OK != GNUNET_FS_indexing_init (sched, cfg)) ||
2592 (GNUNET_OK != main_init (sched, server, cfg)) )
2594 GNUNET_SCHEDULER_shutdown (sched);
2601 * The main function for the fs service.
2603 * @param argc number of arguments from the command line
2604 * @param argv command line arguments
2605 * @return 0 ok, 1 on error
2608 main (int argc, char *const *argv)
2610 return (GNUNET_OK ==
2611 GNUNET_SERVICE_run (argc,
2614 GNUNET_SERVICE_OPTION_NONE,
2615 &run, NULL)) ? 0 : 1;
2618 /* end of gnunet-service-fs.c */