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)
39 #include "gnunet_constants.h"
40 #include "gnunet_core_service.h"
41 #include "gnunet_datastore_service.h"
42 #include "gnunet_peer_lib.h"
43 #include "gnunet_protocols.h"
44 #include "gnunet_signatures.h"
45 #include "gnunet_util_lib.h"
46 #include "gnunet-service-fs_drq.h"
47 #include "gnunet-service-fs_indexing.h"
51 * Maximum number of outgoing messages we queue per peer.
52 * FIXME: set to a tiny value for testing; make configurable.
54 #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 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
934 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
935 connected_peers = NULL;
936 while (client_list != NULL)
937 handle_client_disconnect (NULL,
938 client_list->client);
939 GNUNET_break (0 == GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap));
940 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
941 requests_by_expiration_heap = 0;
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;
1248 GNUNET_assert (peer != NULL);
1249 if (amount != DBLOCK_SIZE)
1251 /* FIXME: call stats... */
1252 return; /* this target round failed */
1254 // (3) transmit, update ttl/priority
1255 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1259 /* Peer must have just left */
1262 /* build message and insert message into priority queue */
1263 k = 0; // FIXME: count hash codes!
1264 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
1265 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1266 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1268 gm = (struct GetMessage*) &pm[1];
1269 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
1270 gm->header.size = htons (msize);
1271 gm->type = htonl (pr->type);
1272 pr->remaining_priority /= 2;
1273 gm->priority = htonl (pr->remaining_priority);
1274 gm->ttl = htonl (pr->ttl);
1275 gm->filter_mutator = htonl(pr->mingle); // FIXME: bad endianess conversion?
1276 gm->hash_bitmap = htonl (42); // FIXME!
1277 gm->query = pr->query;
1278 ext = (GNUNET_HashCode*) &gm[1];
1279 // FIXME: setup "ext[0]..[k-1]"
1280 bfdata = (char *) &ext[k];
1282 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
1285 pm->cont = &transmit_query_continuation;
1287 add_to_pending_messages_for_peer (cp, pm, pr);
1293 * Closure used for "target_peer_select_cb".
1295 struct PeerSelectionContext
1298 * The request for which we are selecting
1301 struct PendingRequest *pr;
1304 * Current "prime" target.
1306 struct GNUNET_PeerIdentity target;
1309 * How much do we like this target?
1311 double target_score;
1317 * Function called for each connected peer to determine
1318 * which one(s) would make good targets for forwarding.
1320 * @param cls closure (struct PeerSelectionContext)
1321 * @param key current key code (peer identity)
1322 * @param value value in the hash map (struct ConnectedPeer)
1323 * @return GNUNET_YES if we should continue to
1328 target_peer_select_cb (void *cls,
1329 const GNUNET_HashCode * key,
1332 struct PeerSelectionContext *psc = cls;
1333 struct ConnectedPeer *cp = value;
1334 struct PendingRequest *pr = psc->pr;
1338 /* 1) check if we have already (recently) forwarded to this peer */
1339 for (i=0;i<pr->used_pids_off;i++)
1340 if (pr->used_pids[i] == cp->pid)
1341 return GNUNET_YES; /* skip */
1342 // 2) calculate how much we'd like to forward to this peer
1343 score = 42; // FIXME!
1344 // FIXME: also need API to gather data on responsiveness
1345 // of this peer (we have fields for that in 'cp', but
1346 // they are never set!)
1348 /* store best-fit in closure */
1349 if (score > psc->target_score)
1351 psc->target_score = score;
1352 psc->target.hashPubKey = *key;
1359 * We're processing a GET request from another peer and have decided
1360 * to forward it to other peers. This function is called periodically
1361 * and should forward the request to other peers until we have all
1362 * possible replies. If we have transmitted the *only* reply to
1363 * the initiator we should destroy the pending request. If we have
1364 * many replies in the queue to the initiator, we should delay sending
1365 * out more queries until the reply queue has shrunk some.
1367 * @param cls our "struct ProcessGetContext *"
1371 forward_request_task (void *cls,
1372 const struct GNUNET_SCHEDULER_TaskContext *tc)
1374 struct PendingRequest *pr = cls;
1375 struct PeerSelectionContext psc;
1376 struct ConnectedPeer *cp;
1378 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1379 get_processing_delay (),
1380 &forward_request_task,
1382 if (pr->irc != NULL)
1383 return; /* previous request still pending */
1384 /* (1) select target */
1386 psc.target_score = DBL_MIN;
1387 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1388 &target_peer_select_cb,
1390 if (psc.target_score == DBL_MIN)
1391 return; /* nobody selected */
1393 /* (2) reserve reply bandwidth */
1394 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1395 &psc.target.hashPubKey);
1396 pr->irc = GNUNET_CORE_peer_change_preference (sched, cfg,
1398 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1399 (uint32_t) -1 /* no limit */,
1401 (uint64_t) cp->inc_preference,
1402 &target_reservation_cb,
1404 cp->inc_preference = 0.0;
1408 /* **************************** P2P PUT Handling ************************ */
1412 * Function called after we either failed or succeeded
1413 * at transmitting a reply to a peer.
1415 * @param cls the requests "struct PendingRequest*"
1416 * @param pid ID of receiving peer, 0 on transmission error
1419 transmit_reply_continuation (void *cls,
1420 GNUNET_PEER_Id tpid)
1422 struct PendingRequest *pr = cls;
1426 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1427 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1428 /* only one reply expected, done with the request! */
1429 destroy_pending_request (pr);
1431 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1432 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1442 * Check if the given KBlock is well-formed.
1444 * @param kb the kblock data (or at least "dsize" bytes claiming to be one)
1445 * @param dsize size of "kb" in bytes; check for < sizeof(struct KBlock)!
1446 * @param query where to store the query that this block answers
1447 * @return GNUNET_OK if this is actually a well-formed KBlock
1450 check_kblock (const struct KBlock *kb,
1452 GNUNET_HashCode *query)
1454 if (dsize < sizeof (struct KBlock))
1456 GNUNET_break_op (0);
1457 return GNUNET_SYSERR;
1459 if (dsize - sizeof (struct KBlock) !=
1460 ntohs (kb->purpose.size)
1461 - sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose)
1462 - sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) )
1464 GNUNET_break_op (0);
1465 return GNUNET_SYSERR;
1468 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_KBLOCK,
1473 GNUNET_break_op (0);
1474 return GNUNET_SYSERR;
1477 GNUNET_CRYPTO_hash (&kb->keyspace,
1478 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1485 * Check if the given SBlock is well-formed.
1487 * @param sb the sblock data (or at least "dsize" bytes claiming to be one)
1488 * @param dsize size of "kb" in bytes; check for < sizeof(struct SBlock)!
1489 * @param query where to store the query that this block answers
1490 * @param namespace where to store the namespace that this block belongs to
1491 * @return GNUNET_OK if this is actually a well-formed SBlock
1494 check_sblock (const struct SBlock *sb,
1496 GNUNET_HashCode *query,
1497 GNUNET_HashCode *namespace)
1499 if (dsize < sizeof (struct SBlock))
1501 GNUNET_break_op (0);
1502 return GNUNET_SYSERR;
1505 ntohs (sb->purpose.size) + sizeof (struct GNUNET_CRYPTO_RsaSignature))
1507 GNUNET_break_op (0);
1508 return GNUNET_SYSERR;
1511 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_SBLOCK,
1516 GNUNET_break_op (0);
1517 return GNUNET_SYSERR;
1520 *query = sb->identifier;
1521 if (namespace != NULL)
1522 GNUNET_CRYPTO_hash (&sb->subspace,
1523 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1530 * Transmit the given message by copying it to the target buffer
1531 * "buf". "buf" will be NULL and "size" zero if the socket was closed
1532 * for writing in the meantime. In that case, do nothing
1533 * (the disconnect or shutdown handler will take care of the rest).
1534 * If we were able to transmit messages and there are still more
1535 * pending, ask core again for further calls to this function.
1537 * @param cls closure, pointer to the 'struct ClientList*'
1538 * @param size number of bytes available in buf
1539 * @param buf where the callee should write the message
1540 * @return number of bytes written to buf
1543 transmit_to_client (void *cls,
1544 size_t size, void *buf)
1546 struct ClientList *cl = cls;
1548 struct ClientResponseMessage *creply;
1555 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1556 "Not sending reply, client communication problem.\n");
1561 while ( (NULL != (creply = cl->res_head) ) &&
1562 (creply->msize <= size) )
1564 memcpy (&cbuf[msize], &creply[1], creply->msize);
1565 msize += creply->msize;
1566 size -= creply->msize;
1567 GNUNET_CONTAINER_DLL_remove (cl->res_head,
1570 GNUNET_free (creply);
1573 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
1575 GNUNET_TIME_UNIT_FOREVER_REL,
1576 &transmit_to_client,
1583 * Closure for "process_reply" function.
1585 struct ProcessReplyClosure
1588 * The data for the reply.
1592 // FIXME: add 'struct ConnectedPeer' to track 'last_xxx_replies' here!
1595 * When the reply expires.
1597 struct GNUNET_TIME_Absolute expiration;
1605 * Namespace that this reply belongs to
1606 * (if it is of type SBLOCK).
1608 GNUNET_HashCode namespace;
1611 * Type of the block.
1616 * How much was this reply worth to us?
1623 * We have received a reply; handle it!
1625 * @param cls response (struct ProcessReplyClosure)
1626 * @param key our query
1627 * @param value value in the hash map (info about the query)
1628 * @return GNUNET_YES (we should continue to iterate)
1631 process_reply (void *cls,
1632 const GNUNET_HashCode * key,
1635 struct ProcessReplyClosure *prq = cls;
1636 struct PendingRequest *pr = value;
1637 struct PendingMessage *reply;
1638 struct ClientResponseMessage *creply;
1639 struct ClientList *cl;
1640 struct PutMessage *pm;
1641 struct ContentMessage *cm;
1642 struct ConnectedPeer *cp;
1643 GNUNET_HashCode chash;
1644 GNUNET_HashCode mhash;
1649 GNUNET_CRYPTO_hash (prq->data,
1654 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1655 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1656 /* only possible reply, stop requesting! */
1657 while (NULL != pr->pending_head)
1658 destroy_pending_message_list_entry (pr->pending_head);
1659 GNUNET_break (GNUNET_YES ==
1660 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
1664 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1665 if (0 != memcmp (pr->namespace,
1667 sizeof (GNUNET_HashCode)))
1668 return GNUNET_YES; /* wrong namespace */
1669 /* then: fall-through! */
1670 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1673 mingle_hash (&chash, pr->mingle, &mhash);
1674 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
1676 return GNUNET_YES; /* duplicate */
1677 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
1680 if (pr->client_request_list != NULL)
1682 cl = pr->client_request_list->client_list;
1683 if (pr->replies_seen_size == pr->replies_seen_off)
1685 GNUNET_array_grow (pr->replies_seen,
1686 pr->replies_seen_size,
1687 pr->replies_seen_size * 2 + 4);
1688 // FIXME: recalculate BF!
1690 pr->replies_seen[pr->replies_seen_off++] = chash;
1693 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
1694 // FIXME: any checks against duplicates for SKBlocks?
1700 prio = pr->priority;
1701 prq->priority += pr->remaining_priority;
1702 pr->remaining_priority = 0;
1703 if (pr->client_request_list != NULL)
1705 msize = sizeof (struct PutMessage) + prq->size;
1706 creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
1707 creply->msize = msize;
1708 creply->client_list = cl;
1709 GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
1713 pm = (struct PutMessage*) &creply[1];
1714 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
1715 pm->header.size = htons (msize);
1716 pm->type = htonl (prq->type);
1717 pm->expiration = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining (prq->expiration));
1718 memcpy (&creply[1], prq->data, prq->size);
1720 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
1722 GNUNET_TIME_UNIT_FOREVER_REL,
1723 &transmit_to_client,
1725 GNUNET_break (cl->th != NULL);
1729 cp = pr->pht_entry->cp;
1730 msize = sizeof (struct ContentMessage) + prq->size;
1731 reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
1732 reply->cont = &transmit_reply_continuation;
1733 reply->cont_cls = pr;
1734 reply->msize = msize;
1735 reply->priority = (uint32_t) -1; /* send replies first! */
1736 cm = (struct ContentMessage*) &reply[1];
1737 cm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_CONTENT);
1738 cm->header.size = htons (msize);
1739 cm->type = htonl (prq->type);
1740 cm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
1741 memcpy (&reply[1], prq->data, prq->size);
1742 add_to_pending_messages_for_peer (cp, reply, pr);
1746 // FIXME: implement hot-path routing statistics keeping!
1752 * Handle P2P "PUT" message.
1754 * @param cls closure, always NULL
1755 * @param other the other peer involved (sender or receiver, NULL
1756 * for loopback messages where we are both sender and receiver)
1757 * @param message the actual message
1758 * @param latency reported latency of the connection with 'other'
1759 * @param distance reported distance (DV) to 'other'
1760 * @return GNUNET_OK to keep the connection open,
1761 * GNUNET_SYSERR to close it (signal serious error)
1764 handle_p2p_put (void *cls,
1765 const struct GNUNET_PeerIdentity *other,
1766 const struct GNUNET_MessageHeader *message,
1767 struct GNUNET_TIME_Relative latency,
1770 const struct PutMessage *put;
1774 struct GNUNET_TIME_Absolute expiration;
1775 GNUNET_HashCode query;
1776 struct ProcessReplyClosure prq;
1778 msize = ntohs (message->size);
1779 if (msize < sizeof (struct PutMessage))
1782 return GNUNET_SYSERR;
1784 put = (const struct PutMessage*) message;
1785 dsize = msize - sizeof (struct PutMessage);
1786 type = ntohl (put->type);
1787 expiration = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (put->expiration));
1789 /* first, validate! */
1792 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1793 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1794 GNUNET_CRYPTO_hash (&put[1], dsize, &query);
1796 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1798 check_kblock ((const struct KBlock*) &put[1],
1801 return GNUNET_SYSERR;
1803 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1805 check_sblock ((const struct SBlock*) &put[1],
1809 return GNUNET_SYSERR;
1811 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
1812 // FIXME -- validate SKBLOCK!
1816 /* unknown block type */
1817 GNUNET_break_op (0);
1818 return GNUNET_SYSERR;
1821 /* now, lookup 'query' */
1822 prq.data = (const void*) &put[1];
1825 prq.expiration = expiration;
1827 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
1831 // FIXME: if migration is on and load is low,
1832 // queue to store data in datastore;
1833 // use "prq.priority" for that!
1838 /* **************************** P2P GET Handling ************************ */
1842 * We're processing (local) results for a search request
1843 * from another peer. Pass applicable results to the
1844 * peer and if we are done either clean up (operation
1845 * complete) or forward to other peers (more results possible).
1847 * @param cls our closure (struct LocalGetContext)
1848 * @param key key for the content
1849 * @param size number of bytes in data
1850 * @param data content stored
1851 * @param type type of the content
1852 * @param priority priority of the content
1853 * @param anonymity anonymity-level for the content
1854 * @param expiration expiration time for the content
1855 * @param uid unique identifier for the datum;
1856 * maybe 0 if no unique identifier is available
1859 process_local_reply (void *cls,
1860 const GNUNET_HashCode * key,
1866 struct GNUNET_TIME_Absolute
1870 struct PendingRequest *pr = cls;
1871 struct ProcessReplyClosure prq;
1872 GNUNET_HashCode dhash;
1873 GNUNET_HashCode mhash;
1874 GNUNET_HashCode query;
1879 /* no more results */
1880 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1881 pr->task = GNUNET_SCHEDULER_add_now (sched,
1882 &forward_request_task,
1886 if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
1889 GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
1890 anonymity, expiration, uid,
1891 &process_local_reply,
1893 GNUNET_FS_drq_get_next (GNUNET_YES);
1896 /* check for duplicates */
1897 GNUNET_CRYPTO_hash (data, size, &dhash);
1898 mingle_hash (&dhash,
1901 if ( (pr->bf != NULL) &&
1903 GNUNET_CONTAINER_bloomfilter_test (pr->bf,
1907 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1908 "Result from datastore filtered by bloomfilter.\n");
1910 GNUNET_FS_drq_get_next (GNUNET_YES);
1913 pr->results_found++;
1914 if ( (pr->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
1915 (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
1916 (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) )
1921 pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1925 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
1928 memset (&prq, 0, sizeof (prq));
1930 prq.expiration = expiration;
1932 if ( (type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) &&
1933 (GNUNET_OK != check_sblock ((const struct SBlock*) data,
1939 /* FIXME: consider removing the block? */
1940 GNUNET_FS_drq_get_next (GNUNET_YES);
1944 prq.priority = priority;
1945 process_reply (&prq, key, pr);
1947 if ( (GNUNET_YES == test_load_too_high()) ||
1948 (pr->results_found > 5 + 2 * pr->priority) )
1950 GNUNET_FS_drq_get_next (GNUNET_NO);
1953 GNUNET_FS_drq_get_next (GNUNET_YES);
1958 * The priority level imposes a bound on the maximum
1959 * value for the ttl that can be requested.
1961 * @param ttl_in requested ttl
1962 * @param prio given priority
1963 * @return ttl_in if ttl_in is below the limit,
1964 * otherwise the ttl-limit for the given priority
1967 bound_ttl (int32_t ttl_in, uint32_t prio)
1969 unsigned long long allowed;
1973 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
1974 if (ttl_in > allowed)
1976 if (allowed >= (1 << 30))
1985 * We've received a request with the specified priority. Bound it
1986 * according to how much we trust the given peer.
1988 * @param prio_in requested priority
1989 * @param cp the peer making the request
1990 * @return effective priority
1993 bound_priority (uint32_t prio_in,
1994 struct ConnectedPeer *cp)
2001 * Handle P2P "GET" request.
2003 * @param cls closure, always NULL
2004 * @param other the other peer involved (sender or receiver, NULL
2005 * for loopback messages where we are both sender and receiver)
2006 * @param message the actual message
2007 * @param latency reported latency of the connection with 'other'
2008 * @param distance reported distance (DV) to 'other'
2009 * @return GNUNET_OK to keep the connection open,
2010 * GNUNET_SYSERR to close it (signal serious error)
2013 handle_p2p_get (void *cls,
2014 const struct GNUNET_PeerIdentity *other,
2015 const struct GNUNET_MessageHeader *message,
2016 struct GNUNET_TIME_Relative latency,
2019 struct PendingRequest *pr;
2020 struct PeerRequestEntry *pre;
2021 struct ConnectedPeer *cp;
2022 struct ConnectedPeer *cps;
2023 struct GNUNET_TIME_Relative timeout;
2025 const struct GetMessage *gm;
2027 const GNUNET_HashCode *opt;
2030 uint32_t ttl_decrement;
2034 msize = ntohs(message->size);
2035 if (msize < sizeof (struct GetMessage))
2037 GNUNET_break_op (0);
2038 return GNUNET_SYSERR;
2040 gm = (const struct GetMessage*) message;
2041 bm = ntohl (gm->hash_bitmap);
2049 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
2051 GNUNET_break_op (0);
2052 return GNUNET_SYSERR;
2054 opt = (const GNUNET_HashCode*) &gm[1];
2055 bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
2057 bm = ntohl (gm->hash_bitmap);
2058 if ( (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)) &&
2059 (ntohl (gm->type) == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) )
2061 GNUNET_break_op (0);
2062 return GNUNET_SYSERR;
2065 cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2066 &other->hashPubKey);
2067 GNUNET_assert (NULL != cps);
2068 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
2069 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2075 /* FIXME: try connect? */
2078 /* note that we can really only check load here since otherwise
2079 peers could find out that we are overloaded by not being
2080 disconnected after sending us a malformed query... */
2081 if (GNUNET_YES == test_load_too_high ())
2084 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2085 "Dropping query from `%s', this peer is too busy.\n",
2086 GNUNET_i2s (other));
2091 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
2092 (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)?sizeof(GNUNET_HashCode):0);
2093 if ((bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2094 pr->namespace = (GNUNET_HashCode*) &pr[1];
2095 pr->type = ntohl (gm->type);
2096 pr->mingle = gm->filter_mutator;
2097 if (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2098 memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
2099 else if (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)
2101 GNUNET_break_op (0);
2103 return GNUNET_SYSERR;
2105 if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
2106 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
2108 pr->anonymity_level = 1;
2109 pr->priority = bound_priority (ntohl (gm->priority), cps);
2110 pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
2111 pr->query = gm->query;
2112 /* decrement ttl (always) */
2113 ttl_decrement = 2 * TTL_DECREMENT +
2114 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2116 if ( (pr->ttl < 0) &&
2117 (pr->ttl - ttl_decrement > 0) )
2120 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2121 "Dropping query from `%s' due to TTL underflow.\n",
2122 GNUNET_i2s (other));
2124 /* integer underflow => drop (should be very rare)! */
2128 pr->ttl -= ttl_decrement;
2129 pr->start_time = GNUNET_TIME_absolute_get ();
2131 /* get bloom filter */
2134 pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
2137 pr->bf_size = bfsize;
2140 /* FIXME: check somewhere if request already exists, and if so,
2141 recycle old state... */
2142 pre = GNUNET_malloc (sizeof (struct PeerRequestEntry));
2145 GNUNET_CONTAINER_multihashmap_put (query_request_map,
2148 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2150 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
2152 GNUNET_TIME_absolute_get().value + pr->ttl);
2155 /* calculate change in traffic preference */
2156 preference = (double) pr->priority;
2157 if (preference < QUERY_BANDWIDTH_VALUE)
2158 preference = QUERY_BANDWIDTH_VALUE;
2159 cps->inc_preference += preference;
2161 /* process locally */
2163 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2164 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2165 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
2166 (pr->priority + 1));
2167 pr->drq = GNUNET_FS_drq_get (&gm->query,
2169 &process_local_reply,
2174 /* Are multiple results possible? If so, start processing remotely now! */
2177 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2178 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2179 /* only one result, wait for datastore */
2182 pr->task = GNUNET_SCHEDULER_add_now (sched,
2183 &forward_request_task,
2187 /* make sure we don't track too many requests */
2188 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
2190 pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
2191 destroy_pending_request (pr);
2197 /* **************************** CS GET Handling ************************ */
2201 * Handle START_SEARCH-message (search request from client).
2203 * @param cls closure
2204 * @param client identification of the client
2205 * @param message the actual message
2208 handle_start_search (void *cls,
2209 struct GNUNET_SERVER_Client *client,
2210 const struct GNUNET_MessageHeader *message)
2212 static GNUNET_HashCode all_zeros;
2213 const struct SearchMessage *sm;
2214 struct ClientList *cl;
2215 struct ClientRequestList *crl;
2216 struct PendingRequest *pr;
2221 msize = ntohs (message->size);
2222 if ( (msize < sizeof (struct SearchMessage)) ||
2223 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
2226 GNUNET_SERVER_receive_done (client,
2230 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
2231 sm = (const struct SearchMessage*) message;
2234 while ( (cl != NULL) &&
2235 (cl->client != client) )
2239 cl = GNUNET_malloc (sizeof (struct ClientList));
2240 cl->client = client;
2241 GNUNET_SERVER_client_keep (client);
2242 cl->next = client_list;
2245 type = ntohl (sm->type);
2247 /* FIXME: detect duplicate request; if duplicate, simply update (merge)
2248 'pr->replies_seen'! */
2249 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
2250 (type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)?sizeof(GNUNET_HashCode):0);
2251 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
2252 crl->client_list = cl;
2253 GNUNET_CONTAINER_DLL_insert (cl->rl_head,
2258 pr->client_request_list = crl;
2259 GNUNET_array_grow (pr->replies_seen,
2260 pr->replies_seen_size,
2262 memcpy (pr->replies_seen,
2264 sc * sizeof (GNUNET_HashCode));
2265 pr->replies_seen_off = sc;
2266 pr->anonymity_level = ntohl (sm->anonymity_level);
2267 pr->mingle = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK,
2269 pr->query = sm->query;
2272 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2273 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2274 if (0 != memcmp (&sm->target,
2276 sizeof (GNUNET_HashCode)))
2277 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
2279 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2280 pr->namespace = (GNUNET_HashCode*) &pr[1];
2281 memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
2286 pr->drq = GNUNET_FS_drq_get (&sm->query,
2288 &process_local_reply,
2290 GNUNET_TIME_UNIT_FOREVER_REL,
2295 /* **************************** Startup ************************ */
2299 * List of handlers for P2P messages
2300 * that we care about.
2302 static struct GNUNET_CORE_MessageHandler p2p_handlers[] =
2305 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
2307 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
2313 * List of handlers for the messages understood by this
2316 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2317 {&GNUNET_FS_handle_index_start, NULL,
2318 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
2319 {&GNUNET_FS_handle_index_list_get, NULL,
2320 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
2321 {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
2322 sizeof (struct UnindexMessage) },
2323 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
2330 * Process fs requests.
2332 * @param cls closure
2333 * @param s scheduler to use
2334 * @param server the initialized server
2335 * @param c configuration to use
2338 main_init (struct GNUNET_SCHEDULER_Handle *s,
2339 struct GNUNET_SERVER_Handle *server,
2340 const struct GNUNET_CONFIGURATION_Handle *c)
2344 core = GNUNET_CORE_connect (sched,
2346 GNUNET_TIME_UNIT_FOREVER_REL,
2350 &peer_connect_handler,
2351 &peer_disconnect_handler,
2357 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2358 _("Failed to connect to `%s' service.\n"),
2360 return GNUNET_SYSERR;
2362 query_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2363 peer_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2364 requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2365 GNUNET_SERVER_disconnect_notify (server,
2366 &handle_client_disconnect,
2368 GNUNET_SERVER_add_handlers (server, handlers);
2369 GNUNET_SCHEDULER_add_delayed (sched,
2370 GNUNET_TIME_UNIT_FOREVER_REL,
2378 * Process fs requests.
2380 * @param cls closure
2381 * @param sched scheduler to use
2382 * @param server the initialized server
2383 * @param cfg configuration to use
2387 struct GNUNET_SCHEDULER_Handle *sched,
2388 struct GNUNET_SERVER_Handle *server,
2389 const struct GNUNET_CONFIGURATION_Handle *cfg)
2391 if ( (GNUNET_OK != GNUNET_FS_drq_init (sched, cfg)) ||
2392 (GNUNET_OK != GNUNET_FS_indexing_init (sched, cfg)) ||
2393 (GNUNET_OK != main_init (sched, server, cfg)) )
2395 GNUNET_SCHEDULER_shutdown (sched);
2402 * The main function for the fs service.
2404 * @param argc number of arguments from the command line
2405 * @param argv command line arguments
2406 * @return 0 ok, 1 on error
2409 main (int argc, char *const *argv)
2411 return (GNUNET_OK ==
2412 GNUNET_SERVICE_run (argc,
2415 GNUNET_SERVICE_OPTION_NONE,
2416 &run, NULL)) ? 0 : 1;
2419 /* end of gnunet-service-fs.c */