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 * - forward_request_task (P2P forwarding!)
28 * - track stats for hot-path routing
29 * - implement hot-path routing decision procedure
30 * - detect duplicate requests (P2P and CS)
31 * - implement: bound_priority, test_load_too_high, validate_skblock
32 * - add content migration support (store locally)
38 #include "gnunet_constants.h"
39 #include "gnunet_core_service.h"
40 #include "gnunet_datastore_service.h"
41 #include "gnunet_peer_lib.h"
42 #include "gnunet_protocols.h"
43 #include "gnunet_signatures.h"
44 #include "gnunet_util_lib.h"
45 #include "gnunet-service-fs_drq.h"
46 #include "gnunet-service-fs_indexing.h"
49 #define DEBUG_FS GNUNET_NO
52 * Maximum number of outgoing messages we queue per peer.
53 * FIXME: set to a tiny value for testing; make configurable.
55 #define MAX_QUEUE_PER_PEER 2
59 * Maximum number of requests (from other peers) that we're
60 * willing to have pending at any given point in time.
61 * FIXME: set from configuration (and 32 is a tiny value for testing only).
63 static uint64_t max_pending_requests = 32;
67 * Information we keep for each pending reply. The
68 * actual message follows at the end of this struct.
70 struct PendingMessage;
74 * Function called upon completion of a transmission.
77 * @param pid ID of receiving peer, 0 on transmission error
79 typedef void (*TransmissionContinuation)(void * cls,
84 * Information we keep for each pending reply. The
85 * actual message follows at the end of this struct.
90 * This is a doubly-linked list of messages to the same peer.
92 struct PendingMessage *next;
95 * This is a doubly-linked list of messages to the same peer.
97 struct PendingMessage *prev;
100 * Entry in pending message list for this pending message.
102 struct PendingMessageList *pml;
105 * Function to call immediately once we have transmitted this
108 TransmissionContinuation cont;
116 * Size of the reply; actual reply message follows
117 * at the end of this struct.
122 * How important is this message for us?
130 * Information about a peer that we are connected to.
131 * We track data that is useful for determining which
132 * peers should receive our requests. We also keep
133 * a list of messages to transmit to this peer.
139 * List of the last clients for which this peer successfully
142 struct GNUNET_SERVER_Client *last_client_replies[CS2P_SUCCESS_LIST_SIZE];
145 * List of the last PIDs for which
146 * this peer successfully answered a query;
147 * We use 0 to indicate no successful reply.
149 GNUNET_PEER_Id last_p2p_replies[P2P_SUCCESS_LIST_SIZE];
152 * Average delay between sending the peer a request and
153 * getting a reply (only calculated over the requests for
154 * which we actually got a reply). Calculated
155 * as a moving average: new_delay = ((n-1)*last_delay+curr_delay) / n
157 struct GNUNET_TIME_Relative avg_delay;
160 * Handle for an active request for transmission to this
163 struct GNUNET_CORE_TransmitHandle *cth;
166 * Messages (replies, queries, content migration) we would like to
167 * send to this peer in the near future. Sorted by priority, head.
169 struct PendingMessage *pending_messages_head;
172 * Messages (replies, queries, content migration) we would like to
173 * send to this peer in the near future. Sorted by priority, tail.
175 struct PendingMessage *pending_messages_tail;
178 * Average priority of successful replies. Calculated
179 * as a moving average: new_avg = ((n-1)*last_avg+curr_prio) / n
184 * Increase in traffic preference still to be submitted
185 * to the core service for this peer. FIXME: double or 'uint64_t'?
187 double inc_preference;
190 * The peer's identity.
195 * Size of the linked list of 'pending_messages'.
197 unsigned int pending_requests;
200 * Which offset in "last_p2p_replies" will be updated next?
201 * (we go round-robin).
203 unsigned int last_p2p_replies_woff;
206 * Which offset in "last_client_replies" will be updated next?
207 * (we go round-robin).
209 unsigned int last_client_replies_woff;
215 * Information we keep for each pending request. We should try to
216 * keep this struct as small as possible since its memory consumption
217 * is key to how many requests we can have pending at once.
219 struct PendingRequest;
223 * Doubly-linked list of requests we are performing
224 * on behalf of the same client.
226 struct ClientRequestList
230 * This is a doubly-linked list.
232 struct ClientRequestList *next;
235 * This is a doubly-linked list.
237 struct ClientRequestList *prev;
240 * Request this entry represents.
242 struct PendingRequest *req;
245 * Client list this request belongs to.
247 struct ClientList *client_list;
253 * Replies to be transmitted to the client. The actual
254 * response message is allocated after this struct.
256 struct ClientResponseMessage
259 * This is a doubly-linked list.
261 struct ClientResponseMessage *next;
264 * This is a doubly-linked list.
266 struct ClientResponseMessage *prev;
269 * Client list entry this response belongs to.
271 struct ClientList *client_list;
274 * Number of bytes in the response.
281 * Linked list of clients we are performing requests
287 * This is a linked list.
289 struct ClientList *next;
292 * ID of a client making a request, NULL if this entry is for a
295 struct GNUNET_SERVER_Client *client;
298 * Head of list of requests performed on behalf
299 * of this client right now.
301 struct ClientRequestList *rl_head;
304 * Tail of list of requests performed on behalf
305 * of this client right now.
307 struct ClientRequestList *rl_tail;
310 * Head of linked list of responses.
312 struct ClientResponseMessage *res_head;
315 * Tail of linked list of responses.
317 struct ClientResponseMessage *res_tail;
320 * Context for sending replies.
322 struct GNUNET_CONNECTION_TransmitHandle *th;
328 * Hash map entry of requests we are performing
329 * on behalf of the same peer.
331 struct PeerRequestEntry
335 * Request this entry represents.
337 struct PendingRequest *req;
340 * Entry of peer responsible for this entry.
342 struct ConnectedPeer *cp;
348 * Doubly-linked list of messages we are performing
349 * due to a pending request.
351 struct PendingMessageList
355 * This is a doubly-linked list of messages on behalf of the same request.
357 struct PendingMessageList *next;
360 * This is a doubly-linked list of messages on behalf of the same request.
362 struct PendingMessageList *prev;
365 * Message this entry represents.
367 struct PendingMessage *pm;
370 * Request this entry belongs to.
372 struct PendingRequest *req;
375 * Peer this message is targeted for.
377 struct ConnectedPeer *target;
383 * Information we keep for each pending request. We should try to
384 * keep this struct as small as possible since its memory consumption
385 * is key to how many requests we can have pending at once.
387 struct PendingRequest
391 * If this request was made by a client, this is our entry in the
392 * client request list; otherwise NULL.
394 struct ClientRequestList *client_request_list;
397 * If this request was made by a peer, this is our entry in the
398 * per-peer multi-hash map; otherwise NULL.
400 struct PeerRequestEntry *pht_entry;
403 * If this is a namespace query, pointer to the hash of the public
404 * key of the namespace; otherwise NULL. Pointer will be to the
405 * end of this struct (so no need to free it).
407 const GNUNET_HashCode *namespace;
410 * Bloomfilter we use to filter out replies that we don't care about
411 * (anymore). NULL as long as we are interested in all replies.
413 struct GNUNET_CONTAINER_BloomFilter *bf;
416 * Context of our GNUNET_CORE_peer_change_preference call.
418 struct GNUNET_CORE_InformationRequestContext *irc;
421 * Hash code of all replies that we have seen so far (only valid
422 * if client is not NULL since we only track replies like this for
425 GNUNET_HashCode *replies_seen;
428 * Node in the heap representing this entry; NULL
429 * if we have no heap node.
431 struct GNUNET_CONTAINER_HeapNode *hnode;
434 * Head of list of messages being performed on behalf of this
437 struct PendingMessageList *pending_head;
440 * Tail of list of messages being performed on behalf of this
443 struct PendingMessageList *pending_tail;
446 * When did we first see this request (form this peer), or, if our
447 * client is initiating, when did we last initiate a search?
449 struct GNUNET_TIME_Absolute start_time;
452 * The query that this request is for.
454 GNUNET_HashCode query;
457 * The task responsible for transmitting queries
460 GNUNET_SCHEDULER_TaskIdentifier task;
463 * (Interned) Peer identifier that identifies a preferred target
466 GNUNET_PEER_Id target_pid;
469 * (Interned) Peer identifiers of peers that have already
470 * received our query for this content.
472 GNUNET_PEER_Id *used_pids;
475 * Our entry in the DRQ (non-NULL while we wait for our
476 * turn to interact with the local database).
478 struct DatastoreRequestQueue *drq;
481 * Size of the 'bf' (in bytes).
486 * Desired anonymity level; only valid for requests from a local client.
488 uint32_t anonymity_level;
491 * How many entries in "used_pids" are actually valid?
493 unsigned int used_pids_off;
496 * How long is the "used_pids" array?
498 unsigned int used_pids_size;
501 * Number of results found for this request.
503 unsigned int results_found;
506 * How many entries in "replies_seen" are actually valid?
508 unsigned int replies_seen_off;
511 * How long is the "replies_seen" array?
513 unsigned int replies_seen_size;
516 * Priority with which this request was made. If one of our clients
517 * made the request, then this is the current priority that we are
518 * using when initiating the request. This value is used when
519 * we decide to reward other peers with trust for providing a reply.
524 * Priority points left for us to spend when forwarding this request
527 uint32_t remaining_priority;
530 * Number to mingle hashes for bloom-filter
536 * TTL with which we saw this request (or, if we initiated, TTL that
537 * we used for the request).
542 * Type of the content that this request is for.
552 static struct GNUNET_SCHEDULER_Handle *sched;
557 const struct GNUNET_CONFIGURATION_Handle *cfg;
560 * Map of peer identifiers to "struct ConnectedPeer" (for that peer).
562 static struct GNUNET_CONTAINER_MultiHashMap *connected_peers;
565 * Map of peer identifiers to "struct PendingRequest" (for that peer).
567 static struct GNUNET_CONTAINER_MultiHashMap *peer_request_map;
570 * Map of query identifiers to "struct PendingRequest" (for that query).
572 static struct GNUNET_CONTAINER_MultiHashMap *query_request_map;
575 * Heap with the request that will expire next at the top. Contains
576 * pointers of type "struct PendingRequest*"; these will *also* be
577 * aliased from the "requests_by_peer" data structures and the
578 * "requests_by_query" table. Note that requests from our clients
579 * don't expire and are thus NOT in the "requests_by_expiration"
580 * (or the "requests_by_peer" tables).
582 static struct GNUNET_CONTAINER_Heap *requests_by_expiration_heap;
585 * Linked list of clients we are currently processing requests for.
587 struct ClientList *client_list;
590 * Pointer to handle to the core service (points to NULL until we've
593 struct GNUNET_CORE_Handle *core;
596 /* ******************* clean up functions ************************ */
600 * We're done with a particular message list entry.
601 * Free all associated resources.
603 * @param pml entry to destroy
606 destroy_pending_message_list_entry (struct PendingMessageList *pml)
608 GNUNET_CONTAINER_DLL_remove (pml->req->pending_head,
609 pml->req->pending_tail,
611 GNUNET_CONTAINER_DLL_remove (pml->target->pending_messages_head,
612 pml->target->pending_messages_tail,
614 pml->target->pending_requests--;
615 GNUNET_free (pml->pm);
621 * Destroy the given pending message (and call the respective
624 * @param pm message to destroy
625 * @param tpid id of peer that the message was delivered to, or 0 for none
628 destroy_pending_message (struct PendingMessage *pm,
631 struct PendingMessageList *pml = pm->pml;
633 GNUNET_assert (pml->pm == pm);
634 GNUNET_assert ( (tpid == 0) || (tpid == pml->target->pid) );
635 pm->cont (pm->cont_cls, 0);
636 destroy_pending_message_list_entry (pml);
642 * We're done processing a particular request.
643 * Free all associated resources.
645 * @param pr request to destroy
648 destroy_pending_request (struct PendingRequest *pr)
650 struct GNUNET_PeerIdentity pid;
652 if (pr->hnode != NULL)
654 GNUNET_CONTAINER_heap_remove_node (requests_by_expiration_heap,
658 /* might have already been removed from map
659 in 'process_reply' if there was a unique
660 reply; hence ignore the return value here */
661 (void) GNUNET_CONTAINER_multihashmap_remove (query_request_map,
666 GNUNET_FS_drq_get_cancel (pr->drq);
669 if (pr->client_request_list != NULL)
671 GNUNET_CONTAINER_DLL_remove (pr->client_request_list->client_list->rl_head,
672 pr->client_request_list->client_list->rl_tail,
673 pr->client_request_list);
674 GNUNET_free (pr->client_request_list);
675 pr->client_request_list = NULL;
677 if (pr->pht_entry != NULL)
679 GNUNET_PEER_resolve (pr->pht_entry->cp->pid,
681 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
684 GNUNET_free (pr->pht_entry);
685 pr->pht_entry = NULL;
689 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
694 GNUNET_CORE_peer_change_preference_cancel (pr->irc);
697 if (pr->replies_seen != NULL)
699 GNUNET_free (pr->replies_seen);
700 pr->replies_seen = NULL;
702 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
704 GNUNET_SCHEDULER_cancel (sched,
706 pr->task = GNUNET_SCHEDULER_NO_TASK;
708 while (NULL != pr->pending_head)
709 destroy_pending_message_list_entry (pr->pending_head);
710 GNUNET_PEER_change_rc (pr->target_pid, -1);
711 if (pr->used_pids != NULL)
713 GNUNET_PEER_decrement_rcs (pr->used_pids, pr->used_pids_off);
714 GNUNET_free (pr->used_pids);
715 pr->used_pids_off = 0;
716 pr->used_pids_size = 0;
717 pr->used_pids = NULL;
724 * Method called whenever a given peer connects.
726 * @param cls closure, not used
727 * @param peer peer identity this notification is about
728 * @param latency reported latency of the connection with 'other'
729 * @param distance reported distance (DV) to 'other'
732 peer_connect_handler (void *cls,
734 GNUNET_PeerIdentity * peer,
735 struct GNUNET_TIME_Relative latency,
738 struct ConnectedPeer *cp;
740 cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
741 cp->pid = GNUNET_PEER_intern (peer);
742 GNUNET_CONTAINER_multihashmap_put (connected_peers,
745 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
750 * Free (each) request made by the peer.
752 * @param cls closure, points to peer that the request belongs to
753 * @param key current key code
754 * @param value value in the hash map
755 * @return GNUNET_YES (we should continue to iterate)
758 destroy_request (void *cls,
759 const GNUNET_HashCode * key,
762 const struct GNUNET_PeerIdentity * peer = cls;
763 struct PendingRequest *pr = value;
765 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
768 destroy_pending_request (pr);
774 * Method called whenever a peer disconnects.
776 * @param cls closure, not used
777 * @param peer peer identity this notification is about
780 peer_disconnect_handler (void *cls,
782 GNUNET_PeerIdentity * peer)
784 struct ConnectedPeer *cp;
785 struct PendingMessage *pm;
788 GNUNET_CONTAINER_multihashmap_get_multiple (peer_request_map,
792 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
796 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
798 if (NULL != cp->last_client_replies[i])
800 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
801 cp->last_client_replies[i] = NULL;
804 GNUNET_CONTAINER_multihashmap_remove (connected_peers,
807 GNUNET_PEER_change_rc (cp->pid, -1);
808 GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
810 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
811 while (NULL != (pm = cp->pending_messages_head))
812 destroy_pending_message (pm, 0 /* delivery failed */);
813 GNUNET_break (0 == cp->pending_requests);
819 * Iterator over hash map entries that removes all occurences
820 * of the given 'client' from the 'last_client_replies' of the
821 * given connected peer.
823 * @param cls closure, the 'struct GNUNET_SERVER_Client*' to remove
824 * @param key current key code (unused)
825 * @param value value in the hash map (the 'struct ConnectedPeer*' to change)
826 * @return GNUNET_YES (we should continue to iterate)
829 remove_client_from_last_client_replies (void *cls,
830 const GNUNET_HashCode * key,
833 struct GNUNET_SERVER_Client *client = cls;
834 struct ConnectedPeer *cp = value;
837 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
839 if (cp->last_client_replies[i] == client)
841 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
842 cp->last_client_replies[i] = NULL;
850 * A client disconnected. Remove all of its pending queries.
852 * @param cls closure, NULL
853 * @param client identification of the client
856 handle_client_disconnect (void *cls,
857 struct GNUNET_SERVER_Client
860 struct ClientList *pos;
861 struct ClientList *prev;
862 struct ClientRequestList *rcl;
863 struct ClientResponseMessage *creply;
866 return; /* huh? is this allowed? */
869 while ( (NULL != pos) &&
870 (pos->client != client) )
876 return; /* no requests pending for this client */
877 while (NULL != (rcl = pos->rl_head))
878 destroy_pending_request (rcl->req);
880 client_list = pos->next;
882 prev->next = pos->next;
885 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
888 while (NULL != (creply = pos->res_head))
890 GNUNET_CONTAINER_DLL_remove (pos->res_head,
893 GNUNET_free (creply);
895 GNUNET_SERVER_client_drop (pos->client);
897 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
898 &remove_client_from_last_client_replies,
904 * Iterator to free peer entries.
906 * @param cls closure, unused
907 * @param key current key code
908 * @param value value in the hash map (peer entry)
909 * @return GNUNET_YES (we should continue to iterate)
912 clean_peer (void *cls,
913 const GNUNET_HashCode * key,
916 peer_disconnect_handler (NULL, (const struct GNUNET_PeerIdentity*) key);
922 * Task run during shutdown.
928 shutdown_task (void *cls,
929 const struct GNUNET_SCHEDULER_TaskContext *tc)
931 while (client_list != NULL)
932 handle_client_disconnect (NULL,
933 client_list->client);
934 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
937 GNUNET_break (0 == GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap));
938 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
939 requests_by_expiration_heap = 0;
940 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
941 connected_peers = NULL;
942 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (query_request_map));
943 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
944 query_request_map = NULL;
945 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (peer_request_map));
946 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
947 peer_request_map = NULL;
948 GNUNET_assert (NULL != core);
949 GNUNET_CORE_disconnect (core);
956 /* ******************* Utility functions ******************** */
960 * Transmit the given message by copying it to the target buffer
961 * "buf". "buf" will be NULL and "size" zero if the socket was closed
962 * for writing in the meantime. In that case, do nothing
963 * (the disconnect or shutdown handler will take care of the rest).
964 * If we were able to transmit messages and there are still more
965 * pending, ask core again for further calls to this function.
967 * @param cls closure, pointer to the 'struct ConnectedPeer*'
968 * @param size number of bytes available in buf
969 * @param buf where the callee should write the message
970 * @return number of bytes written to buf
973 transmit_to_peer (void *cls,
974 size_t size, void *buf)
976 struct ConnectedPeer *cp = cls;
978 struct GNUNET_PeerIdentity pid;
979 struct PendingMessage *pm;
986 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
987 "Dropping reply, core too busy.\n");
992 while ( (NULL != (pm = cp->pending_messages_head) ) &&
993 (pm->msize <= size) )
995 memcpy (&cbuf[msize], &pm[1], pm->msize);
998 destroy_pending_message (pm, cp->pid);
1002 GNUNET_PEER_resolve (cp->pid,
1004 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1006 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1017 * Add a message to the set of pending messages for the given peer.
1019 * @param cp peer to send message to
1020 * @param pm message to queue
1021 * @param pr request on which behalf this message is being queued
1024 add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
1025 struct PendingMessage *pm,
1026 struct PendingRequest *pr)
1028 struct PendingMessage *pos;
1029 struct PendingMessageList *pml;
1030 struct GNUNET_PeerIdentity pid;
1032 GNUNET_assert (pm->next == NULL);
1033 GNUNET_assert (pm->pml == NULL);
1034 pml = GNUNET_malloc (sizeof (struct PendingMessageList));
1039 GNUNET_CONTAINER_DLL_insert (pr->pending_head,
1042 pos = cp->pending_messages_head;
1043 while ( (pos != NULL) &&
1044 (pm->priority < pos->priority) )
1046 GNUNET_CONTAINER_DLL_insert_after (cp->pending_messages_head,
1047 cp->pending_messages_tail,
1050 cp->pending_requests++;
1051 if (cp->pending_requests > MAX_QUEUE_PER_PEER)
1052 destroy_pending_message (cp->pending_messages_tail, 0);
1053 if (cp->cth == NULL)
1055 /* need to schedule transmission */
1056 GNUNET_PEER_resolve (cp->pid, &pid);
1057 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1058 cp->pending_messages_head->priority,
1059 GNUNET_TIME_UNIT_FOREVER_REL,
1061 cp->pending_messages_head->msize,
1065 if (cp->cth == NULL)
1067 /* FIXME: call stats (rare, bad case) */
1073 * Mingle hash with the mingle_number to produce different bits.
1076 mingle_hash (const GNUNET_HashCode * in,
1077 int32_t mingle_number,
1078 GNUNET_HashCode * hc)
1082 GNUNET_CRYPTO_hash (&mingle_number,
1085 GNUNET_CRYPTO_hash_xor (&m, in, hc);
1090 * Test if the load on this peer is too high
1091 * to even consider processing the query at
1094 * @return GNUNET_YES if the load is too high, GNUNET_NO otherwise
1097 test_load_too_high ()
1099 return GNUNET_NO; // FIXME
1103 /* ******************* Pending Request Refresh Task ******************** */
1107 * Function called after we either failed or succeeded
1108 * at transmitting a query to a peer.
1110 * @param cls the requests "struct PendingRequest*"
1111 * @param pid ID of receiving peer, 0 on transmission error
1114 transmit_query_continuation (void *cls,
1115 GNUNET_PEER_Id tpid)
1117 struct PendingRequest *pr = cls;
1121 GNUNET_PEER_change_rc (tpid, 1);
1122 if (pr->used_pids_off == pr->used_pids_size)
1123 GNUNET_array_grow (pr->used_pids,
1125 pr->used_pids_size * 2 + 2);
1126 pr->used_pids[pr->used_pids_off++] = tpid;
1132 * How many bytes should a bloomfilter be if we have already seen
1133 * entry_count responses? Note that BLOOMFILTER_K gives us the number
1134 * of bits set per entry. Furthermore, we should not re-size the
1135 * filter too often (to keep it cheap).
1137 * Since other peers will also add entries but not resize the filter,
1138 * we should generally pick a slightly larger size than what the
1139 * strict math would suggest.
1141 * @return must be a power of two and smaller or equal to 2^15.
1144 compute_bloomfilter_size (unsigned int entry_count)
1147 unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
1148 uint16_t max = 1 << 15;
1150 if (entry_count > max)
1153 while ((size < max) && (size < ideal))
1162 * Recalculate our bloom filter for filtering replies.
1164 * @param count number of entries we are filtering right now
1165 * @param mingle set to our new mingling value
1166 * @param bf_size set to the size of the bloomfilter
1167 * @param entries the entries to filter
1168 * @return updated bloomfilter, NULL for none
1170 static struct GNUNET_CONTAINER_BloomFilter *
1171 refresh_bloomfilter (unsigned int count,
1174 const GNUNET_HashCode *entries)
1176 struct GNUNET_CONTAINER_BloomFilter *bf;
1179 GNUNET_HashCode mhash;
1183 nsize = compute_bloomfilter_size (count);
1184 *mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
1186 bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1189 for (i=0;i<count;i++)
1191 mingle_hash (&entries[i], *mingle, &mhash);
1192 GNUNET_CONTAINER_bloomfilter_add (bf, &mhash);
1200 * We use a random delay to make the timing of requests less
1201 * predictable. This function returns such a random delay.
1203 * FIXME: make schedule dependent on the specifics of the request?
1204 * Or bandwidth and number of connected peers and load?
1206 * @return random delay to use for some request, between 0 and TTL_DECREMENT ms
1208 static struct GNUNET_TIME_Relative
1209 get_processing_delay ()
1211 return GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1212 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1218 * Function called after we've tried to reserve a certain amount of
1219 * bandwidth for a reply. Check if we succeeded and if so send our
1222 * @param cls the requests "struct PendingRequest*"
1223 * @param peer identifies the peer
1224 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1225 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1226 * @param amount set to the amount that was actually reserved or unreserved
1227 * @param preference current traffic preference for the given peer
1230 target_reservation_cb (void *cls,
1232 GNUNET_PeerIdentity * peer,
1233 unsigned int bpm_in,
1234 unsigned int bpm_out,
1236 uint64_t preference)
1238 struct PendingRequest *pr = cls;
1239 struct ConnectedPeer *cp;
1240 struct PendingMessage *pm;
1241 struct GetMessage *gm;
1242 GNUNET_HashCode *ext;
1249 GNUNET_assert (peer != NULL);
1250 // (3) transmit, update ttl/priority
1251 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1255 /* Peer must have just left */
1258 no_route = GNUNET_NO;
1259 if (amount != DBLOCK_SIZE)
1261 if (pr->pht_entry == NULL)
1262 return; /* this target round failed */
1263 /* FIXME: if we are "quite" busy, we may still want to skip
1264 this round; need more load detection code! */
1265 no_route = GNUNET_YES;
1268 /* build message and insert message into priority queue */
1270 if (pr->namespace != NULL)
1272 if (pr->target_pid != 0)
1274 if (GNUNET_YES == no_route)
1276 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
1277 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1278 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1280 gm = (struct GetMessage*) &pm[1];
1281 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
1282 gm->header.size = htons (msize);
1283 gm->type = htonl (pr->type);
1284 pr->remaining_priority /= 2;
1285 gm->priority = htonl (pr->remaining_priority);
1286 gm->ttl = htonl (pr->ttl);
1287 gm->filter_mutator = htonl(pr->mingle); // FIXME: bad endianess conversion?
1288 gm->hash_bitmap = htonl (42); // FIXME!
1289 gm->query = pr->query;
1290 ext = (GNUNET_HashCode*) &gm[1];
1292 if (pr->namespace != NULL)
1293 memcpy (&ext[k++], pr->namespace, sizeof (GNUNET_HashCode));
1294 if (pr->target_pid != 0)
1295 GNUNET_PEER_resolve (pr->target_pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1296 if (GNUNET_YES == no_route)
1297 GNUNET_PEER_resolve (pr->pht_entry->cp->pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1298 bfdata = (char *) &ext[k];
1300 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
1303 pm->cont = &transmit_query_continuation;
1305 add_to_pending_messages_for_peer (cp, pm, pr);
1310 * Closure used for "target_peer_select_cb".
1312 struct PeerSelectionContext
1315 * The request for which we are selecting
1318 struct PendingRequest *pr;
1321 * Current "prime" target.
1323 struct GNUNET_PeerIdentity target;
1326 * How much do we like this target?
1328 double target_score;
1334 * Function called for each connected peer to determine
1335 * which one(s) would make good targets for forwarding.
1337 * @param cls closure (struct PeerSelectionContext)
1338 * @param key current key code (peer identity)
1339 * @param value value in the hash map (struct ConnectedPeer)
1340 * @return GNUNET_YES if we should continue to
1345 target_peer_select_cb (void *cls,
1346 const GNUNET_HashCode * key,
1349 struct PeerSelectionContext *psc = cls;
1350 struct ConnectedPeer *cp = value;
1351 struct PendingRequest *pr = psc->pr;
1355 /* 1) check if we have already (recently) forwarded to this peer */
1356 for (i=0;i<pr->used_pids_off;i++)
1357 if (pr->used_pids[i] == cp->pid)
1358 return GNUNET_YES; /* skip */
1359 // 2) calculate how much we'd like to forward to this peer
1360 score = 42; // FIXME!
1361 // FIXME: also need API to gather data on responsiveness
1362 // of this peer (we have fields for that in 'cp', but
1363 // they are never set!)
1365 /* store best-fit in closure */
1366 if (score > psc->target_score)
1368 psc->target_score = score;
1369 psc->target.hashPubKey = *key;
1376 * We're processing a GET request from another peer and have decided
1377 * to forward it to other peers. This function is called periodically
1378 * and should forward the request to other peers until we have all
1379 * possible replies. If we have transmitted the *only* reply to
1380 * the initiator we should destroy the pending request. If we have
1381 * many replies in the queue to the initiator, we should delay sending
1382 * out more queries until the reply queue has shrunk some.
1384 * @param cls our "struct ProcessGetContext *"
1388 forward_request_task (void *cls,
1389 const struct GNUNET_SCHEDULER_TaskContext *tc)
1391 struct PendingRequest *pr = cls;
1392 struct PeerSelectionContext psc;
1393 struct ConnectedPeer *cp;
1395 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1396 get_processing_delay (),
1397 &forward_request_task,
1399 if (pr->irc != NULL)
1400 return; /* previous request still pending */
1401 /* (1) select target */
1403 psc.target_score = DBL_MIN;
1404 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1405 &target_peer_select_cb,
1407 if (psc.target_score == DBL_MIN)
1408 return; /* nobody selected */
1410 /* (2) reserve reply bandwidth */
1411 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1412 &psc.target.hashPubKey);
1413 pr->irc = GNUNET_CORE_peer_change_preference (sched, cfg,
1415 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1416 (uint32_t) -1 /* no limit */,
1418 (uint64_t) cp->inc_preference,
1419 &target_reservation_cb,
1421 cp->inc_preference = 0.0;
1425 /* **************************** P2P PUT Handling ************************ */
1429 * Function called after we either failed or succeeded
1430 * at transmitting a reply to a peer.
1432 * @param cls the requests "struct PendingRequest*"
1433 * @param pid ID of receiving peer, 0 on transmission error
1436 transmit_reply_continuation (void *cls,
1437 GNUNET_PEER_Id tpid)
1439 struct PendingRequest *pr = cls;
1443 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1444 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1445 /* only one reply expected, done with the request! */
1446 destroy_pending_request (pr);
1448 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1449 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1459 * Check if the given KBlock is well-formed.
1461 * @param kb the kblock data (or at least "dsize" bytes claiming to be one)
1462 * @param dsize size of "kb" in bytes; check for < sizeof(struct KBlock)!
1463 * @param query where to store the query that this block answers
1464 * @return GNUNET_OK if this is actually a well-formed KBlock
1467 check_kblock (const struct KBlock *kb,
1469 GNUNET_HashCode *query)
1471 if (dsize < sizeof (struct KBlock))
1473 GNUNET_break_op (0);
1474 return GNUNET_SYSERR;
1476 if (dsize - sizeof (struct KBlock) !=
1477 ntohs (kb->purpose.size)
1478 - sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose)
1479 - sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) )
1481 GNUNET_break_op (0);
1482 return GNUNET_SYSERR;
1485 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_KBLOCK,
1490 GNUNET_break_op (0);
1491 return GNUNET_SYSERR;
1494 GNUNET_CRYPTO_hash (&kb->keyspace,
1495 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1502 * Check if the given SBlock is well-formed.
1504 * @param sb the sblock data (or at least "dsize" bytes claiming to be one)
1505 * @param dsize size of "kb" in bytes; check for < sizeof(struct SBlock)!
1506 * @param query where to store the query that this block answers
1507 * @param namespace where to store the namespace that this block belongs to
1508 * @return GNUNET_OK if this is actually a well-formed SBlock
1511 check_sblock (const struct SBlock *sb,
1513 GNUNET_HashCode *query,
1514 GNUNET_HashCode *namespace)
1516 if (dsize < sizeof (struct SBlock))
1518 GNUNET_break_op (0);
1519 return GNUNET_SYSERR;
1522 ntohs (sb->purpose.size) + sizeof (struct GNUNET_CRYPTO_RsaSignature))
1524 GNUNET_break_op (0);
1525 return GNUNET_SYSERR;
1528 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_SBLOCK,
1533 GNUNET_break_op (0);
1534 return GNUNET_SYSERR;
1537 *query = sb->identifier;
1538 if (namespace != NULL)
1539 GNUNET_CRYPTO_hash (&sb->subspace,
1540 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1547 * Transmit the given message by copying it to the target buffer
1548 * "buf". "buf" will be NULL and "size" zero if the socket was closed
1549 * for writing in the meantime. In that case, do nothing
1550 * (the disconnect or shutdown handler will take care of the rest).
1551 * If we were able to transmit messages and there are still more
1552 * pending, ask core again for further calls to this function.
1554 * @param cls closure, pointer to the 'struct ClientList*'
1555 * @param size number of bytes available in buf
1556 * @param buf where the callee should write the message
1557 * @return number of bytes written to buf
1560 transmit_to_client (void *cls,
1561 size_t size, void *buf)
1563 struct ClientList *cl = cls;
1565 struct ClientResponseMessage *creply;
1572 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1573 "Not sending reply, client communication problem.\n");
1578 while ( (NULL != (creply = cl->res_head) ) &&
1579 (creply->msize <= size) )
1581 memcpy (&cbuf[msize], &creply[1], creply->msize);
1582 msize += creply->msize;
1583 size -= creply->msize;
1584 GNUNET_CONTAINER_DLL_remove (cl->res_head,
1587 GNUNET_free (creply);
1590 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
1592 GNUNET_TIME_UNIT_FOREVER_REL,
1593 &transmit_to_client,
1596 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1597 "Transmitted %u bytes to client\n",
1598 (unsigned int) msize);
1605 * Closure for "process_reply" function.
1607 struct ProcessReplyClosure
1610 * The data for the reply.
1614 // FIXME: add 'struct ConnectedPeer' to track 'last_xxx_replies' here!
1617 * When the reply expires.
1619 struct GNUNET_TIME_Absolute expiration;
1627 * Namespace that this reply belongs to
1628 * (if it is of type SBLOCK).
1630 GNUNET_HashCode namespace;
1633 * Type of the block.
1638 * How much was this reply worth to us?
1645 * We have received a reply; handle it!
1647 * @param cls response (struct ProcessReplyClosure)
1648 * @param key our query
1649 * @param value value in the hash map (info about the query)
1650 * @return GNUNET_YES (we should continue to iterate)
1653 process_reply (void *cls,
1654 const GNUNET_HashCode * key,
1657 struct ProcessReplyClosure *prq = cls;
1658 struct PendingRequest *pr = value;
1659 struct PendingMessage *reply;
1660 struct ClientResponseMessage *creply;
1661 struct ClientList *cl;
1662 struct PutMessage *pm;
1663 struct ConnectedPeer *cp;
1664 GNUNET_HashCode chash;
1665 GNUNET_HashCode mhash;
1670 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1671 "Matched result for query `%s' with pending request\n",
1674 GNUNET_CRYPTO_hash (prq->data,
1679 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1680 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1681 /* only possible reply, stop requesting! */
1682 while (NULL != pr->pending_head)
1683 destroy_pending_message_list_entry (pr->pending_head);
1684 GNUNET_break (GNUNET_YES ==
1685 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
1689 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1690 if (0 != memcmp (pr->namespace,
1692 sizeof (GNUNET_HashCode)))
1693 return GNUNET_YES; /* wrong namespace */
1694 /* then: fall-through! */
1695 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1698 mingle_hash (&chash, pr->mingle, &mhash);
1699 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
1701 return GNUNET_YES; /* duplicate */
1702 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
1705 if (pr->client_request_list != NULL)
1707 if (pr->replies_seen_size == pr->replies_seen_off)
1709 GNUNET_array_grow (pr->replies_seen,
1710 pr->replies_seen_size,
1711 pr->replies_seen_size * 2 + 4);
1712 // FIXME: recalculate BF!
1714 pr->replies_seen[pr->replies_seen_off++] = chash;
1717 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
1718 // FIXME: any checks against duplicates for SKBlocks?
1724 prio = pr->priority;
1725 prq->priority += pr->remaining_priority;
1726 pr->remaining_priority = 0;
1727 if (pr->client_request_list != NULL)
1730 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1731 "Transmitting result for query `%s' to local client\n",
1734 cl = pr->client_request_list->client_list;
1735 msize = sizeof (struct PutMessage) + prq->size;
1736 creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
1737 creply->msize = msize;
1738 creply->client_list = cl;
1739 GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
1743 pm = (struct PutMessage*) &creply[1];
1744 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
1745 pm->header.size = htons (msize);
1746 pm->type = htonl (prq->type);
1747 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
1748 memcpy (&pm[1], prq->data, prq->size);
1750 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
1752 GNUNET_TIME_UNIT_FOREVER_REL,
1753 &transmit_to_client,
1755 GNUNET_break (cl->th != NULL);
1759 cp = pr->pht_entry->cp;
1761 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1762 "Transmitting result for query `%s' to other peer (PID=%u)\n",
1764 (unsigned int) cp->pid);
1766 msize = sizeof (struct PutMessage) + prq->size;
1767 reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
1768 reply->cont = &transmit_reply_continuation;
1769 reply->cont_cls = pr;
1770 reply->msize = msize;
1771 reply->priority = (uint32_t) -1; /* send replies first! */
1772 pm = (struct PutMessage*) &reply[1];
1773 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
1774 pm->header.size = htons (msize);
1775 pm->type = htonl (prq->type);
1776 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
1777 memcpy (&pm[1], prq->data, prq->size);
1778 add_to_pending_messages_for_peer (cp, reply, pr);
1782 // FIXME: implement hot-path routing statistics keeping!
1788 * Handle P2P "PUT" message.
1790 * @param cls closure, always NULL
1791 * @param other the other peer involved (sender or receiver, NULL
1792 * for loopback messages where we are both sender and receiver)
1793 * @param message the actual message
1794 * @param latency reported latency of the connection with 'other'
1795 * @param distance reported distance (DV) to 'other'
1796 * @return GNUNET_OK to keep the connection open,
1797 * GNUNET_SYSERR to close it (signal serious error)
1800 handle_p2p_put (void *cls,
1801 const struct GNUNET_PeerIdentity *other,
1802 const struct GNUNET_MessageHeader *message,
1803 struct GNUNET_TIME_Relative latency,
1806 const struct PutMessage *put;
1810 struct GNUNET_TIME_Absolute expiration;
1811 GNUNET_HashCode query;
1812 struct ProcessReplyClosure prq;
1814 msize = ntohs (message->size);
1815 if (msize < sizeof (struct PutMessage))
1818 return GNUNET_SYSERR;
1820 put = (const struct PutMessage*) message;
1821 dsize = msize - sizeof (struct PutMessage);
1822 type = ntohl (put->type);
1823 expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
1825 /* first, validate! */
1828 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1829 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1830 GNUNET_CRYPTO_hash (&put[1], dsize, &query);
1832 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1834 check_kblock ((const struct KBlock*) &put[1],
1837 return GNUNET_SYSERR;
1839 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1841 check_sblock ((const struct SBlock*) &put[1],
1845 return GNUNET_SYSERR;
1847 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
1848 // FIXME -- validate SKBLOCK!
1852 /* unknown block type */
1853 GNUNET_break_op (0);
1854 return GNUNET_SYSERR;
1858 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1859 "Received result for query `%s' from peer `%4s'\n",
1860 GNUNET_h2s (&query),
1861 GNUNET_i2s (other));
1863 /* now, lookup 'query' */
1864 prq.data = (const void*) &put[1];
1867 prq.expiration = expiration;
1869 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
1873 // FIXME: if migration is on and load is low,
1874 // queue to store data in datastore;
1875 // use "prq.priority" for that!
1880 /* **************************** P2P GET Handling ************************ */
1884 * We're processing (local) results for a search request
1885 * from another peer. Pass applicable results to the
1886 * peer and if we are done either clean up (operation
1887 * complete) or forward to other peers (more results possible).
1889 * @param cls our closure (struct LocalGetContext)
1890 * @param key key for the content
1891 * @param size number of bytes in data
1892 * @param data content stored
1893 * @param type type of the content
1894 * @param priority priority of the content
1895 * @param anonymity anonymity-level for the content
1896 * @param expiration expiration time for the content
1897 * @param uid unique identifier for the datum;
1898 * maybe 0 if no unique identifier is available
1901 process_local_reply (void *cls,
1902 const GNUNET_HashCode * key,
1908 struct GNUNET_TIME_Absolute
1912 struct PendingRequest *pr = cls;
1913 struct ProcessReplyClosure prq;
1914 GNUNET_HashCode dhash;
1915 GNUNET_HashCode mhash;
1916 GNUNET_HashCode query;
1921 if (pr->client_request_list != NULL)
1922 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
1924 /* no more results */
1925 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1926 pr->task = GNUNET_SCHEDULER_add_now (sched,
1927 &forward_request_task,
1931 if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
1934 GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
1935 anonymity, expiration, uid,
1936 &process_local_reply,
1938 GNUNET_FS_drq_get_next (GNUNET_YES);
1941 /* check for duplicates */
1942 GNUNET_CRYPTO_hash (data, size, &dhash);
1943 mingle_hash (&dhash,
1946 if ( (pr->bf != NULL) &&
1948 GNUNET_CONTAINER_bloomfilter_test (pr->bf,
1952 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1953 "Result from datastore filtered by bloomfilter (duplicate).\n");
1955 GNUNET_FS_drq_get_next (GNUNET_YES);
1959 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1960 "Found result for query `%s' in local datastore\n",
1963 pr->results_found++;
1964 if ( (pr->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
1965 (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
1966 (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) )
1971 pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1975 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
1978 memset (&prq, 0, sizeof (prq));
1980 prq.expiration = expiration;
1982 if ( (type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) &&
1983 (GNUNET_OK != check_sblock ((const struct SBlock*) data,
1989 /* FIXME: consider removing the block? */
1990 GNUNET_FS_drq_get_next (GNUNET_YES);
1994 prq.priority = priority;
1995 process_reply (&prq, key, pr);
1997 if ( (GNUNET_YES == test_load_too_high()) ||
1998 (pr->results_found > 5 + 2 * pr->priority) )
2000 GNUNET_FS_drq_get_next (GNUNET_NO);
2003 GNUNET_FS_drq_get_next (GNUNET_YES);
2008 * The priority level imposes a bound on the maximum
2009 * value for the ttl that can be requested.
2011 * @param ttl_in requested ttl
2012 * @param prio given priority
2013 * @return ttl_in if ttl_in is below the limit,
2014 * otherwise the ttl-limit for the given priority
2017 bound_ttl (int32_t ttl_in, uint32_t prio)
2019 unsigned long long allowed;
2023 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
2024 if (ttl_in > allowed)
2026 if (allowed >= (1 << 30))
2035 * We've received a request with the specified priority. Bound it
2036 * according to how much we trust the given peer.
2038 * @param prio_in requested priority
2039 * @param cp the peer making the request
2040 * @return effective priority
2043 bound_priority (uint32_t prio_in,
2044 struct ConnectedPeer *cp)
2051 * Handle P2P "GET" request.
2053 * @param cls closure, always NULL
2054 * @param other the other peer involved (sender or receiver, NULL
2055 * for loopback messages where we are both sender and receiver)
2056 * @param message the actual message
2057 * @param latency reported latency of the connection with 'other'
2058 * @param distance reported distance (DV) to 'other'
2059 * @return GNUNET_OK to keep the connection open,
2060 * GNUNET_SYSERR to close it (signal serious error)
2063 handle_p2p_get (void *cls,
2064 const struct GNUNET_PeerIdentity *other,
2065 const struct GNUNET_MessageHeader *message,
2066 struct GNUNET_TIME_Relative latency,
2069 struct PendingRequest *pr;
2070 struct PeerRequestEntry *pre;
2071 struct ConnectedPeer *cp;
2072 struct ConnectedPeer *cps;
2073 struct GNUNET_TIME_Relative timeout;
2075 const struct GetMessage *gm;
2077 const GNUNET_HashCode *opt;
2080 uint32_t ttl_decrement;
2084 msize = ntohs(message->size);
2085 if (msize < sizeof (struct GetMessage))
2087 GNUNET_break_op (0);
2088 return GNUNET_SYSERR;
2090 gm = (const struct GetMessage*) message;
2091 bm = ntohl (gm->hash_bitmap);
2099 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
2101 GNUNET_break_op (0);
2102 return GNUNET_SYSERR;
2104 opt = (const GNUNET_HashCode*) &gm[1];
2105 bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
2107 bm = ntohl (gm->hash_bitmap);
2108 if ( (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)) &&
2109 (ntohl (gm->type) == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) )
2111 GNUNET_break_op (0);
2112 return GNUNET_SYSERR;
2115 cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2116 &other->hashPubKey);
2117 GNUNET_assert (NULL != cps);
2118 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
2119 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2125 /* FIXME: try connect? */
2128 /* note that we can really only check load here since otherwise
2129 peers could find out that we are overloaded by not being
2130 disconnected after sending us a malformed query... */
2131 if (GNUNET_YES == test_load_too_high ())
2134 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2135 "Dropping query from `%s', this peer is too busy.\n",
2136 GNUNET_i2s (other));
2142 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2143 "Received request for `%s' of type %u from peer `%4s'\n",
2144 GNUNET_h2s (&gm->query),
2145 (unsigned int) ntohl (gm->type),
2146 GNUNET_i2s (other));
2148 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
2149 (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)?sizeof(GNUNET_HashCode):0);
2150 if ((bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2151 pr->namespace = (GNUNET_HashCode*) &pr[1];
2152 pr->type = ntohl (gm->type);
2153 pr->mingle = gm->filter_mutator;
2154 if (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2155 memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
2156 else if (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)
2158 GNUNET_break_op (0);
2160 return GNUNET_SYSERR;
2162 if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
2163 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
2165 pr->anonymity_level = 1;
2166 pr->priority = bound_priority (ntohl (gm->priority), cps);
2167 pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
2168 pr->query = gm->query;
2169 /* decrement ttl (always) */
2170 ttl_decrement = 2 * TTL_DECREMENT +
2171 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2173 if ( (pr->ttl < 0) &&
2174 (pr->ttl - ttl_decrement > 0) )
2177 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2178 "Dropping query from `%s' due to TTL underflow.\n",
2179 GNUNET_i2s (other));
2181 /* integer underflow => drop (should be very rare)! */
2185 pr->ttl -= ttl_decrement;
2186 pr->start_time = GNUNET_TIME_absolute_get ();
2188 /* get bloom filter */
2191 pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
2194 pr->bf_size = bfsize;
2197 /* FIXME: check somewhere if request already exists, and if so,
2198 recycle old state... */
2199 pre = GNUNET_malloc (sizeof (struct PeerRequestEntry));
2202 GNUNET_CONTAINER_multihashmap_put (query_request_map,
2205 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2207 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
2209 GNUNET_TIME_absolute_get().value + pr->ttl);
2212 /* calculate change in traffic preference */
2213 preference = (double) pr->priority;
2214 if (preference < QUERY_BANDWIDTH_VALUE)
2215 preference = QUERY_BANDWIDTH_VALUE;
2216 cps->inc_preference += preference;
2218 /* process locally */
2220 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2221 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2222 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
2223 (pr->priority + 1));
2224 pr->drq = GNUNET_FS_drq_get (&gm->query,
2226 &process_local_reply,
2231 /* Are multiple results possible? If so, start processing remotely now! */
2234 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2235 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2236 /* only one result, wait for datastore */
2239 pr->task = GNUNET_SCHEDULER_add_now (sched,
2240 &forward_request_task,
2244 /* make sure we don't track too many requests */
2245 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
2247 pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
2248 destroy_pending_request (pr);
2254 /* **************************** CS GET Handling ************************ */
2258 * Handle START_SEARCH-message (search request from client).
2260 * @param cls closure
2261 * @param client identification of the client
2262 * @param message the actual message
2265 handle_start_search (void *cls,
2266 struct GNUNET_SERVER_Client *client,
2267 const struct GNUNET_MessageHeader *message)
2269 static GNUNET_HashCode all_zeros;
2270 const struct SearchMessage *sm;
2271 struct ClientList *cl;
2272 struct ClientRequestList *crl;
2273 struct PendingRequest *pr;
2278 msize = ntohs (message->size);
2279 if ( (msize < sizeof (struct SearchMessage)) ||
2280 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
2283 GNUNET_SERVER_receive_done (client,
2287 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
2288 sm = (const struct SearchMessage*) message;
2291 while ( (cl != NULL) &&
2292 (cl->client != client) )
2296 cl = GNUNET_malloc (sizeof (struct ClientList));
2297 cl->client = client;
2298 GNUNET_SERVER_client_keep (client);
2299 cl->next = client_list;
2302 type = ntohl (sm->type);
2304 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2305 "Received request for `%s' of type %u from local client\n",
2306 GNUNET_h2s (&sm->query),
2307 (unsigned int) type);
2309 /* FIXME: detect duplicate request; if duplicate, simply update (merge)
2310 'pr->replies_seen'! */
2311 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
2312 ((type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)?sizeof(GNUNET_HashCode):0));
2313 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
2314 memset (crl, 0, sizeof (struct ClientRequestList));
2315 crl->client_list = cl;
2316 GNUNET_CONTAINER_DLL_insert (cl->rl_head,
2321 pr->client_request_list = crl;
2322 GNUNET_array_grow (pr->replies_seen,
2323 pr->replies_seen_size,
2325 memcpy (pr->replies_seen,
2327 sc * sizeof (GNUNET_HashCode));
2328 pr->replies_seen_off = sc;
2329 pr->anonymity_level = ntohl (sm->anonymity_level);
2330 pr->mingle = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK,
2332 pr->query = sm->query;
2335 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2336 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2337 if (0 != memcmp (&sm->target,
2339 sizeof (GNUNET_HashCode)))
2340 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
2342 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2343 pr->namespace = (GNUNET_HashCode*) &pr[1];
2344 memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
2349 GNUNET_CONTAINER_multihashmap_put (query_request_map,
2352 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2353 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2354 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* get on-demand blocks too! */
2355 pr->drq = GNUNET_FS_drq_get (&sm->query,
2357 &process_local_reply,
2359 GNUNET_TIME_UNIT_FOREVER_REL,
2364 /* **************************** Startup ************************ */
2368 * List of handlers for P2P messages
2369 * that we care about.
2371 static struct GNUNET_CORE_MessageHandler p2p_handlers[] =
2374 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
2376 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
2382 * List of handlers for the messages understood by this
2385 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2386 {&GNUNET_FS_handle_index_start, NULL,
2387 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
2388 {&GNUNET_FS_handle_index_list_get, NULL,
2389 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
2390 {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
2391 sizeof (struct UnindexMessage) },
2392 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
2399 * Process fs requests.
2401 * @param cls closure
2402 * @param s scheduler to use
2403 * @param server the initialized server
2404 * @param c configuration to use
2407 main_init (struct GNUNET_SCHEDULER_Handle *s,
2408 struct GNUNET_SERVER_Handle *server,
2409 const struct GNUNET_CONFIGURATION_Handle *c)
2413 connected_peers = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2414 query_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2415 peer_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2416 requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2417 core = GNUNET_CORE_connect (sched,
2419 GNUNET_TIME_UNIT_FOREVER_REL,
2423 &peer_connect_handler,
2424 &peer_disconnect_handler,
2430 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2431 _("Failed to connect to `%s' service.\n"),
2433 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
2434 connected_peers = NULL;
2435 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
2436 query_request_map = NULL;
2437 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
2438 requests_by_expiration_heap = NULL;
2439 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
2440 peer_request_map = NULL;
2442 return GNUNET_SYSERR;
2444 GNUNET_SERVER_disconnect_notify (server,
2445 &handle_client_disconnect,
2447 GNUNET_SERVER_add_handlers (server, handlers);
2448 GNUNET_SCHEDULER_add_delayed (sched,
2449 GNUNET_TIME_UNIT_FOREVER_REL,
2457 * Process fs requests.
2459 * @param cls closure
2460 * @param sched scheduler to use
2461 * @param server the initialized server
2462 * @param cfg configuration to use
2466 struct GNUNET_SCHEDULER_Handle *sched,
2467 struct GNUNET_SERVER_Handle *server,
2468 const struct GNUNET_CONFIGURATION_Handle *cfg)
2470 if ( (GNUNET_OK != GNUNET_FS_drq_init (sched, cfg)) ||
2471 (GNUNET_OK != GNUNET_FS_indexing_init (sched, cfg)) ||
2472 (GNUNET_OK != main_init (sched, server, cfg)) )
2474 GNUNET_SCHEDULER_shutdown (sched);
2481 * The main function for the fs service.
2483 * @param argc number of arguments from the command line
2484 * @param argv command line arguments
2485 * @return 0 ok, 1 on error
2488 main (int argc, char *const *argv)
2490 return (GNUNET_OK ==
2491 GNUNET_SERVICE_run (argc,
2494 GNUNET_SERVICE_OPTION_NONE,
2495 &run, NULL)) ? 0 : 1;
2498 /* end of gnunet-service-fs.c */