2 This file is part of GNUnet.
3 (C) 2009, 2010 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 2, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file fs/gnunet-service-fs.c
23 * @brief gnunet anonymity protocol implementation
24 * @author Christian Grothoff
27 * - track stats for hot-path routing
28 * - implement hot-path routing decision procedure
29 * - implement: bound_priority, test_load_too_high, validate_skblock
30 * - add content migration support (store locally)
35 #include "gnunet_constants.h"
36 #include "gnunet_core_service.h"
37 #include "gnunet_datastore_service.h"
38 #include "gnunet_peer_lib.h"
39 #include "gnunet_protocols.h"
40 #include "gnunet_signatures.h"
41 #include "gnunet_util_lib.h"
42 #include "gnunet-service-fs_drq.h"
43 #include "gnunet-service-fs_indexing.h"
46 #define DEBUG_FS GNUNET_YES
49 * Maximum number of outgoing messages we queue per peer.
50 * FIXME: set to a tiny value for testing; make configurable.
52 #define MAX_QUEUE_PER_PEER 2
56 * Maximum number of requests (from other peers) that we're
57 * willing to have pending at any given point in time.
58 * FIXME: set from configuration (and 32 is a tiny value for testing only).
60 static uint64_t max_pending_requests = 32;
64 * Information we keep for each pending reply. The
65 * actual message follows at the end of this struct.
67 struct PendingMessage;
71 * Function called upon completion of a transmission.
74 * @param pid ID of receiving peer, 0 on transmission error
76 typedef void (*TransmissionContinuation)(void * cls,
81 * Information we keep for each pending reply. The
82 * actual message follows at the end of this struct.
87 * This is a doubly-linked list of messages to the same peer.
89 struct PendingMessage *next;
92 * This is a doubly-linked list of messages to the same peer.
94 struct PendingMessage *prev;
97 * Entry in pending message list for this pending message.
99 struct PendingMessageList *pml;
102 * Function to call immediately once we have transmitted this
105 TransmissionContinuation cont;
113 * Size of the reply; actual reply message follows
114 * at the end of this struct.
119 * How important is this message for us?
127 * Information about a peer that we are connected to.
128 * We track data that is useful for determining which
129 * peers should receive our requests. We also keep
130 * a list of messages to transmit to this peer.
136 * List of the last clients for which this peer successfully
139 struct GNUNET_SERVER_Client *last_client_replies[CS2P_SUCCESS_LIST_SIZE];
142 * List of the last PIDs for which
143 * this peer successfully answered a query;
144 * We use 0 to indicate no successful reply.
146 GNUNET_PEER_Id last_p2p_replies[P2P_SUCCESS_LIST_SIZE];
149 * Average delay between sending the peer a request and
150 * getting a reply (only calculated over the requests for
151 * which we actually got a reply). Calculated
152 * as a moving average: new_delay = ((n-1)*last_delay+curr_delay) / n
154 struct GNUNET_TIME_Relative avg_delay;
157 * Handle for an active request for transmission to this
160 struct GNUNET_CORE_TransmitHandle *cth;
163 * Messages (replies, queries, content migration) we would like to
164 * send to this peer in the near future. Sorted by priority, head.
166 struct PendingMessage *pending_messages_head;
169 * Messages (replies, queries, content migration) we would like to
170 * send to this peer in the near future. Sorted by priority, tail.
172 struct PendingMessage *pending_messages_tail;
175 * Average priority of successful replies. Calculated
176 * as a moving average: new_avg = ((n-1)*last_avg+curr_prio) / n
181 * Increase in traffic preference still to be submitted
182 * to the core service for this peer. FIXME: double or 'uint64_t'?
184 double inc_preference;
187 * The peer's identity.
192 * Size of the linked list of 'pending_messages'.
194 unsigned int pending_requests;
197 * Which offset in "last_p2p_replies" will be updated next?
198 * (we go round-robin).
200 unsigned int last_p2p_replies_woff;
203 * Which offset in "last_client_replies" will be updated next?
204 * (we go round-robin).
206 unsigned int last_client_replies_woff;
212 * Information we keep for each pending request. We should try to
213 * keep this struct as small as possible since its memory consumption
214 * is key to how many requests we can have pending at once.
216 struct PendingRequest;
220 * Doubly-linked list of requests we are performing
221 * on behalf of the same client.
223 struct ClientRequestList
227 * This is a doubly-linked list.
229 struct ClientRequestList *next;
232 * This is a doubly-linked list.
234 struct ClientRequestList *prev;
237 * Request this entry represents.
239 struct PendingRequest *req;
242 * Client list this request belongs to.
244 struct ClientList *client_list;
250 * Replies to be transmitted to the client. The actual
251 * response message is allocated after this struct.
253 struct ClientResponseMessage
256 * This is a doubly-linked list.
258 struct ClientResponseMessage *next;
261 * This is a doubly-linked list.
263 struct ClientResponseMessage *prev;
266 * Client list entry this response belongs to.
268 struct ClientList *client_list;
271 * Number of bytes in the response.
278 * Linked list of clients we are performing requests
284 * This is a linked list.
286 struct ClientList *next;
289 * ID of a client making a request, NULL if this entry is for a
292 struct GNUNET_SERVER_Client *client;
295 * Head of list of requests performed on behalf
296 * of this client right now.
298 struct ClientRequestList *rl_head;
301 * Tail of list of requests performed on behalf
302 * of this client right now.
304 struct ClientRequestList *rl_tail;
307 * Head of linked list of responses.
309 struct ClientResponseMessage *res_head;
312 * Tail of linked list of responses.
314 struct ClientResponseMessage *res_tail;
317 * Context for sending replies.
319 struct GNUNET_CONNECTION_TransmitHandle *th;
325 * Doubly-linked list of messages we are performing
326 * due to a pending request.
328 struct PendingMessageList
332 * This is a doubly-linked list of messages on behalf of the same request.
334 struct PendingMessageList *next;
337 * This is a doubly-linked list of messages on behalf of the same request.
339 struct PendingMessageList *prev;
342 * Message this entry represents.
344 struct PendingMessage *pm;
347 * Request this entry belongs to.
349 struct PendingRequest *req;
352 * Peer this message is targeted for.
354 struct ConnectedPeer *target;
360 * Information we keep for each pending request. We should try to
361 * keep this struct as small as possible since its memory consumption
362 * is key to how many requests we can have pending at once.
364 struct PendingRequest
368 * If this request was made by a client, this is our entry in the
369 * client request list; otherwise NULL.
371 struct ClientRequestList *client_request_list;
374 * Entry of peer responsible for this entry (if this request
375 * was made by a peer).
377 struct ConnectedPeer *cp;
380 * If this is a namespace query, pointer to the hash of the public
381 * key of the namespace; otherwise NULL. Pointer will be to the
382 * end of this struct (so no need to free it).
384 const GNUNET_HashCode *namespace;
387 * Bloomfilter we use to filter out replies that we don't care about
388 * (anymore). NULL as long as we are interested in all replies.
390 struct GNUNET_CONTAINER_BloomFilter *bf;
393 * Context of our GNUNET_CORE_peer_change_preference call.
395 struct GNUNET_CORE_InformationRequestContext *irc;
398 * Hash code of all replies that we have seen so far (only valid
399 * if client is not NULL since we only track replies like this for
402 GNUNET_HashCode *replies_seen;
405 * Node in the heap representing this entry; NULL
406 * if we have no heap node.
408 struct GNUNET_CONTAINER_HeapNode *hnode;
411 * Head of list of messages being performed on behalf of this
414 struct PendingMessageList *pending_head;
417 * Tail of list of messages being performed on behalf of this
420 struct PendingMessageList *pending_tail;
423 * When did we first see this request (form this peer), or, if our
424 * client is initiating, when did we last initiate a search?
426 struct GNUNET_TIME_Absolute start_time;
429 * The query that this request is for.
431 GNUNET_HashCode query;
434 * The task responsible for transmitting queries
437 GNUNET_SCHEDULER_TaskIdentifier task;
440 * (Interned) Peer identifier that identifies a preferred target
443 GNUNET_PEER_Id target_pid;
446 * (Interned) Peer identifiers of peers that have already
447 * received our query for this content.
449 GNUNET_PEER_Id *used_pids;
452 * Our entry in the DRQ (non-NULL while we wait for our
453 * turn to interact with the local database).
455 struct DatastoreRequestQueue *drq;
458 * Size of the 'bf' (in bytes).
463 * Desired anonymity level; only valid for requests from a local client.
465 uint32_t anonymity_level;
468 * How many entries in "used_pids" are actually valid?
470 unsigned int used_pids_off;
473 * How long is the "used_pids" array?
475 unsigned int used_pids_size;
478 * Number of results found for this request.
480 unsigned int results_found;
483 * How many entries in "replies_seen" are actually valid?
485 unsigned int replies_seen_off;
488 * How long is the "replies_seen" array?
490 unsigned int replies_seen_size;
493 * Priority with which this request was made. If one of our clients
494 * made the request, then this is the current priority that we are
495 * using when initiating the request. This value is used when
496 * we decide to reward other peers with trust for providing a reply.
501 * Priority points left for us to spend when forwarding this request
504 uint32_t remaining_priority;
507 * Number to mingle hashes for bloom-filter tests with.
512 * TTL with which we saw this request (or, if we initiated, TTL that
513 * we used for the request).
518 * Type of the content that this request is for.
528 static struct GNUNET_SCHEDULER_Handle *sched;
533 static const struct GNUNET_CONFIGURATION_Handle *cfg;
536 * Map of peer identifiers to "struct ConnectedPeer" (for that peer).
538 static struct GNUNET_CONTAINER_MultiHashMap *connected_peers;
541 * Map of peer identifiers to "struct PendingRequest" (for that peer).
543 static struct GNUNET_CONTAINER_MultiHashMap *peer_request_map;
546 * Map of query identifiers to "struct PendingRequest" (for that query).
548 static struct GNUNET_CONTAINER_MultiHashMap *query_request_map;
551 * Heap with the request that will expire next at the top. Contains
552 * pointers of type "struct PendingRequest*"; these will *also* be
553 * aliased from the "requests_by_peer" data structures and the
554 * "requests_by_query" table. Note that requests from our clients
555 * don't expire and are thus NOT in the "requests_by_expiration"
556 * (or the "requests_by_peer" tables).
558 static struct GNUNET_CONTAINER_Heap *requests_by_expiration_heap;
561 * Linked list of clients we are currently processing requests for.
563 struct ClientList *client_list;
566 * Pointer to handle to the core service (points to NULL until we've
569 struct GNUNET_CORE_Handle *core;
572 /* ******************* clean up functions ************************ */
576 * We're done with a particular message list entry.
577 * Free all associated resources.
579 * @param pml entry to destroy
582 destroy_pending_message_list_entry (struct PendingMessageList *pml)
584 GNUNET_CONTAINER_DLL_remove (pml->req->pending_head,
585 pml->req->pending_tail,
587 GNUNET_CONTAINER_DLL_remove (pml->target->pending_messages_head,
588 pml->target->pending_messages_tail,
590 pml->target->pending_requests--;
591 GNUNET_free (pml->pm);
597 * Destroy the given pending message (and call the respective
600 * @param pm message to destroy
601 * @param tpid id of peer that the message was delivered to, or 0 for none
604 destroy_pending_message (struct PendingMessage *pm,
607 struct PendingMessageList *pml = pm->pml;
609 GNUNET_assert (pml->pm == pm);
610 GNUNET_assert ( (tpid == 0) || (tpid == pml->target->pid) );
611 pm->cont (pm->cont_cls, 0);
612 destroy_pending_message_list_entry (pml);
618 * We're done processing a particular request.
619 * Free all associated resources.
621 * @param pr request to destroy
624 destroy_pending_request (struct PendingRequest *pr)
626 struct GNUNET_PeerIdentity pid;
628 if (pr->hnode != NULL)
630 GNUNET_CONTAINER_heap_remove_node (requests_by_expiration_heap,
634 /* might have already been removed from map in 'process_reply' (if
635 there was a unique reply) or never inserted if it was a
636 duplicate; hence ignore the return value here */
637 (void) GNUNET_CONTAINER_multihashmap_remove (query_request_map,
642 GNUNET_FS_drq_get_cancel (pr->drq);
645 if (pr->client_request_list != NULL)
647 GNUNET_CONTAINER_DLL_remove (pr->client_request_list->client_list->rl_head,
648 pr->client_request_list->client_list->rl_tail,
649 pr->client_request_list);
650 GNUNET_free (pr->client_request_list);
651 pr->client_request_list = NULL;
655 GNUNET_PEER_resolve (pr->cp->pid,
657 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
664 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
669 GNUNET_CORE_peer_change_preference_cancel (pr->irc);
672 if (pr->replies_seen != NULL)
674 GNUNET_free (pr->replies_seen);
675 pr->replies_seen = NULL;
677 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
679 GNUNET_SCHEDULER_cancel (sched,
681 pr->task = GNUNET_SCHEDULER_NO_TASK;
683 while (NULL != pr->pending_head)
684 destroy_pending_message_list_entry (pr->pending_head);
685 GNUNET_PEER_change_rc (pr->target_pid, -1);
686 if (pr->used_pids != NULL)
688 GNUNET_PEER_decrement_rcs (pr->used_pids, pr->used_pids_off);
689 GNUNET_free (pr->used_pids);
690 pr->used_pids_off = 0;
691 pr->used_pids_size = 0;
692 pr->used_pids = NULL;
699 * Method called whenever a given peer connects.
701 * @param cls closure, not used
702 * @param peer peer identity this notification is about
703 * @param latency reported latency of the connection with 'other'
704 * @param distance reported distance (DV) to 'other'
707 peer_connect_handler (void *cls,
709 GNUNET_PeerIdentity * peer,
710 struct GNUNET_TIME_Relative latency,
713 struct ConnectedPeer *cp;
715 cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
716 cp->pid = GNUNET_PEER_intern (peer);
717 GNUNET_CONTAINER_multihashmap_put (connected_peers,
720 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
725 * Free (each) request made by the peer.
727 * @param cls closure, points to peer that the request belongs to
728 * @param key current key code
729 * @param value value in the hash map
730 * @return GNUNET_YES (we should continue to iterate)
733 destroy_request (void *cls,
734 const GNUNET_HashCode * key,
737 const struct GNUNET_PeerIdentity * peer = cls;
738 struct PendingRequest *pr = value;
740 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
743 destroy_pending_request (pr);
749 * Method called whenever a peer disconnects.
751 * @param cls closure, not used
752 * @param peer peer identity this notification is about
755 peer_disconnect_handler (void *cls,
757 GNUNET_PeerIdentity * peer)
759 struct ConnectedPeer *cp;
760 struct PendingMessage *pm;
763 GNUNET_CONTAINER_multihashmap_get_multiple (peer_request_map,
767 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
771 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
773 if (NULL != cp->last_client_replies[i])
775 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
776 cp->last_client_replies[i] = NULL;
779 GNUNET_CONTAINER_multihashmap_remove (connected_peers,
782 GNUNET_PEER_change_rc (cp->pid, -1);
783 GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
785 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
786 while (NULL != (pm = cp->pending_messages_head))
787 destroy_pending_message (pm, 0 /* delivery failed */);
788 GNUNET_break (0 == cp->pending_requests);
794 * Iterator over hash map entries that removes all occurences
795 * of the given 'client' from the 'last_client_replies' of the
796 * given connected peer.
798 * @param cls closure, the 'struct GNUNET_SERVER_Client*' to remove
799 * @param key current key code (unused)
800 * @param value value in the hash map (the 'struct ConnectedPeer*' to change)
801 * @return GNUNET_YES (we should continue to iterate)
804 remove_client_from_last_client_replies (void *cls,
805 const GNUNET_HashCode * key,
808 struct GNUNET_SERVER_Client *client = cls;
809 struct ConnectedPeer *cp = value;
812 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
814 if (cp->last_client_replies[i] == client)
816 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
817 cp->last_client_replies[i] = NULL;
825 * A client disconnected. Remove all of its pending queries.
827 * @param cls closure, NULL
828 * @param client identification of the client
831 handle_client_disconnect (void *cls,
832 struct GNUNET_SERVER_Client
835 struct ClientList *pos;
836 struct ClientList *prev;
837 struct ClientRequestList *rcl;
838 struct ClientResponseMessage *creply;
841 return; /* huh? is this allowed? */
844 while ( (NULL != pos) &&
845 (pos->client != client) )
851 return; /* no requests pending for this client */
852 while (NULL != (rcl = pos->rl_head))
853 destroy_pending_request (rcl->req);
855 client_list = pos->next;
857 prev->next = pos->next;
860 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
863 while (NULL != (creply = pos->res_head))
865 GNUNET_CONTAINER_DLL_remove (pos->res_head,
868 GNUNET_free (creply);
870 GNUNET_SERVER_client_drop (pos->client);
872 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
873 &remove_client_from_last_client_replies,
879 * Iterator to free peer entries.
881 * @param cls closure, unused
882 * @param key current key code
883 * @param value value in the hash map (peer entry)
884 * @return GNUNET_YES (we should continue to iterate)
887 clean_peer (void *cls,
888 const GNUNET_HashCode * key,
891 peer_disconnect_handler (NULL, (const struct GNUNET_PeerIdentity*) key);
897 * Task run during shutdown.
903 shutdown_task (void *cls,
904 const struct GNUNET_SCHEDULER_TaskContext *tc)
906 while (client_list != NULL)
907 handle_client_disconnect (NULL,
908 client_list->client);
909 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
912 GNUNET_break (0 == GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap));
913 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
914 requests_by_expiration_heap = 0;
915 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
916 connected_peers = NULL;
917 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (query_request_map));
918 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
919 query_request_map = NULL;
920 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (peer_request_map));
921 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
922 peer_request_map = NULL;
923 GNUNET_assert (NULL != core);
924 GNUNET_CORE_disconnect (core);
931 /* ******************* Utility functions ******************** */
935 * Transmit the given message by copying it to the target buffer
936 * "buf". "buf" will be NULL and "size" zero if the socket was closed
937 * for writing in the meantime. In that case, do nothing
938 * (the disconnect or shutdown handler will take care of the rest).
939 * If we were able to transmit messages and there are still more
940 * pending, ask core again for further calls to this function.
942 * @param cls closure, pointer to the 'struct ConnectedPeer*'
943 * @param size number of bytes available in buf
944 * @param buf where the callee should write the message
945 * @return number of bytes written to buf
948 transmit_to_peer (void *cls,
949 size_t size, void *buf)
951 struct ConnectedPeer *cp = cls;
953 struct GNUNET_PeerIdentity pid;
954 struct PendingMessage *pm;
961 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
962 "Dropping message, core too busy.\n");
967 while ( (NULL != (pm = cp->pending_messages_head) ) &&
968 (pm->msize <= size) )
970 memcpy (&cbuf[msize], &pm[1], pm->msize);
973 destroy_pending_message (pm, cp->pid);
977 GNUNET_PEER_resolve (cp->pid,
979 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
981 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
988 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
989 "Transmitting %u bytes to peer %u.\n",
998 * Add a message to the set of pending messages for the given peer.
1000 * @param cp peer to send message to
1001 * @param pm message to queue
1002 * @param pr request on which behalf this message is being queued
1005 add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
1006 struct PendingMessage *pm,
1007 struct PendingRequest *pr)
1009 struct PendingMessage *pos;
1010 struct PendingMessageList *pml;
1011 struct GNUNET_PeerIdentity pid;
1013 GNUNET_assert (pm->next == NULL);
1014 GNUNET_assert (pm->pml == NULL);
1015 pml = GNUNET_malloc (sizeof (struct PendingMessageList));
1020 GNUNET_CONTAINER_DLL_insert (pr->pending_head,
1023 pos = cp->pending_messages_head;
1024 while ( (pos != NULL) &&
1025 (pm->priority < pos->priority) )
1027 GNUNET_CONTAINER_DLL_insert_after (cp->pending_messages_head,
1028 cp->pending_messages_tail,
1031 cp->pending_requests++;
1032 if (cp->pending_requests > MAX_QUEUE_PER_PEER)
1033 destroy_pending_message (cp->pending_messages_tail, 0);
1034 if (cp->cth == NULL)
1036 /* need to schedule transmission */
1037 GNUNET_PEER_resolve (cp->pid, &pid);
1038 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1039 cp->pending_messages_head->priority,
1040 GNUNET_TIME_UNIT_FOREVER_REL,
1042 cp->pending_messages_head->msize,
1046 if (cp->cth == NULL)
1049 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1050 "Failed to schedule transmission with core!\n");
1052 /* FIXME: call stats (rare, bad case) */
1058 * Mingle hash with the mingle_number to produce different bits.
1061 mingle_hash (const GNUNET_HashCode * in,
1062 int32_t mingle_number,
1063 GNUNET_HashCode * hc)
1067 GNUNET_CRYPTO_hash (&mingle_number,
1070 GNUNET_CRYPTO_hash_xor (&m, in, hc);
1075 * Test if the load on this peer is too high
1076 * to even consider processing the query at
1079 * @return GNUNET_YES if the load is too high, GNUNET_NO otherwise
1082 test_load_too_high ()
1084 return GNUNET_NO; // FIXME
1088 /* ******************* Pending Request Refresh Task ******************** */
1092 * Function called after we either failed or succeeded
1093 * at transmitting a query to a peer.
1095 * @param cls the requests "struct PendingRequest*"
1096 * @param tpid ID of receiving peer, 0 on transmission error
1099 transmit_query_continuation (void *cls,
1100 GNUNET_PEER_Id tpid)
1102 struct PendingRequest *pr = cls;
1106 GNUNET_PEER_change_rc (tpid, 1);
1107 if (pr->used_pids_off == pr->used_pids_size)
1108 GNUNET_array_grow (pr->used_pids,
1110 pr->used_pids_size * 2 + 2);
1111 pr->used_pids[pr->used_pids_off++] = tpid;
1116 * How many bytes should a bloomfilter be if we have already seen
1117 * entry_count responses? Note that BLOOMFILTER_K gives us the number
1118 * of bits set per entry. Furthermore, we should not re-size the
1119 * filter too often (to keep it cheap).
1121 * Since other peers will also add entries but not resize the filter,
1122 * we should generally pick a slightly larger size than what the
1123 * strict math would suggest.
1125 * @return must be a power of two and smaller or equal to 2^15.
1128 compute_bloomfilter_size (unsigned int entry_count)
1131 unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
1132 uint16_t max = 1 << 15;
1134 if (entry_count > max)
1137 while ((size < max) && (size < ideal))
1146 * Recalculate our bloom filter for filtering replies.
1148 * @param count number of entries we are filtering right now
1149 * @param mingle set to our new mingling value
1150 * @param bf_size set to the size of the bloomfilter
1151 * @param entries the entries to filter
1152 * @return updated bloomfilter, NULL for none
1154 static struct GNUNET_CONTAINER_BloomFilter *
1155 refresh_bloomfilter (unsigned int count,
1158 const GNUNET_HashCode *entries)
1160 struct GNUNET_CONTAINER_BloomFilter *bf;
1163 GNUNET_HashCode mhash;
1167 nsize = compute_bloomfilter_size (count);
1168 *mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
1170 bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1173 for (i=0;i<count;i++)
1175 mingle_hash (&entries[i], *mingle, &mhash);
1176 GNUNET_CONTAINER_bloomfilter_add (bf, &mhash);
1183 * We use a random delay to make the timing of requests less
1184 * predictable. This function returns such a random delay.
1186 * FIXME: make schedule dependent on the specifics of the request?
1187 * Or bandwidth and number of connected peers and load?
1189 * @return random delay to use for some request, between 0 and TTL_DECREMENT ms
1191 static struct GNUNET_TIME_Relative
1192 get_processing_delay ()
1194 return GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1195 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1201 * Function called after we've tried to reserve a certain amount of
1202 * bandwidth for a reply. Check if we succeeded and if so send our
1205 * @param cls the requests "struct PendingRequest*"
1206 * @param peer identifies the peer
1207 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1208 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1209 * @param amount set to the amount that was actually reserved or unreserved
1210 * @param preference current traffic preference for the given peer
1213 target_reservation_cb (void *cls,
1215 GNUNET_PeerIdentity * peer,
1216 unsigned int bpm_in,
1217 unsigned int bpm_out,
1219 uint64_t preference)
1221 struct PendingRequest *pr = cls;
1222 struct ConnectedPeer *cp;
1223 struct PendingMessage *pm;
1224 struct GetMessage *gm;
1225 GNUNET_HashCode *ext;
1233 GNUNET_assert (peer != NULL);
1234 // (3) transmit, update ttl/priority
1235 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1239 /* Peer must have just left */
1241 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1242 "Selected peer disconnected!\n");
1246 no_route = GNUNET_NO;
1247 /* FIXME: check against DBLOCK_SIZE and possibly return
1248 amount to reserve; however, this also needs to work
1249 with testcases which currently start out with a far
1250 too low per-peer bw limit, so they would never send
1251 anything. Big issue. */
1257 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1258 "Failed to reserve bandwidth for reply (got %d/%u bytes only)!\n",
1262 return; /* this target round failed */
1264 /* FIXME: if we are "quite" busy, we may still want to skip
1265 this round; need more load detection code! */
1266 no_route = GNUNET_YES;
1269 /* build message and insert message into priority queue */
1271 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1272 "Forwarding request to `%4s'!\n",
1277 if (GNUNET_YES == no_route)
1279 bm |= GET_MESSAGE_BIT_RETURN_TO;
1282 if (pr->namespace != NULL)
1284 bm |= GET_MESSAGE_BIT_SKS_NAMESPACE;
1287 if (pr->target_pid != 0)
1289 bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
1292 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
1293 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1294 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1296 gm = (struct GetMessage*) &pm[1];
1297 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
1298 gm->header.size = htons (msize);
1299 gm->type = htonl (pr->type);
1300 pr->remaining_priority /= 2;
1301 gm->priority = htonl (pr->remaining_priority);
1302 gm->ttl = htonl (pr->ttl);
1303 gm->filter_mutator = htonl(pr->mingle);
1304 gm->hash_bitmap = htonl (bm);
1305 gm->query = pr->query;
1306 ext = (GNUNET_HashCode*) &gm[1];
1308 if (GNUNET_YES == no_route)
1309 GNUNET_PEER_resolve (pr->cp->pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1310 if (pr->namespace != NULL)
1311 memcpy (&ext[k++], pr->namespace, sizeof (GNUNET_HashCode));
1312 if (pr->target_pid != 0)
1313 GNUNET_PEER_resolve (pr->target_pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1314 bfdata = (char *) &ext[k];
1316 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
1319 pm->cont = &transmit_query_continuation;
1321 add_to_pending_messages_for_peer (cp, pm, pr);
1326 * Closure used for "target_peer_select_cb".
1328 struct PeerSelectionContext
1331 * The request for which we are selecting
1334 struct PendingRequest *pr;
1337 * Current "prime" target.
1339 struct GNUNET_PeerIdentity target;
1342 * How much do we like this target?
1344 double target_score;
1350 * Function called for each connected peer to determine
1351 * which one(s) would make good targets for forwarding.
1353 * @param cls closure (struct PeerSelectionContext)
1354 * @param key current key code (peer identity)
1355 * @param value value in the hash map (struct ConnectedPeer)
1356 * @return GNUNET_YES if we should continue to
1361 target_peer_select_cb (void *cls,
1362 const GNUNET_HashCode * key,
1365 struct PeerSelectionContext *psc = cls;
1366 struct ConnectedPeer *cp = value;
1367 struct PendingRequest *pr = psc->pr;
1371 /* 1) check if we have already (recently) forwarded to this peer */
1372 for (i=0;i<pr->used_pids_off;i++)
1373 if (pr->used_pids[i] == cp->pid)
1374 return GNUNET_YES; /* skip */
1375 // 2) calculate how much we'd like to forward to this peer
1376 score = 42; // FIXME!
1377 // FIXME: also need API to gather data on responsiveness
1378 // of this peer (we have fields for that in 'cp', but
1379 // they are never set!)
1381 /* store best-fit in closure */
1382 if (score > psc->target_score)
1384 psc->target_score = score;
1385 psc->target.hashPubKey = *key;
1392 * We're processing a GET request from another peer and have decided
1393 * to forward it to other peers. This function is called periodically
1394 * and should forward the request to other peers until we have all
1395 * possible replies. If we have transmitted the *only* reply to
1396 * the initiator we should destroy the pending request. If we have
1397 * many replies in the queue to the initiator, we should delay sending
1398 * out more queries until the reply queue has shrunk some.
1400 * @param cls our "struct ProcessGetContext *"
1404 forward_request_task (void *cls,
1405 const struct GNUNET_SCHEDULER_TaskContext *tc)
1407 struct PendingRequest *pr = cls;
1408 struct PeerSelectionContext psc;
1409 struct ConnectedPeer *cp;
1411 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1412 get_processing_delay (),
1413 &forward_request_task,
1415 if (pr->irc != NULL)
1416 return; /* previous request still pending */
1417 /* (1) select target */
1419 psc.target_score = DBL_MIN;
1420 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1421 &target_peer_select_cb,
1423 if (psc.target_score == DBL_MIN)
1426 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1427 "No peer selected for forwarding!\n");
1429 return; /* nobody selected */
1432 /* (2) reserve reply bandwidth */
1433 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1434 &psc.target.hashPubKey);
1435 pr->irc = GNUNET_CORE_peer_change_preference (sched, cfg,
1437 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1438 (uint32_t) -1 /* no limit */,
1440 (uint64_t) cp->inc_preference,
1441 &target_reservation_cb,
1443 cp->inc_preference = 0.0;
1447 /* **************************** P2P PUT Handling ************************ */
1451 * Function called after we either failed or succeeded
1452 * at transmitting a reply to a peer.
1454 * @param cls the requests "struct PendingRequest*"
1455 * @param tpid ID of receiving peer, 0 on transmission error
1458 transmit_reply_continuation (void *cls,
1459 GNUNET_PEER_Id tpid)
1461 struct PendingRequest *pr = cls;
1465 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1466 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1467 /* only one reply expected, done with the request! */
1468 destroy_pending_request (pr);
1470 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1471 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1481 * Check if the given KBlock is well-formed.
1483 * @param kb the kblock data (or at least "dsize" bytes claiming to be one)
1484 * @param dsize size of "kb" in bytes; check for < sizeof(struct KBlock)!
1485 * @param query where to store the query that this block answers
1486 * @return GNUNET_OK if this is actually a well-formed KBlock
1489 check_kblock (const struct KBlock *kb,
1491 GNUNET_HashCode *query)
1493 if (dsize < sizeof (struct KBlock))
1495 GNUNET_break_op (0);
1496 return GNUNET_SYSERR;
1498 if (dsize - sizeof (struct KBlock) !=
1499 ntohs (kb->purpose.size)
1500 - sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose)
1501 - sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) )
1503 GNUNET_break_op (0);
1504 return GNUNET_SYSERR;
1507 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_KBLOCK,
1512 GNUNET_break_op (0);
1513 return GNUNET_SYSERR;
1516 GNUNET_CRYPTO_hash (&kb->keyspace,
1517 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1524 * Check if the given SBlock is well-formed.
1526 * @param sb the sblock data (or at least "dsize" bytes claiming to be one)
1527 * @param dsize size of "kb" in bytes; check for < sizeof(struct SBlock)!
1528 * @param query where to store the query that this block answers
1529 * @param namespace where to store the namespace that this block belongs to
1530 * @return GNUNET_OK if this is actually a well-formed SBlock
1533 check_sblock (const struct SBlock *sb,
1535 GNUNET_HashCode *query,
1536 GNUNET_HashCode *namespace)
1538 if (dsize < sizeof (struct SBlock))
1540 GNUNET_break_op (0);
1541 return GNUNET_SYSERR;
1544 ntohs (sb->purpose.size) + sizeof (struct GNUNET_CRYPTO_RsaSignature))
1546 GNUNET_break_op (0);
1547 return GNUNET_SYSERR;
1550 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_SBLOCK,
1555 GNUNET_break_op (0);
1556 return GNUNET_SYSERR;
1559 *query = sb->identifier;
1560 if (namespace != NULL)
1561 GNUNET_CRYPTO_hash (&sb->subspace,
1562 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1569 * Transmit the given message by copying it to the target buffer
1570 * "buf". "buf" will be NULL and "size" zero if the socket was closed
1571 * for writing in the meantime. In that case, do nothing
1572 * (the disconnect or shutdown handler will take care of the rest).
1573 * If we were able to transmit messages and there are still more
1574 * pending, ask core again for further calls to this function.
1576 * @param cls closure, pointer to the 'struct ClientList*'
1577 * @param size number of bytes available in buf
1578 * @param buf where the callee should write the message
1579 * @return number of bytes written to buf
1582 transmit_to_client (void *cls,
1583 size_t size, void *buf)
1585 struct ClientList *cl = cls;
1587 struct ClientResponseMessage *creply;
1594 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1595 "Not sending reply, client communication problem.\n");
1600 while ( (NULL != (creply = cl->res_head) ) &&
1601 (creply->msize <= size) )
1603 memcpy (&cbuf[msize], &creply[1], creply->msize);
1604 msize += creply->msize;
1605 size -= creply->msize;
1606 GNUNET_CONTAINER_DLL_remove (cl->res_head,
1609 GNUNET_free (creply);
1612 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
1614 GNUNET_TIME_UNIT_FOREVER_REL,
1615 &transmit_to_client,
1618 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1619 "Transmitted %u bytes to client\n",
1620 (unsigned int) msize);
1627 * Closure for "process_reply" function.
1629 struct ProcessReplyClosure
1632 * The data for the reply.
1636 // FIXME: add 'struct ConnectedPeer' to track 'last_xxx_replies' here!
1639 * When the reply expires.
1641 struct GNUNET_TIME_Absolute expiration;
1649 * Namespace that this reply belongs to
1650 * (if it is of type SBLOCK).
1652 GNUNET_HashCode namespace;
1655 * Type of the block.
1660 * How much was this reply worth to us?
1667 * We have received a reply; handle it!
1669 * @param cls response (struct ProcessReplyClosure)
1670 * @param key our query
1671 * @param value value in the hash map (info about the query)
1672 * @return GNUNET_YES (we should continue to iterate)
1675 process_reply (void *cls,
1676 const GNUNET_HashCode * key,
1679 struct ProcessReplyClosure *prq = cls;
1680 struct PendingRequest *pr = value;
1681 struct PendingMessage *reply;
1682 struct ClientResponseMessage *creply;
1683 struct ClientList *cl;
1684 struct PutMessage *pm;
1685 struct ConnectedPeer *cp;
1686 GNUNET_HashCode chash;
1687 GNUNET_HashCode mhash;
1692 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1693 "Matched result for query `%s' with pending request\n",
1696 GNUNET_CRYPTO_hash (prq->data,
1701 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1702 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1703 /* only possible reply, stop requesting! */
1704 while (NULL != pr->pending_head)
1705 destroy_pending_message_list_entry (pr->pending_head);
1706 if (pr->drq != NULL)
1708 GNUNET_FS_drq_get_cancel (pr->drq);
1711 GNUNET_break (GNUNET_YES ==
1712 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
1716 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1717 if (0 != memcmp (pr->namespace,
1719 sizeof (GNUNET_HashCode)))
1720 return GNUNET_YES; /* wrong namespace */
1721 /* then: fall-through! */
1722 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1725 mingle_hash (&chash, pr->mingle, &mhash);
1726 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
1728 return GNUNET_YES; /* duplicate */
1729 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
1732 if (pr->client_request_list != NULL)
1734 if (pr->replies_seen_size == pr->replies_seen_off)
1736 GNUNET_array_grow (pr->replies_seen,
1737 pr->replies_seen_size,
1738 pr->replies_seen_size * 2 + 4);
1740 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
1741 pr->bf = refresh_bloomfilter (pr->replies_seen_off,
1746 pr->replies_seen[pr->replies_seen_off++] = chash;
1750 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
1751 // FIXME: any checks against duplicates for SKBlocks?
1757 prio = pr->priority;
1758 prq->priority += pr->remaining_priority;
1759 pr->remaining_priority = 0;
1760 if (pr->client_request_list != NULL)
1763 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1764 "Transmitting result for query `%s' to local client\n",
1767 cl = pr->client_request_list->client_list;
1768 msize = sizeof (struct PutMessage) + prq->size;
1769 creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
1770 creply->msize = msize;
1771 creply->client_list = cl;
1772 GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
1776 pm = (struct PutMessage*) &creply[1];
1777 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
1778 pm->header.size = htons (msize);
1779 pm->type = htonl (prq->type);
1780 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
1781 memcpy (&pm[1], prq->data, prq->size);
1783 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
1785 GNUNET_TIME_UNIT_FOREVER_REL,
1786 &transmit_to_client,
1788 GNUNET_break (cl->th != NULL);
1794 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1795 "Transmitting result for query `%s' to other peer (PID=%u)\n",
1797 (unsigned int) cp->pid);
1799 msize = sizeof (struct PutMessage) + prq->size;
1800 reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
1801 reply->cont = &transmit_reply_continuation;
1802 reply->cont_cls = pr;
1803 reply->msize = msize;
1804 reply->priority = (uint32_t) -1; /* send replies first! */
1805 pm = (struct PutMessage*) &reply[1];
1806 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
1807 pm->header.size = htons (msize);
1808 pm->type = htonl (prq->type);
1809 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
1810 memcpy (&pm[1], prq->data, prq->size);
1811 add_to_pending_messages_for_peer (cp, reply, pr);
1815 // FIXME: implement hot-path routing statistics keeping!
1821 * Handle P2P "PUT" message.
1823 * @param cls closure, always NULL
1824 * @param other the other peer involved (sender or receiver, NULL
1825 * for loopback messages where we are both sender and receiver)
1826 * @param message the actual message
1827 * @param latency reported latency of the connection with 'other'
1828 * @param distance reported distance (DV) to 'other'
1829 * @return GNUNET_OK to keep the connection open,
1830 * GNUNET_SYSERR to close it (signal serious error)
1833 handle_p2p_put (void *cls,
1834 const struct GNUNET_PeerIdentity *other,
1835 const struct GNUNET_MessageHeader *message,
1836 struct GNUNET_TIME_Relative latency,
1839 const struct PutMessage *put;
1843 struct GNUNET_TIME_Absolute expiration;
1844 GNUNET_HashCode query;
1845 struct ProcessReplyClosure prq;
1847 msize = ntohs (message->size);
1848 if (msize < sizeof (struct PutMessage))
1851 return GNUNET_SYSERR;
1853 put = (const struct PutMessage*) message;
1854 dsize = msize - sizeof (struct PutMessage);
1855 type = ntohl (put->type);
1856 expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
1858 /* first, validate! */
1861 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1862 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1863 GNUNET_CRYPTO_hash (&put[1], dsize, &query);
1865 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1867 check_kblock ((const struct KBlock*) &put[1],
1870 return GNUNET_SYSERR;
1872 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1874 check_sblock ((const struct SBlock*) &put[1],
1878 return GNUNET_SYSERR;
1880 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
1881 // FIXME -- validate SKBLOCK!
1885 /* unknown block type */
1886 GNUNET_break_op (0);
1887 return GNUNET_SYSERR;
1891 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1892 "Received result for query `%s' from peer `%4s'\n",
1893 GNUNET_h2s (&query),
1894 GNUNET_i2s (other));
1896 /* now, lookup 'query' */
1897 prq.data = (const void*) &put[1];
1900 prq.expiration = expiration;
1902 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
1906 // FIXME: if migration is on and load is low,
1907 // queue to store data in datastore;
1908 // use "prq.priority" for that!
1913 /* **************************** P2P GET Handling ************************ */
1917 * We're processing (local) results for a search request
1918 * from another peer. Pass applicable results to the
1919 * peer and if we are done either clean up (operation
1920 * complete) or forward to other peers (more results possible).
1922 * @param cls our closure (struct LocalGetContext)
1923 * @param key key for the content
1924 * @param size number of bytes in data
1925 * @param data content stored
1926 * @param type type of the content
1927 * @param priority priority of the content
1928 * @param anonymity anonymity-level for the content
1929 * @param expiration expiration time for the content
1930 * @param uid unique identifier for the datum;
1931 * maybe 0 if no unique identifier is available
1934 process_local_reply (void *cls,
1935 const GNUNET_HashCode * key,
1941 struct GNUNET_TIME_Absolute
1945 struct PendingRequest *pr = cls;
1946 struct ProcessReplyClosure prq;
1947 GNUNET_HashCode dhash;
1948 GNUNET_HashCode mhash;
1949 GNUNET_HashCode query;
1955 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1956 "Done processing local replies, forwarding request to other peers.\n");
1958 if (pr->client_request_list != NULL)
1959 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
1961 /* no more results */
1962 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1963 pr->task = GNUNET_SCHEDULER_add_now (sched,
1964 &forward_request_task,
1968 if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
1971 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1972 "Found ONDEMAND block, performing on-demand encoding\n");
1975 GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
1976 anonymity, expiration, uid,
1977 &process_local_reply,
1979 GNUNET_FS_drq_get_next (GNUNET_YES);
1982 /* check for duplicates */
1983 GNUNET_CRYPTO_hash (data, size, &dhash);
1984 mingle_hash (&dhash,
1987 if ( (pr->bf != NULL) &&
1989 GNUNET_CONTAINER_bloomfilter_test (pr->bf,
1993 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1994 "Result from datastore filtered by bloomfilter (duplicate).\n");
1996 GNUNET_FS_drq_get_next (GNUNET_YES);
2000 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2001 "Found result for query `%s' in local datastore\n",
2004 pr->results_found++;
2005 if ( (pr->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
2006 (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
2007 (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) )
2012 pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
2016 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
2019 memset (&prq, 0, sizeof (prq));
2021 prq.expiration = expiration;
2023 if ( (type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) &&
2024 (GNUNET_OK != check_sblock ((const struct SBlock*) data,
2030 /* FIXME: consider removing the block? */
2031 GNUNET_FS_drq_get_next (GNUNET_YES);
2035 prq.priority = priority;
2036 process_reply (&prq, key, pr);
2038 if ( ( (pr->client_request_list == NULL) &&
2039 ( (GNUNET_YES == test_load_too_high()) ||
2040 (pr->results_found > 5 + 2 * pr->priority) ) ) ||
2041 (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK) )
2044 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2045 "Unique reply found or load too high, done with request\n");
2047 GNUNET_FS_drq_get_next (GNUNET_NO);
2050 GNUNET_FS_drq_get_next (GNUNET_YES);
2055 * The priority level imposes a bound on the maximum
2056 * value for the ttl that can be requested.
2058 * @param ttl_in requested ttl
2059 * @param prio given priority
2060 * @return ttl_in if ttl_in is below the limit,
2061 * otherwise the ttl-limit for the given priority
2064 bound_ttl (int32_t ttl_in, uint32_t prio)
2066 unsigned long long allowed;
2070 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
2071 if (ttl_in > allowed)
2073 if (allowed >= (1 << 30))
2082 * We've received a request with the specified priority. Bound it
2083 * according to how much we trust the given peer.
2085 * @param prio_in requested priority
2086 * @param cp the peer making the request
2087 * @return effective priority
2090 bound_priority (uint32_t prio_in,
2091 struct ConnectedPeer *cp)
2098 * Closure for 'check_duplicate_request'.
2100 struct CheckDuplicateRequestClosure
2103 * The new request we should check if it already exists.
2105 const struct PendingRequest *pr;
2108 * Existing request found by the checker, NULL if none.
2110 struct PendingRequest *have;
2115 * Iterator over entries in the 'query_request_map' that
2116 * tries to see if we have the same request pending from
2117 * the same peer already.
2119 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
2120 * @param key current key code (query, ignored, must match)
2121 * @param value value in the hash map (a 'struct PendingRequest'
2122 * that already exists)
2123 * @return GNUNET_YES if we should continue to
2124 * iterate (no match yet)
2125 * GNUNET_NO if not (match found).
2128 check_duplicate_request (void *cls,
2129 const GNUNET_HashCode * key,
2132 struct CheckDuplicateRequestClosure *cdc = cls;
2133 struct PendingRequest *have = value;
2135 if (cdc->pr->target_pid == have->target_pid)
2145 * Handle P2P "GET" request.
2147 * @param cls closure, always NULL
2148 * @param other the other peer involved (sender or receiver, NULL
2149 * for loopback messages where we are both sender and receiver)
2150 * @param message the actual message
2151 * @param latency reported latency of the connection with 'other'
2152 * @param distance reported distance (DV) to 'other'
2153 * @return GNUNET_OK to keep the connection open,
2154 * GNUNET_SYSERR to close it (signal serious error)
2157 handle_p2p_get (void *cls,
2158 const struct GNUNET_PeerIdentity *other,
2159 const struct GNUNET_MessageHeader *message,
2160 struct GNUNET_TIME_Relative latency,
2163 struct PendingRequest *pr;
2164 struct ConnectedPeer *cp;
2165 struct ConnectedPeer *cps;
2166 struct CheckDuplicateRequestClosure cdc;
2167 struct GNUNET_TIME_Relative timeout;
2169 const struct GetMessage *gm;
2171 const GNUNET_HashCode *opt;
2174 uint32_t ttl_decrement;
2178 msize = ntohs(message->size);
2179 if (msize < sizeof (struct GetMessage))
2181 GNUNET_break_op (0);
2182 return GNUNET_SYSERR;
2184 gm = (const struct GetMessage*) message;
2185 bm = ntohl (gm->hash_bitmap);
2193 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
2195 GNUNET_break_op (0);
2196 return GNUNET_SYSERR;
2198 opt = (const GNUNET_HashCode*) &gm[1];
2199 bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
2200 bm = ntohl (gm->hash_bitmap);
2201 if ( (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)) &&
2202 (ntohl (gm->type) == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) )
2204 GNUNET_break_op (0);
2205 return GNUNET_SYSERR;
2208 cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2209 &other->hashPubKey);
2210 GNUNET_assert (NULL != cps);
2211 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
2212 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2219 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
2220 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2221 "Failed to find RETURN-TO peer `%4s' in connection set. Dropping query.\n",
2222 GNUNET_i2s ((const struct GNUNET_PeerIdentity*) &opt[bits-1]));
2225 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2226 "Failed to find peer `%4s' in connection set. Dropping query.\n",
2227 GNUNET_i2s (other));
2229 /* FIXME: try connect? */
2232 /* note that we can really only check load here since otherwise
2233 peers could find out that we are overloaded by not being
2234 disconnected after sending us a malformed query... */
2235 if (GNUNET_YES == test_load_too_high ())
2238 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2239 "Dropping query from `%s', this peer is too busy.\n",
2240 GNUNET_i2s (other));
2246 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2247 "Received request for `%s' of type %u from peer `%4s'\n",
2248 GNUNET_h2s (&gm->query),
2249 (unsigned int) ntohl (gm->type),
2250 GNUNET_i2s (other));
2252 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
2253 (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)?sizeof(GNUNET_HashCode):0);
2254 if ((bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2255 pr->namespace = (GNUNET_HashCode*) &pr[1];
2256 pr->type = ntohl (gm->type);
2257 pr->mingle = ntohl (gm->filter_mutator);
2258 if (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2259 memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
2260 else if (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)
2262 GNUNET_break_op (0);
2264 return GNUNET_SYSERR;
2266 if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
2267 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
2269 pr->anonymity_level = 1;
2270 pr->priority = bound_priority (ntohl (gm->priority), cps);
2271 pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
2272 pr->query = gm->query;
2273 /* decrement ttl (always) */
2274 ttl_decrement = 2 * TTL_DECREMENT +
2275 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2277 if ( (pr->ttl < 0) &&
2278 (pr->ttl - ttl_decrement > 0) )
2281 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2282 "Dropping query from `%s' due to TTL underflow.\n",
2283 GNUNET_i2s (other));
2285 /* integer underflow => drop (should be very rare)! */
2289 pr->ttl -= ttl_decrement;
2290 pr->start_time = GNUNET_TIME_absolute_get ();
2292 /* get bloom filter */
2295 pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
2298 pr->bf_size = bfsize;
2303 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2305 &check_duplicate_request,
2307 if (cdc.have != NULL)
2309 if (cdc.have->start_time.value + cdc.have->ttl >=
2310 pr->start_time.value + pr->ttl)
2312 /* existing request has higher TTL, drop new one! */
2313 cdc.have->priority += pr->priority;
2314 destroy_pending_request (pr);
2316 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2317 "Have existing request with higher TTL, dropping new request.\n",
2318 GNUNET_i2s (other));
2324 /* existing request has lower TTL, drop old one! */
2325 pr->priority += cdc.have->priority;
2326 /* Possible optimization: if we have applicable pending
2327 replies in 'cdc.have', we might want to move those over
2328 (this is a really rare special-case, so it is not clear
2329 that this would be worth it) */
2330 destroy_pending_request (cdc.have);
2331 /* keep processing 'pr'! */
2336 GNUNET_CONTAINER_multihashmap_put (query_request_map,
2339 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2340 GNUNET_CONTAINER_multihashmap_put (peer_request_map,
2343 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2345 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
2347 pr->start_time.value + pr->ttl);
2350 /* calculate change in traffic preference */
2351 preference = (double) pr->priority;
2352 if (preference < QUERY_BANDWIDTH_VALUE)
2353 preference = QUERY_BANDWIDTH_VALUE;
2354 cps->inc_preference += preference;
2356 /* process locally */
2358 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2359 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2360 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
2361 (pr->priority + 1));
2362 pr->drq = GNUNET_FS_drq_get (&gm->query,
2364 &process_local_reply,
2369 /* Are multiple results possible? If so, start processing remotely now! */
2372 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2373 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2374 /* only one result, wait for datastore */
2377 pr->task = GNUNET_SCHEDULER_add_now (sched,
2378 &forward_request_task,
2382 /* make sure we don't track too many requests */
2383 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
2385 pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
2386 destroy_pending_request (pr);
2392 /* **************************** CS GET Handling ************************ */
2396 * Handle START_SEARCH-message (search request from client).
2398 * @param cls closure
2399 * @param client identification of the client
2400 * @param message the actual message
2403 handle_start_search (void *cls,
2404 struct GNUNET_SERVER_Client *client,
2405 const struct GNUNET_MessageHeader *message)
2407 static GNUNET_HashCode all_zeros;
2408 const struct SearchMessage *sm;
2409 struct ClientList *cl;
2410 struct ClientRequestList *crl;
2411 struct PendingRequest *pr;
2416 msize = ntohs (message->size);
2417 if ( (msize < sizeof (struct SearchMessage)) ||
2418 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
2421 GNUNET_SERVER_receive_done (client,
2425 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
2426 sm = (const struct SearchMessage*) message;
2429 while ( (cl != NULL) &&
2430 (cl->client != client) )
2434 cl = GNUNET_malloc (sizeof (struct ClientList));
2435 cl->client = client;
2436 GNUNET_SERVER_client_keep (client);
2437 cl->next = client_list;
2440 type = ntohl (sm->type);
2442 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2443 "Received request for `%s' of type %u from local client\n",
2444 GNUNET_h2s (&sm->query),
2445 (unsigned int) type);
2448 /* detect duplicate KBLOCK requests */
2449 if (type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK)
2452 while ( (crl != NULL) &&
2453 ( (0 != memcmp (&crl->req->query,
2455 sizeof (GNUNET_HashCode))) ||
2456 (crl->req->type != type) ) )
2461 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2462 "Have existing request, merging content-seen lists.\n");
2465 /* Duplicate request (used to send long list of
2466 known/blocked results); merge 'pr->replies_seen'
2467 and update bloom filter */
2468 GNUNET_array_grow (pr->replies_seen,
2469 pr->replies_seen_size,
2470 pr->replies_seen_off + sc);
2471 memcpy (&pr->replies_seen[pr->replies_seen_off],
2473 sc * sizeof (GNUNET_HashCode));
2474 pr->replies_seen_off += sc;
2476 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
2477 pr->bf = refresh_bloomfilter (pr->replies_seen_off,
2481 GNUNET_SERVER_receive_done (client,
2486 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
2487 ((type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)?sizeof(GNUNET_HashCode):0));
2488 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
2489 memset (crl, 0, sizeof (struct ClientRequestList));
2490 crl->client_list = cl;
2491 GNUNET_CONTAINER_DLL_insert (cl->rl_head,
2496 pr->client_request_list = crl;
2497 GNUNET_array_grow (pr->replies_seen,
2498 pr->replies_seen_size,
2500 memcpy (pr->replies_seen,
2502 sc * sizeof (GNUNET_HashCode));
2503 pr->replies_seen_off = sc;
2504 pr->anonymity_level = ntohl (sm->anonymity_level);
2505 pr->bf = refresh_bloomfilter (pr->replies_seen_off,
2509 pr->query = sm->query;
2512 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2513 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2514 if (0 != memcmp (&sm->target,
2516 sizeof (GNUNET_HashCode)))
2517 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
2519 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2520 pr->namespace = (GNUNET_HashCode*) &pr[1];
2521 memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
2526 GNUNET_CONTAINER_multihashmap_put (query_request_map,
2529 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2530 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2531 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* get on-demand blocks too! */
2532 pr->drq = GNUNET_FS_drq_get (&sm->query,
2534 &process_local_reply,
2536 GNUNET_TIME_UNIT_FOREVER_REL,
2541 /* **************************** Startup ************************ */
2545 * List of handlers for P2P messages
2546 * that we care about.
2548 static struct GNUNET_CORE_MessageHandler p2p_handlers[] =
2551 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
2553 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
2559 * List of handlers for the messages understood by this
2562 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2563 {&GNUNET_FS_handle_index_start, NULL,
2564 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
2565 {&GNUNET_FS_handle_index_list_get, NULL,
2566 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
2567 {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
2568 sizeof (struct UnindexMessage) },
2569 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
2576 * Process fs requests.
2578 * @param s scheduler to use
2579 * @param server the initialized server
2580 * @param c configuration to use
2583 main_init (struct GNUNET_SCHEDULER_Handle *s,
2584 struct GNUNET_SERVER_Handle *server,
2585 const struct GNUNET_CONFIGURATION_Handle *c)
2589 connected_peers = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2590 query_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2591 peer_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2592 requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2593 core = GNUNET_CORE_connect (sched,
2595 GNUNET_TIME_UNIT_FOREVER_REL,
2599 &peer_connect_handler,
2600 &peer_disconnect_handler,
2606 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2607 _("Failed to connect to `%s' service.\n"),
2609 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
2610 connected_peers = NULL;
2611 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
2612 query_request_map = NULL;
2613 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
2614 requests_by_expiration_heap = NULL;
2615 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
2616 peer_request_map = NULL;
2618 return GNUNET_SYSERR;
2620 GNUNET_SERVER_disconnect_notify (server,
2621 &handle_client_disconnect,
2623 GNUNET_SERVER_add_handlers (server, handlers);
2624 GNUNET_SCHEDULER_add_delayed (sched,
2625 GNUNET_TIME_UNIT_FOREVER_REL,
2633 * Process fs requests.
2635 * @param cls closure
2636 * @param sched scheduler to use
2637 * @param server the initialized server
2638 * @param cfg configuration to use
2642 struct GNUNET_SCHEDULER_Handle *sched,
2643 struct GNUNET_SERVER_Handle *server,
2644 const struct GNUNET_CONFIGURATION_Handle *cfg)
2646 if ( (GNUNET_OK != GNUNET_FS_drq_init (sched, cfg)) ||
2647 (GNUNET_OK != GNUNET_FS_indexing_init (sched, cfg)) ||
2648 (GNUNET_OK != main_init (sched, server, cfg)) )
2650 GNUNET_SCHEDULER_shutdown (sched);
2657 * The main function for the fs service.
2659 * @param argc number of arguments from the command line
2660 * @param argv command line arguments
2661 * @return 0 ok, 1 on error
2664 main (int argc, char *const *argv)
2666 return (GNUNET_OK ==
2667 GNUNET_SERVICE_run (argc,
2670 GNUNET_SERVICE_OPTION_NONE,
2671 &run, NULL)) ? 0 : 1;
2674 /* end of gnunet-service-fs.c */