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"
50 * Maximum number of outgoing messages we queue per peer.
51 * FIXME: set to a tiny value for testing; make configurable.
53 #define MAX_QUEUE_PER_PEER 2
58 * Maximum number of requests (from other peers) that we're
59 * willing to have pending at any given point in time.
60 * FIXME: set from configuration (and 32 is a tiny value for testing only).
62 static uint64_t max_pending_requests = 32;
66 * Information we keep for each pending reply. The
67 * actual message follows at the end of this struct.
69 struct PendingMessage;
73 * Function called upon completion of a transmission.
76 * @param pid ID of receiving peer, 0 on transmission error
78 typedef void (*TransmissionContinuation)(void * cls,
83 * Information we keep for each pending reply. The
84 * actual message follows at the end of this struct.
89 * This is a doubly-linked list of messages to the same peer.
91 struct PendingMessage *next;
94 * This is a doubly-linked list of messages to the same peer.
96 struct PendingMessage *prev;
99 * Entry in pending message list for this pending message.
101 struct PendingMessageList *pml;
104 * Function to call immediately once we have transmitted this
107 TransmissionContinuation cont;
115 * Size of the reply; actual reply message follows
116 * at the end of this struct.
121 * How important is this message for us?
129 * Information about a peer that we are connected to.
130 * We track data that is useful for determining which
131 * peers should receive our requests. We also keep
132 * a list of messages to transmit to this peer.
138 * List of the last clients for which this peer successfully
141 struct GNUNET_SERVER_Client *last_client_replies[CS2P_SUCCESS_LIST_SIZE];
144 * List of the last PIDs for which
145 * this peer successfully answered a query;
146 * We use 0 to indicate no successful reply.
148 GNUNET_PEER_Id last_p2p_replies[P2P_SUCCESS_LIST_SIZE];
151 * Average delay between sending the peer a request and
152 * getting a reply (only calculated over the requests for
153 * which we actually got a reply). Calculated
154 * as a moving average: new_delay = ((n-1)*last_delay+curr_delay) / n
156 struct GNUNET_TIME_Relative avg_delay;
159 * Handle for an active request for transmission to this
162 struct GNUNET_CORE_TransmitHandle *cth;
165 * Messages (replies, queries, content migration) we would like to
166 * send to this peer in the near future. Sorted by priority, head.
168 struct PendingMessage *pending_messages_head;
171 * Messages (replies, queries, content migration) we would like to
172 * send to this peer in the near future. Sorted by priority, tail.
174 struct PendingMessage *pending_messages_tail;
177 * Average priority of successful replies. Calculated
178 * as a moving average: new_avg = ((n-1)*last_avg+curr_prio) / n
183 * Increase in traffic preference still to be submitted
184 * to the core service for this peer. FIXME: double or 'uint64_t'?
186 double inc_preference;
189 * The peer's identity.
194 * Size of the linked list of 'pending_messages'.
196 unsigned int pending_requests;
199 * Which offset in "last_p2p_replies" will be updated next?
200 * (we go round-robin).
202 unsigned int last_p2p_replies_woff;
205 * Which offset in "last_client_replies" will be updated next?
206 * (we go round-robin).
208 unsigned int last_client_replies_woff;
214 * Information we keep for each pending request. We should try to
215 * keep this struct as small as possible since its memory consumption
216 * is key to how many requests we can have pending at once.
218 struct PendingRequest;
222 * Doubly-linked list of requests we are performing
223 * on behalf of the same client.
225 struct ClientRequestList
229 * This is a doubly-linked list.
231 struct ClientRequestList *next;
234 * This is a doubly-linked list.
236 struct ClientRequestList *prev;
239 * Request this entry represents.
241 struct PendingRequest *req;
244 * Client list this request belongs to.
246 struct ClientList *client_list;
252 * Replies to be transmitted to the client. The actual
253 * response message is allocated after this struct.
255 struct ClientResponseMessage
258 * This is a doubly-linked list.
260 struct ClientResponseMessage *next;
263 * This is a doubly-linked list.
265 struct ClientResponseMessage *prev;
268 * Client list entry this response belongs to.
270 struct ClientList *client_list;
273 * Number of bytes in the response.
280 * Linked list of clients we are performing requests
286 * This is a linked list.
288 struct ClientList *next;
291 * ID of a client making a request, NULL if this entry is for a
294 struct GNUNET_SERVER_Client *client;
297 * Head of list of requests performed on behalf
298 * of this client right now.
300 struct ClientRequestList *rl_head;
303 * Tail of list of requests performed on behalf
304 * of this client right now.
306 struct ClientRequestList *rl_tail;
309 * Head of linked list of responses.
311 struct ClientResponseMessage *res_head;
314 * Tail of linked list of responses.
316 struct ClientResponseMessage *res_tail;
319 * Context for sending replies.
321 struct GNUNET_CONNECTION_TransmitHandle *th;
327 * Hash map entry of requests we are performing
328 * on behalf of the same peer.
330 struct PeerRequestEntry
334 * Request this entry represents.
336 struct PendingRequest *req;
339 * Entry of peer responsible for this entry.
341 struct ConnectedPeer *cp;
347 * Doubly-linked list of messages we are performing
348 * due to a pending request.
350 struct PendingMessageList
354 * This is a doubly-linked list of messages on behalf of the same request.
356 struct PendingMessageList *next;
359 * This is a doubly-linked list of messages on behalf of the same request.
361 struct PendingMessageList *prev;
364 * Message this entry represents.
366 struct PendingMessage *pm;
369 * Request this entry belongs to.
371 struct PendingRequest *req;
374 * Peer this message is targeted for.
376 struct ConnectedPeer *target;
382 * Information we keep for each pending request. We should try to
383 * keep this struct as small as possible since its memory consumption
384 * is key to how many requests we can have pending at once.
386 struct PendingRequest
390 * If this request was made by a client, this is our entry in the
391 * client request list; otherwise NULL.
393 struct ClientRequestList *client_request_list;
396 * If this request was made by a peer, this is our entry in the
397 * per-peer multi-hash map; otherwise NULL.
399 struct PeerRequestEntry *pht_entry;
402 * If this is a namespace query, pointer to the hash of the public
403 * key of the namespace; otherwise NULL. Pointer will be to the
404 * end of this struct (so no need to free it).
406 const GNUNET_HashCode *namespace;
409 * Bloomfilter we use to filter out replies that we don't care about
410 * (anymore). NULL as long as we are interested in all replies.
412 struct GNUNET_CONTAINER_BloomFilter *bf;
415 * Context of our GNUNET_CORE_peer_change_preference call.
417 struct GNUNET_CORE_InformationRequestContext *irc;
420 * Hash code of all replies that we have seen so far (only valid
421 * if client is not NULL since we only track replies like this for
424 GNUNET_HashCode *replies_seen;
427 * Node in the heap representing this entry; NULL
428 * if we have no heap node.
430 struct GNUNET_CONTAINER_HeapNode *hnode;
433 * Head of list of messages being performed on behalf of this
436 struct PendingMessageList *pending_head;
439 * Tail of list of messages being performed on behalf of this
442 struct PendingMessageList *pending_tail;
445 * When did we first see this request (form this peer), or, if our
446 * client is initiating, when did we last initiate a search?
448 struct GNUNET_TIME_Absolute start_time;
451 * The query that this request is for.
453 GNUNET_HashCode query;
456 * The task responsible for transmitting queries
459 GNUNET_SCHEDULER_TaskIdentifier task;
462 * (Interned) Peer identifier that identifies a preferred target
465 GNUNET_PEER_Id target_pid;
468 * (Interned) Peer identifiers of peers that have already
469 * received our query for this content.
471 GNUNET_PEER_Id *used_pids;
474 * Our entry in the DRQ (non-NULL while we wait for our
475 * turn to interact with the local database).
477 struct DatastoreRequestQueue *drq;
480 * Size of the 'bf' (in bytes).
485 * Desired anonymity level; only valid for requests from a local client.
487 uint32_t anonymity_level;
490 * How many entries in "used_pids" are actually valid?
492 unsigned int used_pids_off;
495 * How long is the "used_pids" array?
497 unsigned int used_pids_size;
500 * Number of results found for this request.
502 unsigned int results_found;
505 * How many entries in "replies_seen" are actually valid?
507 unsigned int replies_seen_off;
510 * How long is the "replies_seen" array?
512 unsigned int replies_seen_size;
515 * Priority with which this request was made. If one of our clients
516 * made the request, then this is the current priority that we are
517 * using when initiating the request. This value is used when
518 * we decide to reward other peers with trust for providing a reply.
523 * Priority points left for us to spend when forwarding this request
526 uint32_t remaining_priority;
529 * Number to mingle hashes for bloom-filter
535 * TTL with which we saw this request (or, if we initiated, TTL that
536 * we used for the request).
541 * Type of the content that this request is for.
551 static struct GNUNET_SCHEDULER_Handle *sched;
556 const struct GNUNET_CONFIGURATION_Handle *cfg;
559 * Map of peer identifiers to "struct ConnectedPeer" (for that peer).
561 static struct GNUNET_CONTAINER_MultiHashMap *connected_peers;
564 * Map of peer identifiers to "struct PendingRequest" (for that peer).
566 static struct GNUNET_CONTAINER_MultiHashMap *peer_request_map;
569 * Map of query identifiers to "struct PendingRequest" (for that query).
571 static struct GNUNET_CONTAINER_MultiHashMap *query_request_map;
574 * Heap with the request that will expire next at the top. Contains
575 * pointers of type "struct PendingRequest*"; these will *also* be
576 * aliased from the "requests_by_peer" data structures and the
577 * "requests_by_query" table. Note that requests from our clients
578 * don't expire and are thus NOT in the "requests_by_expiration"
579 * (or the "requests_by_peer" tables).
581 static struct GNUNET_CONTAINER_Heap *requests_by_expiration_heap;
584 * Linked list of clients we are currently processing requests for.
586 struct ClientList *client_list;
589 * Pointer to handle to the core service (points to NULL until we've
592 struct GNUNET_CORE_Handle *core;
595 /* ******************* clean up functions ************************ */
599 * We're done with a particular message list entry.
600 * Free all associated resources.
602 * @param pml entry to destroy
605 destroy_pending_message_list_entry (struct PendingMessageList *pml)
607 GNUNET_CONTAINER_DLL_remove (pml->req->pending_head,
608 pml->req->pending_tail,
610 GNUNET_CONTAINER_DLL_remove (pml->target->pending_messages_head,
611 pml->target->pending_messages_tail,
613 pml->target->pending_requests--;
614 GNUNET_free (pml->pm);
620 * Destroy the given pending message (and call the respective
623 * @param pm message to destroy
624 * @param tpid id of peer that the message was delivered to, or 0 for none
627 destroy_pending_message (struct PendingMessage *pm,
630 struct PendingMessageList *pml = pm->pml;
632 GNUNET_assert (pml->pm == pm);
633 GNUNET_assert ( (tpid == 0) || (tpid == pml->target->pid) );
634 pm->cont (pm->cont_cls, 0);
635 destroy_pending_message_list_entry (pml);
641 * We're done processing a particular request.
642 * Free all associated resources.
644 * @param pr request to destroy
647 destroy_pending_request (struct PendingRequest *pr)
649 struct GNUNET_PeerIdentity pid;
651 if (pr->hnode != NULL)
653 GNUNET_CONTAINER_heap_remove_node (requests_by_expiration_heap,
657 /* might have already been removed from map
658 in 'process_reply' if there was a unique
659 reply; hence ignore the return value here */
660 (void) GNUNET_CONTAINER_multihashmap_remove (query_request_map,
665 GNUNET_FS_drq_get_cancel (pr->drq);
668 if (pr->client_request_list != NULL)
670 GNUNET_CONTAINER_DLL_remove (pr->client_request_list->client_list->rl_head,
671 pr->client_request_list->client_list->rl_tail,
672 pr->client_request_list);
673 GNUNET_free (pr->client_request_list);
674 pr->client_request_list = NULL;
676 if (pr->pht_entry != NULL)
678 GNUNET_PEER_resolve (pr->pht_entry->cp->pid,
680 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
683 GNUNET_free (pr->pht_entry);
684 pr->pht_entry = NULL;
688 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
693 GNUNET_CORE_peer_change_preference_cancel (pr->irc);
696 if (pr->replies_seen != NULL)
698 GNUNET_free (pr->replies_seen);
699 pr->replies_seen = NULL;
701 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
703 GNUNET_SCHEDULER_cancel (sched,
705 pr->task = GNUNET_SCHEDULER_NO_TASK;
707 while (NULL != pr->pending_head)
708 destroy_pending_message_list_entry (pr->pending_head);
709 GNUNET_PEER_change_rc (pr->target_pid, -1);
710 if (pr->used_pids != NULL)
712 GNUNET_PEER_decrement_rcs (pr->used_pids, pr->used_pids_off);
713 GNUNET_free (pr->used_pids);
714 pr->used_pids_off = 0;
715 pr->used_pids_size = 0;
716 pr->used_pids = NULL;
723 * Method called whenever a given peer connects.
725 * @param cls closure, not used
726 * @param peer peer identity this notification is about
727 * @param latency reported latency of the connection with 'other'
728 * @param distance reported distance (DV) to 'other'
731 peer_connect_handler (void *cls,
733 GNUNET_PeerIdentity * peer,
734 struct GNUNET_TIME_Relative latency,
737 struct ConnectedPeer *cp;
739 cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
740 cp->pid = GNUNET_PEER_intern (peer);
741 GNUNET_CONTAINER_multihashmap_put (connected_peers,
744 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
749 * Free (each) request made by the peer.
751 * @param cls closure, points to peer that the request belongs to
752 * @param key current key code
753 * @param value value in the hash map
754 * @return GNUNET_YES (we should continue to iterate)
757 destroy_request (void *cls,
758 const GNUNET_HashCode * key,
761 const struct GNUNET_PeerIdentity * peer = cls;
762 struct PendingRequest *pr = value;
764 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
767 destroy_pending_request (pr);
773 * Method called whenever a peer disconnects.
775 * @param cls closure, not used
776 * @param peer peer identity this notification is about
779 peer_disconnect_handler (void *cls,
781 GNUNET_PeerIdentity * peer)
783 struct ConnectedPeer *cp;
784 struct PendingMessage *pm;
787 GNUNET_CONTAINER_multihashmap_get_multiple (peer_request_map,
791 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
795 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
797 if (NULL != cp->last_client_replies[i])
799 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
800 cp->last_client_replies[i] = NULL;
803 GNUNET_CONTAINER_multihashmap_remove (connected_peers,
806 GNUNET_PEER_change_rc (cp->pid, -1);
807 GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
809 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
810 while (NULL != (pm = cp->pending_messages_head))
811 destroy_pending_message (pm, 0 /* delivery failed */);
812 GNUNET_break (0 == cp->pending_requests);
818 * Iterator over hash map entries that removes all occurences
819 * of the given 'client' from the 'last_client_replies' of the
820 * given connected peer.
822 * @param cls closure, the 'struct GNUNET_SERVER_Client*' to remove
823 * @param key current key code (unused)
824 * @param value value in the hash map (the 'struct ConnectedPeer*' to change)
825 * @return GNUNET_YES (we should continue to iterate)
828 remove_client_from_last_client_replies (void *cls,
829 const GNUNET_HashCode * key,
832 struct GNUNET_SERVER_Client *client = cls;
833 struct ConnectedPeer *cp = value;
836 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
838 if (cp->last_client_replies[i] == client)
840 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
841 cp->last_client_replies[i] = NULL;
849 * A client disconnected. Remove all of its pending queries.
851 * @param cls closure, NULL
852 * @param client identification of the client
855 handle_client_disconnect (void *cls,
856 struct GNUNET_SERVER_Client
859 struct ClientList *pos;
860 struct ClientList *prev;
861 struct ClientRequestList *rcl;
862 struct ClientResponseMessage *creply;
865 return; /* huh? is this allowed? */
868 while ( (NULL != pos) &&
869 (pos->client != client) )
875 return; /* no requests pending for this client */
876 while (NULL != (rcl = pos->rl_head))
877 destroy_pending_request (rcl->req);
879 client_list = pos->next;
881 prev->next = pos->next;
884 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
887 while (NULL != (creply = pos->res_head))
889 GNUNET_CONTAINER_DLL_remove (pos->res_head,
892 GNUNET_free (creply);
894 GNUNET_SERVER_client_drop (pos->client);
896 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
897 &remove_client_from_last_client_replies,
903 * Iterator to free peer entries.
905 * @param cls closure, unused
906 * @param key current key code
907 * @param value value in the hash map (peer entry)
908 * @return GNUNET_YES (we should continue to iterate)
911 clean_peer (void *cls,
912 const GNUNET_HashCode * key,
915 peer_disconnect_handler (NULL, (const struct GNUNET_PeerIdentity*) key);
921 * Task run during shutdown.
927 shutdown_task (void *cls,
928 const struct GNUNET_SCHEDULER_TaskContext *tc)
930 while (client_list != NULL)
931 handle_client_disconnect (NULL,
932 client_list->client);
933 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
936 GNUNET_break (0 == GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap));
937 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
938 requests_by_expiration_heap = 0;
939 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
940 connected_peers = NULL;
941 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (query_request_map));
942 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
943 query_request_map = NULL;
944 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (peer_request_map));
945 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
946 peer_request_map = NULL;
947 GNUNET_assert (NULL != core);
948 GNUNET_CORE_disconnect (core);
955 /* ******************* Utility functions ******************** */
959 * Transmit the given message by copying it to the target buffer
960 * "buf". "buf" will be NULL and "size" zero if the socket was closed
961 * for writing in the meantime. In that case, do nothing
962 * (the disconnect or shutdown handler will take care of the rest).
963 * If we were able to transmit messages and there are still more
964 * pending, ask core again for further calls to this function.
966 * @param cls closure, pointer to the 'struct ConnectedPeer*'
967 * @param size number of bytes available in buf
968 * @param buf where the callee should write the message
969 * @return number of bytes written to buf
972 transmit_to_peer (void *cls,
973 size_t size, void *buf)
975 struct ConnectedPeer *cp = cls;
977 struct GNUNET_PeerIdentity pid;
978 struct PendingMessage *pm;
985 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
986 "Dropping reply, core too busy.\n");
991 while ( (NULL != (pm = cp->pending_messages_head) ) &&
992 (pm->msize <= size) )
994 memcpy (&cbuf[msize], &pm[1], pm->msize);
997 destroy_pending_message (pm, cp->pid);
1001 GNUNET_PEER_resolve (cp->pid,
1003 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1005 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1016 * Add a message to the set of pending messages for the given peer.
1018 * @param cp peer to send message to
1019 * @param pm message to queue
1020 * @param pr request on which behalf this message is being queued
1023 add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
1024 struct PendingMessage *pm,
1025 struct PendingRequest *pr)
1027 struct PendingMessage *pos;
1028 struct PendingMessageList *pml;
1029 struct GNUNET_PeerIdentity pid;
1031 GNUNET_assert (pm->next == NULL);
1032 GNUNET_assert (pm->pml == NULL);
1033 pml = GNUNET_malloc (sizeof (struct PendingMessageList));
1038 GNUNET_CONTAINER_DLL_insert (pr->pending_head,
1041 pos = cp->pending_messages_head;
1042 while ( (pos != NULL) &&
1043 (pm->priority < pos->priority) )
1045 GNUNET_CONTAINER_DLL_insert_after (cp->pending_messages_head,
1046 cp->pending_messages_tail,
1049 cp->pending_requests++;
1050 if (cp->pending_requests > MAX_QUEUE_PER_PEER)
1051 destroy_pending_message (cp->pending_messages_tail, 0);
1052 if (cp->cth == NULL)
1054 /* need to schedule transmission */
1055 GNUNET_PEER_resolve (cp->pid, &pid);
1056 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1057 cp->pending_messages_head->priority,
1058 GNUNET_TIME_UNIT_FOREVER_REL,
1060 cp->pending_messages_head->msize,
1064 if (cp->cth == NULL)
1066 /* FIXME: call stats (rare, bad case) */
1072 * Mingle hash with the mingle_number to produce different bits.
1075 mingle_hash (const GNUNET_HashCode * in,
1076 int32_t mingle_number,
1077 GNUNET_HashCode * hc)
1081 GNUNET_CRYPTO_hash (&mingle_number,
1084 GNUNET_CRYPTO_hash_xor (&m, in, hc);
1089 * Test if the load on this peer is too high
1090 * to even consider processing the query at
1093 * @return GNUNET_YES if the load is too high, GNUNET_NO otherwise
1096 test_load_too_high ()
1098 return GNUNET_NO; // FIXME
1102 /* ******************* Pending Request Refresh Task ******************** */
1106 * Function called after we either failed or succeeded
1107 * at transmitting a query to a peer.
1109 * @param cls the requests "struct PendingRequest*"
1110 * @param pid ID of receiving peer, 0 on transmission error
1113 transmit_query_continuation (void *cls,
1114 GNUNET_PEER_Id tpid)
1116 struct PendingRequest *pr = cls;
1120 GNUNET_PEER_change_rc (tpid, 1);
1121 if (pr->used_pids_off == pr->used_pids_size)
1122 GNUNET_array_grow (pr->used_pids,
1124 pr->used_pids_size * 2 + 2);
1125 pr->used_pids[pr->used_pids_off++] = tpid;
1131 * How many bytes should a bloomfilter be if we have already seen
1132 * entry_count responses? Note that BLOOMFILTER_K gives us the number
1133 * of bits set per entry. Furthermore, we should not re-size the
1134 * filter too often (to keep it cheap).
1136 * Since other peers will also add entries but not resize the filter,
1137 * we should generally pick a slightly larger size than what the
1138 * strict math would suggest.
1140 * @return must be a power of two and smaller or equal to 2^15.
1143 compute_bloomfilter_size (unsigned int entry_count)
1146 unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
1147 uint16_t max = 1 << 15;
1149 if (entry_count > max)
1152 while ((size < max) && (size < ideal))
1161 * Recalculate our bloom filter for filtering replies.
1163 * @param count number of entries we are filtering right now
1164 * @param mingle set to our new mingling value
1165 * @param bf_size set to the size of the bloomfilter
1166 * @param entries the entries to filter
1167 * @return updated bloomfilter, NULL for none
1169 static struct GNUNET_CONTAINER_BloomFilter *
1170 refresh_bloomfilter (unsigned int count,
1173 const GNUNET_HashCode *entries)
1175 struct GNUNET_CONTAINER_BloomFilter *bf;
1178 GNUNET_HashCode mhash;
1182 nsize = compute_bloomfilter_size (count);
1183 *mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
1185 bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1188 for (i=0;i<count;i++)
1190 mingle_hash (&entries[i], *mingle, &mhash);
1191 GNUNET_CONTAINER_bloomfilter_add (bf, &mhash);
1199 * We use a random delay to make the timing of requests less
1200 * predictable. This function returns such a random delay.
1202 * FIXME: make schedule dependent on the specifics of the request?
1203 * Or bandwidth and number of connected peers and load?
1205 * @return random delay to use for some request, between 0 and TTL_DECREMENT ms
1207 static struct GNUNET_TIME_Relative
1208 get_processing_delay ()
1210 return GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1211 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1217 * Function called after we've tried to reserve a certain amount of
1218 * bandwidth for a reply. Check if we succeeded and if so send our
1221 * @param cls the requests "struct PendingRequest*"
1222 * @param peer identifies the peer
1223 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1224 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1225 * @param amount set to the amount that was actually reserved or unreserved
1226 * @param preference current traffic preference for the given peer
1229 target_reservation_cb (void *cls,
1231 GNUNET_PeerIdentity * peer,
1232 unsigned int bpm_in,
1233 unsigned int bpm_out,
1235 uint64_t preference)
1237 struct PendingRequest *pr = cls;
1238 struct ConnectedPeer *cp;
1239 struct PendingMessage *pm;
1240 struct GetMessage *gm;
1241 GNUNET_HashCode *ext;
1248 GNUNET_assert (peer != NULL);
1249 // (3) transmit, update ttl/priority
1250 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1254 /* Peer must have just left */
1257 no_route = GNUNET_NO;
1258 if (amount != DBLOCK_SIZE)
1260 if (pr->pht_entry == NULL)
1261 return; /* this target round failed */
1262 /* FIXME: if we are "quite" busy, we may still want to skip
1263 this round; need more load detection code! */
1264 no_route = GNUNET_YES;
1267 /* build message and insert message into priority queue */
1269 if (pr->namespace != NULL)
1271 if (pr->target_pid != 0)
1273 if (GNUNET_YES == no_route)
1275 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
1276 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1277 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1279 gm = (struct GetMessage*) &pm[1];
1280 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
1281 gm->header.size = htons (msize);
1282 gm->type = htonl (pr->type);
1283 pr->remaining_priority /= 2;
1284 gm->priority = htonl (pr->remaining_priority);
1285 gm->ttl = htonl (pr->ttl);
1286 gm->filter_mutator = htonl(pr->mingle); // FIXME: bad endianess conversion?
1287 gm->hash_bitmap = htonl (42); // FIXME!
1288 gm->query = pr->query;
1289 ext = (GNUNET_HashCode*) &gm[1];
1291 if (pr->namespace != NULL)
1292 memcpy (&ext[k++], pr->namespace, sizeof (GNUNET_HashCode));
1293 if (pr->target_pid != 0)
1294 GNUNET_PEER_resolve (pr->target_pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1295 if (GNUNET_YES == no_route)
1296 GNUNET_PEER_resolve (pr->pht_entry->cp->pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1297 bfdata = (char *) &ext[k];
1299 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
1302 pm->cont = &transmit_query_continuation;
1304 add_to_pending_messages_for_peer (cp, pm, pr);
1309 * Closure used for "target_peer_select_cb".
1311 struct PeerSelectionContext
1314 * The request for which we are selecting
1317 struct PendingRequest *pr;
1320 * Current "prime" target.
1322 struct GNUNET_PeerIdentity target;
1325 * How much do we like this target?
1327 double target_score;
1333 * Function called for each connected peer to determine
1334 * which one(s) would make good targets for forwarding.
1336 * @param cls closure (struct PeerSelectionContext)
1337 * @param key current key code (peer identity)
1338 * @param value value in the hash map (struct ConnectedPeer)
1339 * @return GNUNET_YES if we should continue to
1344 target_peer_select_cb (void *cls,
1345 const GNUNET_HashCode * key,
1348 struct PeerSelectionContext *psc = cls;
1349 struct ConnectedPeer *cp = value;
1350 struct PendingRequest *pr = psc->pr;
1354 /* 1) check if we have already (recently) forwarded to this peer */
1355 for (i=0;i<pr->used_pids_off;i++)
1356 if (pr->used_pids[i] == cp->pid)
1357 return GNUNET_YES; /* skip */
1358 // 2) calculate how much we'd like to forward to this peer
1359 score = 42; // FIXME!
1360 // FIXME: also need API to gather data on responsiveness
1361 // of this peer (we have fields for that in 'cp', but
1362 // they are never set!)
1364 /* store best-fit in closure */
1365 if (score > psc->target_score)
1367 psc->target_score = score;
1368 psc->target.hashPubKey = *key;
1375 * We're processing a GET request from another peer and have decided
1376 * to forward it to other peers. This function is called periodically
1377 * and should forward the request to other peers until we have all
1378 * possible replies. If we have transmitted the *only* reply to
1379 * the initiator we should destroy the pending request. If we have
1380 * many replies in the queue to the initiator, we should delay sending
1381 * out more queries until the reply queue has shrunk some.
1383 * @param cls our "struct ProcessGetContext *"
1387 forward_request_task (void *cls,
1388 const struct GNUNET_SCHEDULER_TaskContext *tc)
1390 struct PendingRequest *pr = cls;
1391 struct PeerSelectionContext psc;
1392 struct ConnectedPeer *cp;
1394 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1395 get_processing_delay (),
1396 &forward_request_task,
1398 if (pr->irc != NULL)
1399 return; /* previous request still pending */
1400 /* (1) select target */
1402 psc.target_score = DBL_MIN;
1403 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1404 &target_peer_select_cb,
1406 if (psc.target_score == DBL_MIN)
1407 return; /* nobody selected */
1409 /* (2) reserve reply bandwidth */
1410 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1411 &psc.target.hashPubKey);
1412 pr->irc = GNUNET_CORE_peer_change_preference (sched, cfg,
1414 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1415 (uint32_t) -1 /* no limit */,
1417 (uint64_t) cp->inc_preference,
1418 &target_reservation_cb,
1420 cp->inc_preference = 0.0;
1424 /* **************************** P2P PUT Handling ************************ */
1428 * Function called after we either failed or succeeded
1429 * at transmitting a reply to a peer.
1431 * @param cls the requests "struct PendingRequest*"
1432 * @param pid ID of receiving peer, 0 on transmission error
1435 transmit_reply_continuation (void *cls,
1436 GNUNET_PEER_Id tpid)
1438 struct PendingRequest *pr = cls;
1442 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1443 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1444 /* only one reply expected, done with the request! */
1445 destroy_pending_request (pr);
1447 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1448 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1458 * Check if the given KBlock is well-formed.
1460 * @param kb the kblock data (or at least "dsize" bytes claiming to be one)
1461 * @param dsize size of "kb" in bytes; check for < sizeof(struct KBlock)!
1462 * @param query where to store the query that this block answers
1463 * @return GNUNET_OK if this is actually a well-formed KBlock
1466 check_kblock (const struct KBlock *kb,
1468 GNUNET_HashCode *query)
1470 if (dsize < sizeof (struct KBlock))
1472 GNUNET_break_op (0);
1473 return GNUNET_SYSERR;
1475 if (dsize - sizeof (struct KBlock) !=
1476 ntohs (kb->purpose.size)
1477 - sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose)
1478 - sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) )
1480 GNUNET_break_op (0);
1481 return GNUNET_SYSERR;
1484 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_KBLOCK,
1489 GNUNET_break_op (0);
1490 return GNUNET_SYSERR;
1493 GNUNET_CRYPTO_hash (&kb->keyspace,
1494 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1501 * Check if the given SBlock is well-formed.
1503 * @param sb the sblock data (or at least "dsize" bytes claiming to be one)
1504 * @param dsize size of "kb" in bytes; check for < sizeof(struct SBlock)!
1505 * @param query where to store the query that this block answers
1506 * @param namespace where to store the namespace that this block belongs to
1507 * @return GNUNET_OK if this is actually a well-formed SBlock
1510 check_sblock (const struct SBlock *sb,
1512 GNUNET_HashCode *query,
1513 GNUNET_HashCode *namespace)
1515 if (dsize < sizeof (struct SBlock))
1517 GNUNET_break_op (0);
1518 return GNUNET_SYSERR;
1521 ntohs (sb->purpose.size) + sizeof (struct GNUNET_CRYPTO_RsaSignature))
1523 GNUNET_break_op (0);
1524 return GNUNET_SYSERR;
1527 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_SBLOCK,
1532 GNUNET_break_op (0);
1533 return GNUNET_SYSERR;
1536 *query = sb->identifier;
1537 if (namespace != NULL)
1538 GNUNET_CRYPTO_hash (&sb->subspace,
1539 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1546 * Transmit the given message by copying it to the target buffer
1547 * "buf". "buf" will be NULL and "size" zero if the socket was closed
1548 * for writing in the meantime. In that case, do nothing
1549 * (the disconnect or shutdown handler will take care of the rest).
1550 * If we were able to transmit messages and there are still more
1551 * pending, ask core again for further calls to this function.
1553 * @param cls closure, pointer to the 'struct ClientList*'
1554 * @param size number of bytes available in buf
1555 * @param buf where the callee should write the message
1556 * @return number of bytes written to buf
1559 transmit_to_client (void *cls,
1560 size_t size, void *buf)
1562 struct ClientList *cl = cls;
1564 struct ClientResponseMessage *creply;
1571 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1572 "Not sending reply, client communication problem.\n");
1577 while ( (NULL != (creply = cl->res_head) ) &&
1578 (creply->msize <= size) )
1580 memcpy (&cbuf[msize], &creply[1], creply->msize);
1581 msize += creply->msize;
1582 size -= creply->msize;
1583 GNUNET_CONTAINER_DLL_remove (cl->res_head,
1586 GNUNET_free (creply);
1589 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
1591 GNUNET_TIME_UNIT_FOREVER_REL,
1592 &transmit_to_client,
1599 * Closure for "process_reply" function.
1601 struct ProcessReplyClosure
1604 * The data for the reply.
1608 // FIXME: add 'struct ConnectedPeer' to track 'last_xxx_replies' here!
1611 * When the reply expires.
1613 struct GNUNET_TIME_Absolute expiration;
1621 * Namespace that this reply belongs to
1622 * (if it is of type SBLOCK).
1624 GNUNET_HashCode namespace;
1627 * Type of the block.
1632 * How much was this reply worth to us?
1639 * We have received a reply; handle it!
1641 * @param cls response (struct ProcessReplyClosure)
1642 * @param key our query
1643 * @param value value in the hash map (info about the query)
1644 * @return GNUNET_YES (we should continue to iterate)
1647 process_reply (void *cls,
1648 const GNUNET_HashCode * key,
1651 struct ProcessReplyClosure *prq = cls;
1652 struct PendingRequest *pr = value;
1653 struct PendingMessage *reply;
1654 struct ClientResponseMessage *creply;
1655 struct ClientList *cl;
1656 struct PutMessage *pm;
1657 struct ContentMessage *cm;
1658 struct ConnectedPeer *cp;
1659 GNUNET_HashCode chash;
1660 GNUNET_HashCode mhash;
1665 GNUNET_CRYPTO_hash (prq->data,
1670 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1671 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1672 /* only possible reply, stop requesting! */
1673 while (NULL != pr->pending_head)
1674 destroy_pending_message_list_entry (pr->pending_head);
1675 GNUNET_break (GNUNET_YES ==
1676 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
1680 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1681 if (0 != memcmp (pr->namespace,
1683 sizeof (GNUNET_HashCode)))
1684 return GNUNET_YES; /* wrong namespace */
1685 /* then: fall-through! */
1686 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1689 mingle_hash (&chash, pr->mingle, &mhash);
1690 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
1692 return GNUNET_YES; /* duplicate */
1693 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
1696 if (pr->client_request_list != NULL)
1698 if (pr->replies_seen_size == pr->replies_seen_off)
1700 GNUNET_array_grow (pr->replies_seen,
1701 pr->replies_seen_size,
1702 pr->replies_seen_size * 2 + 4);
1703 // FIXME: recalculate BF!
1705 pr->replies_seen[pr->replies_seen_off++] = chash;
1708 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
1709 // FIXME: any checks against duplicates for SKBlocks?
1715 prio = pr->priority;
1716 prq->priority += pr->remaining_priority;
1717 pr->remaining_priority = 0;
1718 if (pr->client_request_list != NULL)
1720 cl = pr->client_request_list->client_list;
1721 msize = sizeof (struct PutMessage) + prq->size;
1722 creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
1723 creply->msize = msize;
1724 creply->client_list = cl;
1725 GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
1729 pm = (struct PutMessage*) &creply[1];
1730 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
1731 pm->header.size = htons (msize);
1732 pm->type = htonl (prq->type);
1733 pm->expiration = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining (prq->expiration));
1734 memcpy (&creply[1], prq->data, prq->size);
1736 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
1738 GNUNET_TIME_UNIT_FOREVER_REL,
1739 &transmit_to_client,
1741 GNUNET_break (cl->th != NULL);
1745 cp = pr->pht_entry->cp;
1746 msize = sizeof (struct ContentMessage) + prq->size;
1747 reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
1748 reply->cont = &transmit_reply_continuation;
1749 reply->cont_cls = pr;
1750 reply->msize = msize;
1751 reply->priority = (uint32_t) -1; /* send replies first! */
1752 cm = (struct ContentMessage*) &reply[1];
1753 cm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_CONTENT);
1754 cm->header.size = htons (msize);
1755 cm->type = htonl (prq->type);
1756 cm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
1757 memcpy (&reply[1], prq->data, prq->size);
1758 add_to_pending_messages_for_peer (cp, reply, pr);
1762 // FIXME: implement hot-path routing statistics keeping!
1768 * Handle P2P "PUT" message.
1770 * @param cls closure, always NULL
1771 * @param other the other peer involved (sender or receiver, NULL
1772 * for loopback messages where we are both sender and receiver)
1773 * @param message the actual message
1774 * @param latency reported latency of the connection with 'other'
1775 * @param distance reported distance (DV) to 'other'
1776 * @return GNUNET_OK to keep the connection open,
1777 * GNUNET_SYSERR to close it (signal serious error)
1780 handle_p2p_put (void *cls,
1781 const struct GNUNET_PeerIdentity *other,
1782 const struct GNUNET_MessageHeader *message,
1783 struct GNUNET_TIME_Relative latency,
1786 const struct PutMessage *put;
1790 struct GNUNET_TIME_Absolute expiration;
1791 GNUNET_HashCode query;
1792 struct ProcessReplyClosure prq;
1794 msize = ntohs (message->size);
1795 if (msize < sizeof (struct PutMessage))
1798 return GNUNET_SYSERR;
1800 put = (const struct PutMessage*) message;
1801 dsize = msize - sizeof (struct PutMessage);
1802 type = ntohl (put->type);
1803 expiration = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (put->expiration));
1805 /* first, validate! */
1808 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1809 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1810 GNUNET_CRYPTO_hash (&put[1], dsize, &query);
1812 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1814 check_kblock ((const struct KBlock*) &put[1],
1817 return GNUNET_SYSERR;
1819 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1821 check_sblock ((const struct SBlock*) &put[1],
1825 return GNUNET_SYSERR;
1827 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
1828 // FIXME -- validate SKBLOCK!
1832 /* unknown block type */
1833 GNUNET_break_op (0);
1834 return GNUNET_SYSERR;
1837 /* now, lookup 'query' */
1838 prq.data = (const void*) &put[1];
1841 prq.expiration = expiration;
1843 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
1847 // FIXME: if migration is on and load is low,
1848 // queue to store data in datastore;
1849 // use "prq.priority" for that!
1854 /* **************************** P2P GET Handling ************************ */
1858 * We're processing (local) results for a search request
1859 * from another peer. Pass applicable results to the
1860 * peer and if we are done either clean up (operation
1861 * complete) or forward to other peers (more results possible).
1863 * @param cls our closure (struct LocalGetContext)
1864 * @param key key for the content
1865 * @param size number of bytes in data
1866 * @param data content stored
1867 * @param type type of the content
1868 * @param priority priority of the content
1869 * @param anonymity anonymity-level for the content
1870 * @param expiration expiration time for the content
1871 * @param uid unique identifier for the datum;
1872 * maybe 0 if no unique identifier is available
1875 process_local_reply (void *cls,
1876 const GNUNET_HashCode * key,
1882 struct GNUNET_TIME_Absolute
1886 struct PendingRequest *pr = cls;
1887 struct ProcessReplyClosure prq;
1888 GNUNET_HashCode dhash;
1889 GNUNET_HashCode mhash;
1890 GNUNET_HashCode query;
1895 /* no more results */
1896 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1897 pr->task = GNUNET_SCHEDULER_add_now (sched,
1898 &forward_request_task,
1902 if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
1905 GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
1906 anonymity, expiration, uid,
1907 &process_local_reply,
1909 GNUNET_FS_drq_get_next (GNUNET_YES);
1912 /* check for duplicates */
1913 GNUNET_CRYPTO_hash (data, size, &dhash);
1914 mingle_hash (&dhash,
1917 if ( (pr->bf != NULL) &&
1919 GNUNET_CONTAINER_bloomfilter_test (pr->bf,
1923 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1924 "Result from datastore filtered by bloomfilter.\n");
1926 GNUNET_FS_drq_get_next (GNUNET_YES);
1929 pr->results_found++;
1930 if ( (pr->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
1931 (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
1932 (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) )
1937 pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1941 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
1944 memset (&prq, 0, sizeof (prq));
1946 prq.expiration = expiration;
1948 if ( (type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) &&
1949 (GNUNET_OK != check_sblock ((const struct SBlock*) data,
1955 /* FIXME: consider removing the block? */
1956 GNUNET_FS_drq_get_next (GNUNET_YES);
1960 prq.priority = priority;
1961 process_reply (&prq, key, pr);
1963 if ( (GNUNET_YES == test_load_too_high()) ||
1964 (pr->results_found > 5 + 2 * pr->priority) )
1966 GNUNET_FS_drq_get_next (GNUNET_NO);
1969 GNUNET_FS_drq_get_next (GNUNET_YES);
1974 * The priority level imposes a bound on the maximum
1975 * value for the ttl that can be requested.
1977 * @param ttl_in requested ttl
1978 * @param prio given priority
1979 * @return ttl_in if ttl_in is below the limit,
1980 * otherwise the ttl-limit for the given priority
1983 bound_ttl (int32_t ttl_in, uint32_t prio)
1985 unsigned long long allowed;
1989 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
1990 if (ttl_in > allowed)
1992 if (allowed >= (1 << 30))
2001 * We've received a request with the specified priority. Bound it
2002 * according to how much we trust the given peer.
2004 * @param prio_in requested priority
2005 * @param cp the peer making the request
2006 * @return effective priority
2009 bound_priority (uint32_t prio_in,
2010 struct ConnectedPeer *cp)
2017 * Handle P2P "GET" request.
2019 * @param cls closure, always NULL
2020 * @param other the other peer involved (sender or receiver, NULL
2021 * for loopback messages where we are both sender and receiver)
2022 * @param message the actual message
2023 * @param latency reported latency of the connection with 'other'
2024 * @param distance reported distance (DV) to 'other'
2025 * @return GNUNET_OK to keep the connection open,
2026 * GNUNET_SYSERR to close it (signal serious error)
2029 handle_p2p_get (void *cls,
2030 const struct GNUNET_PeerIdentity *other,
2031 const struct GNUNET_MessageHeader *message,
2032 struct GNUNET_TIME_Relative latency,
2035 struct PendingRequest *pr;
2036 struct PeerRequestEntry *pre;
2037 struct ConnectedPeer *cp;
2038 struct ConnectedPeer *cps;
2039 struct GNUNET_TIME_Relative timeout;
2041 const struct GetMessage *gm;
2043 const GNUNET_HashCode *opt;
2046 uint32_t ttl_decrement;
2050 msize = ntohs(message->size);
2051 if (msize < sizeof (struct GetMessage))
2053 GNUNET_break_op (0);
2054 return GNUNET_SYSERR;
2056 gm = (const struct GetMessage*) message;
2057 bm = ntohl (gm->hash_bitmap);
2065 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
2067 GNUNET_break_op (0);
2068 return GNUNET_SYSERR;
2070 opt = (const GNUNET_HashCode*) &gm[1];
2071 bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
2073 bm = ntohl (gm->hash_bitmap);
2074 if ( (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)) &&
2075 (ntohl (gm->type) == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) )
2077 GNUNET_break_op (0);
2078 return GNUNET_SYSERR;
2081 cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2082 &other->hashPubKey);
2083 GNUNET_assert (NULL != cps);
2084 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
2085 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2091 /* FIXME: try connect? */
2094 /* note that we can really only check load here since otherwise
2095 peers could find out that we are overloaded by not being
2096 disconnected after sending us a malformed query... */
2097 if (GNUNET_YES == test_load_too_high ())
2100 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2101 "Dropping query from `%s', this peer is too busy.\n",
2102 GNUNET_i2s (other));
2107 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
2108 (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)?sizeof(GNUNET_HashCode):0);
2109 if ((bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2110 pr->namespace = (GNUNET_HashCode*) &pr[1];
2111 pr->type = ntohl (gm->type);
2112 pr->mingle = gm->filter_mutator;
2113 if (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2114 memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
2115 else if (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)
2117 GNUNET_break_op (0);
2119 return GNUNET_SYSERR;
2121 if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
2122 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
2124 pr->anonymity_level = 1;
2125 pr->priority = bound_priority (ntohl (gm->priority), cps);
2126 pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
2127 pr->query = gm->query;
2128 /* decrement ttl (always) */
2129 ttl_decrement = 2 * TTL_DECREMENT +
2130 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2132 if ( (pr->ttl < 0) &&
2133 (pr->ttl - ttl_decrement > 0) )
2136 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2137 "Dropping query from `%s' due to TTL underflow.\n",
2138 GNUNET_i2s (other));
2140 /* integer underflow => drop (should be very rare)! */
2144 pr->ttl -= ttl_decrement;
2145 pr->start_time = GNUNET_TIME_absolute_get ();
2147 /* get bloom filter */
2150 pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
2153 pr->bf_size = bfsize;
2156 /* FIXME: check somewhere if request already exists, and if so,
2157 recycle old state... */
2158 pre = GNUNET_malloc (sizeof (struct PeerRequestEntry));
2161 GNUNET_CONTAINER_multihashmap_put (query_request_map,
2164 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2166 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
2168 GNUNET_TIME_absolute_get().value + pr->ttl);
2171 /* calculate change in traffic preference */
2172 preference = (double) pr->priority;
2173 if (preference < QUERY_BANDWIDTH_VALUE)
2174 preference = QUERY_BANDWIDTH_VALUE;
2175 cps->inc_preference += preference;
2177 /* process locally */
2179 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2180 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2181 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
2182 (pr->priority + 1));
2183 pr->drq = GNUNET_FS_drq_get (&gm->query,
2185 &process_local_reply,
2190 /* Are multiple results possible? If so, start processing remotely now! */
2193 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2194 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2195 /* only one result, wait for datastore */
2198 pr->task = GNUNET_SCHEDULER_add_now (sched,
2199 &forward_request_task,
2203 /* make sure we don't track too many requests */
2204 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
2206 pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
2207 destroy_pending_request (pr);
2213 /* **************************** CS GET Handling ************************ */
2217 * Handle START_SEARCH-message (search request from client).
2219 * @param cls closure
2220 * @param client identification of the client
2221 * @param message the actual message
2224 handle_start_search (void *cls,
2225 struct GNUNET_SERVER_Client *client,
2226 const struct GNUNET_MessageHeader *message)
2228 static GNUNET_HashCode all_zeros;
2229 const struct SearchMessage *sm;
2230 struct ClientList *cl;
2231 struct ClientRequestList *crl;
2232 struct PendingRequest *pr;
2237 msize = ntohs (message->size);
2238 if ( (msize < sizeof (struct SearchMessage)) ||
2239 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
2242 GNUNET_SERVER_receive_done (client,
2246 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
2247 sm = (const struct SearchMessage*) message;
2250 while ( (cl != NULL) &&
2251 (cl->client != client) )
2255 cl = GNUNET_malloc (sizeof (struct ClientList));
2256 cl->client = client;
2257 GNUNET_SERVER_client_keep (client);
2258 cl->next = client_list;
2261 type = ntohl (sm->type);
2263 /* FIXME: detect duplicate request; if duplicate, simply update (merge)
2264 'pr->replies_seen'! */
2265 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
2266 ((type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)?sizeof(GNUNET_HashCode):0));
2267 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
2268 memset (crl, 0, sizeof (struct ClientRequestList));
2269 crl->client_list = cl;
2270 GNUNET_CONTAINER_DLL_insert (cl->rl_head,
2275 pr->client_request_list = crl;
2276 GNUNET_array_grow (pr->replies_seen,
2277 pr->replies_seen_size,
2279 memcpy (pr->replies_seen,
2281 sc * sizeof (GNUNET_HashCode));
2282 pr->replies_seen_off = sc;
2283 pr->anonymity_level = ntohl (sm->anonymity_level);
2284 pr->mingle = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK,
2286 pr->query = sm->query;
2289 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2290 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2291 if (0 != memcmp (&sm->target,
2293 sizeof (GNUNET_HashCode)))
2294 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
2296 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2297 pr->namespace = (GNUNET_HashCode*) &pr[1];
2298 memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
2303 GNUNET_CONTAINER_multihashmap_put (query_request_map,
2306 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2307 pr->drq = GNUNET_FS_drq_get (&sm->query,
2309 &process_local_reply,
2311 GNUNET_TIME_UNIT_FOREVER_REL,
2316 /* **************************** Startup ************************ */
2320 * List of handlers for P2P messages
2321 * that we care about.
2323 static struct GNUNET_CORE_MessageHandler p2p_handlers[] =
2326 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
2328 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
2334 * List of handlers for the messages understood by this
2337 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2338 {&GNUNET_FS_handle_index_start, NULL,
2339 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
2340 {&GNUNET_FS_handle_index_list_get, NULL,
2341 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
2342 {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
2343 sizeof (struct UnindexMessage) },
2344 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
2351 * Process fs requests.
2353 * @param cls closure
2354 * @param s scheduler to use
2355 * @param server the initialized server
2356 * @param c configuration to use
2359 main_init (struct GNUNET_SCHEDULER_Handle *s,
2360 struct GNUNET_SERVER_Handle *server,
2361 const struct GNUNET_CONFIGURATION_Handle *c)
2365 connected_peers = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2366 query_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2367 peer_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2368 requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2369 core = GNUNET_CORE_connect (sched,
2371 GNUNET_TIME_UNIT_FOREVER_REL,
2375 &peer_connect_handler,
2376 &peer_disconnect_handler,
2382 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2383 _("Failed to connect to `%s' service.\n"),
2385 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
2386 connected_peers = NULL;
2387 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
2388 query_request_map = NULL;
2389 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
2390 requests_by_expiration_heap = NULL;
2391 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
2392 peer_request_map = NULL;
2394 return GNUNET_SYSERR;
2396 GNUNET_SERVER_disconnect_notify (server,
2397 &handle_client_disconnect,
2399 GNUNET_SERVER_add_handlers (server, handlers);
2400 GNUNET_SCHEDULER_add_delayed (sched,
2401 GNUNET_TIME_UNIT_FOREVER_REL,
2409 * Process fs requests.
2411 * @param cls closure
2412 * @param sched scheduler to use
2413 * @param server the initialized server
2414 * @param cfg configuration to use
2418 struct GNUNET_SCHEDULER_Handle *sched,
2419 struct GNUNET_SERVER_Handle *server,
2420 const struct GNUNET_CONFIGURATION_Handle *cfg)
2422 if ( (GNUNET_OK != GNUNET_FS_drq_init (sched, cfg)) ||
2423 (GNUNET_OK != GNUNET_FS_indexing_init (sched, cfg)) ||
2424 (GNUNET_OK != main_init (sched, server, cfg)) )
2426 GNUNET_SCHEDULER_shutdown (sched);
2433 * The main function for the fs service.
2435 * @param argc number of arguments from the command line
2436 * @param argv command line arguments
2437 * @return 0 ok, 1 on error
2440 main (int argc, char *const *argv)
2442 return (GNUNET_OK ==
2443 GNUNET_SERVICE_run (argc,
2446 GNUNET_SERVICE_OPTION_NONE,
2447 &run, NULL)) ? 0 : 1;
2450 /* end of gnunet-service-fs.c */