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 * - TTL/priority calculations are absent!
29 * - have non-zero preference / priority for requests we initiate!
30 * - implement hot-path routing decision procedure
31 * - implement: bound_priority, test_load_too_high
36 #include "gnunet_constants.h"
37 #include "gnunet_core_service.h"
38 #include "gnunet_datastore_service.h"
39 #include "gnunet_peer_lib.h"
40 #include "gnunet_protocols.h"
41 #include "gnunet_signatures.h"
42 #include "gnunet_statistics_service.h"
43 #include "gnunet_util_lib.h"
44 #include "gnunet-service-fs_indexing.h"
47 #define DEBUG_FS GNUNET_YES
50 * Maximum number of outgoing messages we queue per peer.
51 * FIXME: make configurable?
53 #define MAX_QUEUE_PER_PEER 16
56 * Inverse of the probability that we will submit the same query
57 * to the same peer again. If the same peer already got the query
58 * repeatedly recently, the probability is multiplied by the inverse
59 * of this number each time. Note that we only try about every TTL_DECREMENT/2
60 * plus MAX_CORK_DELAY (so roughly every 3.5s).
62 #define RETRY_PROBABILITY_INV 3
65 * What is the maximum delay for a P2P FS message (in our interaction
66 * with core)? FS-internal delays are another story. The value is
67 * chosen based on the 32k block size. Given that peers typcially
68 * have at least 1 kb/s bandwidth, 45s waits give us a chance to
69 * transmit one message even to the lowest-bandwidth peers.
71 #define MAX_TRANSMIT_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 45)
76 * Maximum number of requests (from other peers) that we're
77 * willing to have pending at any given point in time.
78 * FIXME: set from configuration.
80 static uint64_t max_pending_requests = (32 * 1024);
84 * Information we keep for each pending reply. The
85 * actual message follows at the end of this struct.
87 struct PendingMessage;
90 * Our connection to the datastore.
92 static struct GNUNET_DATASTORE_Handle *dsh;
96 * Function called upon completion of a transmission.
99 * @param pid ID of receiving peer, 0 on transmission error
101 typedef void (*TransmissionContinuation)(void * cls,
102 GNUNET_PEER_Id tpid);
106 * Information we keep for each pending message (GET/PUT). The
107 * actual message follows at the end of this struct.
109 struct PendingMessage
112 * This is a doubly-linked list of messages to the same peer.
114 struct PendingMessage *next;
117 * This is a doubly-linked list of messages to the same peer.
119 struct PendingMessage *prev;
122 * Entry in pending message list for this pending message.
124 struct PendingMessageList *pml;
127 * Function to call immediately once we have transmitted this
130 TransmissionContinuation cont;
138 * Size of the reply; actual reply message follows
139 * at the end of this struct.
144 * How important is this message for us?
152 * Information about a peer that we are connected to.
153 * We track data that is useful for determining which
154 * peers should receive our requests. We also keep
155 * a list of messages to transmit to this peer.
161 * List of the last clients for which this peer successfully
164 struct GNUNET_SERVER_Client *last_client_replies[CS2P_SUCCESS_LIST_SIZE];
167 * List of the last PIDs for which
168 * this peer successfully answered a query;
169 * We use 0 to indicate no successful reply.
171 GNUNET_PEER_Id last_p2p_replies[P2P_SUCCESS_LIST_SIZE];
174 * Average delay between sending the peer a request and
175 * getting a reply (only calculated over the requests for
176 * which we actually got a reply). Calculated
177 * as a moving average: new_delay = ((n-1)*last_delay+curr_delay) / n
179 struct GNUNET_TIME_Relative avg_delay;
182 * Handle for an active request for transmission to this
185 struct GNUNET_CORE_TransmitHandle *cth;
188 * Messages (replies, queries, content migration) we would like to
189 * send to this peer in the near future. Sorted by priority, head.
191 struct PendingMessage *pending_messages_head;
194 * Messages (replies, queries, content migration) we would like to
195 * send to this peer in the near future. Sorted by priority, tail.
197 struct PendingMessage *pending_messages_tail;
200 * Average priority of successful replies. Calculated
201 * as a moving average: new_avg = ((n-1)*last_avg+curr_prio) / n
206 * Increase in traffic preference still to be submitted
207 * to the core service for this peer. FIXME: double or 'uint64_t'?
209 double inc_preference;
212 * The peer's identity.
217 * Size of the linked list of 'pending_messages'.
219 unsigned int pending_requests;
222 * Which offset in "last_p2p_replies" will be updated next?
223 * (we go round-robin).
225 unsigned int last_p2p_replies_woff;
228 * Which offset in "last_client_replies" will be updated next?
229 * (we go round-robin).
231 unsigned int last_client_replies_woff;
237 * Information we keep for each pending request. We should try to
238 * keep this struct as small as possible since its memory consumption
239 * is key to how many requests we can have pending at once.
241 struct PendingRequest;
245 * Doubly-linked list of requests we are performing
246 * on behalf of the same client.
248 struct ClientRequestList
252 * This is a doubly-linked list.
254 struct ClientRequestList *next;
257 * This is a doubly-linked list.
259 struct ClientRequestList *prev;
262 * Request this entry represents.
264 struct PendingRequest *req;
267 * Client list this request belongs to.
269 struct ClientList *client_list;
275 * Replies to be transmitted to the client. The actual
276 * response message is allocated after this struct.
278 struct ClientResponseMessage
281 * This is a doubly-linked list.
283 struct ClientResponseMessage *next;
286 * This is a doubly-linked list.
288 struct ClientResponseMessage *prev;
291 * Client list entry this response belongs to.
293 struct ClientList *client_list;
296 * Number of bytes in the response.
303 * Linked list of clients we are performing requests
309 * This is a linked list.
311 struct ClientList *next;
314 * ID of a client making a request, NULL if this entry is for a
317 struct GNUNET_SERVER_Client *client;
320 * Head of list of requests performed on behalf
321 * of this client right now.
323 struct ClientRequestList *rl_head;
326 * Tail of list of requests performed on behalf
327 * of this client right now.
329 struct ClientRequestList *rl_tail;
332 * Head of linked list of responses.
334 struct ClientResponseMessage *res_head;
337 * Tail of linked list of responses.
339 struct ClientResponseMessage *res_tail;
342 * Context for sending replies.
344 struct GNUNET_CONNECTION_TransmitHandle *th;
350 * Doubly-linked list of messages we are performing
351 * due to a pending request.
353 struct PendingMessageList
357 * This is a doubly-linked list of messages on behalf of the same request.
359 struct PendingMessageList *next;
362 * This is a doubly-linked list of messages on behalf of the same request.
364 struct PendingMessageList *prev;
367 * Message this entry represents.
369 struct PendingMessage *pm;
372 * Request this entry belongs to.
374 struct PendingRequest *req;
377 * Peer this message is targeted for.
379 struct ConnectedPeer *target;
385 * Information we keep for each pending request. We should try to
386 * keep this struct as small as possible since its memory consumption
387 * is key to how many requests we can have pending at once.
389 struct PendingRequest
393 * If this request was made by a client, this is our entry in the
394 * client request list; otherwise NULL.
396 struct ClientRequestList *client_request_list;
399 * Entry of peer responsible for this entry (if this request
400 * was made by a peer).
402 struct ConnectedPeer *cp;
405 * If this is a namespace query, pointer to the hash of the public
406 * key of the namespace; otherwise NULL. Pointer will be to the
407 * end of this struct (so no need to free it).
409 const GNUNET_HashCode *namespace;
412 * Bloomfilter we use to filter out replies that we don't care about
413 * (anymore). NULL as long as we are interested in all replies.
415 struct GNUNET_CONTAINER_BloomFilter *bf;
418 * Context of our GNUNET_CORE_peer_change_preference call.
420 struct GNUNET_CORE_InformationRequestContext *irc;
423 * Hash code of all replies that we have seen so far (only valid
424 * if client is not NULL since we only track replies like this for
427 GNUNET_HashCode *replies_seen;
430 * Node in the heap representing this entry; NULL
431 * if we have no heap node.
433 struct GNUNET_CONTAINER_HeapNode *hnode;
436 * Head of list of messages being performed on behalf of this
439 struct PendingMessageList *pending_head;
442 * Tail of list of messages being performed on behalf of this
445 struct PendingMessageList *pending_tail;
448 * When did we first see this request (form this peer), or, if our
449 * client is initiating, when did we last initiate a search?
451 struct GNUNET_TIME_Absolute start_time;
454 * The query that this request is for.
456 GNUNET_HashCode query;
459 * The task responsible for transmitting queries
462 GNUNET_SCHEDULER_TaskIdentifier task;
465 * (Interned) Peer identifier that identifies a preferred target
468 GNUNET_PEER_Id target_pid;
471 * (Interned) Peer identifiers of peers that have already
472 * received our query for this content.
474 GNUNET_PEER_Id *used_pids;
477 * Our entry in the queue (non-NULL while we wait for our
478 * turn to interact with the local database).
480 struct GNUNET_DATASTORE_QueueEntry *qe;
484 * Size of the 'bf' (in bytes).
489 * Desired anonymity level; only valid for requests from a local client.
491 uint32_t anonymity_level;
494 * How many entries in "used_pids" are actually valid?
496 unsigned int used_pids_off;
499 * How long is the "used_pids" array?
501 unsigned int used_pids_size;
504 * Number of results found for this request.
506 unsigned int results_found;
509 * How many entries in "replies_seen" are actually valid?
511 unsigned int replies_seen_off;
514 * How long is the "replies_seen" array?
516 unsigned int replies_seen_size;
519 * Priority with which this request was made. If one of our clients
520 * made the request, then this is the current priority that we are
521 * using when initiating the request. This value is used when
522 * we decide to reward other peers with trust for providing a reply.
527 * Priority points left for us to spend when forwarding this request
530 uint32_t remaining_priority;
533 * Number to mingle hashes for bloom-filter tests with.
538 * TTL with which we saw this request (or, if we initiated, TTL that
539 * we used for the request).
544 * Type of the content that this request is for.
546 enum GNUNET_BLOCK_Type type;
549 * Remove this request after transmission of the current response.
554 * GNUNET_YES if we should not forward this request to other peers.
562 * Block that is ready for migration to other peers. Actual data is at the end of the block.
564 struct MigrationReadyBlock
568 * This is a doubly-linked list.
570 struct MigrationReadyBlock *next;
573 * This is a doubly-linked list.
575 struct MigrationReadyBlock *prev;
578 * Query for the block.
580 GNUNET_HashCode query;
583 * When does this block expire?
585 struct GNUNET_TIME_Absolute expiration;
588 * Peers we would consider forwarding this
589 * block to. Zero for empty entries.
591 GNUNET_PEER_Id target_list[MIGRATION_LIST_SIZE];
599 * Number of targets already used.
601 unsigned int used_targets;
606 enum GNUNET_BLOCK_Type type;
613 static struct GNUNET_SCHEDULER_Handle *sched;
618 static const struct GNUNET_CONFIGURATION_Handle *cfg;
621 * Map of peer identifiers to "struct ConnectedPeer" (for that peer).
623 static struct GNUNET_CONTAINER_MultiHashMap *connected_peers;
626 * Map of peer identifiers to "struct PendingRequest" (for that peer).
628 static struct GNUNET_CONTAINER_MultiHashMap *peer_request_map;
631 * Map of query identifiers to "struct PendingRequest" (for that query).
633 static struct GNUNET_CONTAINER_MultiHashMap *query_request_map;
636 * Heap with the request that will expire next at the top. Contains
637 * pointers of type "struct PendingRequest*"; these will *also* be
638 * aliased from the "requests_by_peer" data structures and the
639 * "requests_by_query" table. Note that requests from our clients
640 * don't expire and are thus NOT in the "requests_by_expiration"
641 * (or the "requests_by_peer" tables).
643 static struct GNUNET_CONTAINER_Heap *requests_by_expiration_heap;
646 * Handle for reporting statistics.
648 static struct GNUNET_STATISTICS_Handle *stats;
651 * Linked list of clients we are currently processing requests for.
653 static struct ClientList *client_list;
656 * Pointer to handle to the core service (points to NULL until we've
659 static struct GNUNET_CORE_Handle *core;
662 * Head of linked list of blocks that can be migrated.
664 static struct MigrationReadyBlock *mig_head;
667 * Tail of linked list of blocks that can be migrated.
669 static struct MigrationReadyBlock *mig_tail;
672 * Request to datastore for migration (or NULL).
674 static struct GNUNET_DATASTORE_QueueEntry *mig_qe;
677 * ID of task that collects blocks for migration.
679 static GNUNET_SCHEDULER_TaskIdentifier mig_task;
682 * What is the maximum frequency at which we are allowed to
683 * poll the datastore for migration content?
685 static struct GNUNET_TIME_Relative min_migration_delay;
688 * Size of the doubly-linked list of migration blocks.
690 static unsigned int mig_size;
693 * Are we allowed to migrate content to this peer.
695 static int active_migration;
699 * Transmit messages by copying it to the target buffer
700 * "buf". "buf" will be NULL and "size" zero if the socket was closed
701 * for writing in the meantime. In that case, do nothing
702 * (the disconnect or shutdown handler will take care of the rest).
703 * If we were able to transmit messages and there are still more
704 * pending, ask core again for further calls to this function.
706 * @param cls closure, pointer to the 'struct ConnectedPeer*'
707 * @param size number of bytes available in buf
708 * @param buf where the callee should write the message
709 * @return number of bytes written to buf
712 transmit_to_peer (void *cls,
713 size_t size, void *buf);
716 /* ******************* clean up functions ************************ */
720 * Delete the given migration block.
722 * @param mb block to delete
725 delete_migration_block (struct MigrationReadyBlock *mb)
727 GNUNET_CONTAINER_DLL_remove (mig_head,
730 GNUNET_PEER_decrement_rcs (mb->target_list,
731 MIGRATION_LIST_SIZE);
738 * Compare the distance of two peers to a key.
741 * @param p1 first peer
742 * @param p2 second peer
743 * @return GNUNET_YES if P1 is closer to key than P2
746 is_closer (const GNUNET_HashCode *key,
747 const struct GNUNET_PeerIdentity *p1,
748 const struct GNUNET_PeerIdentity *p2)
750 return GNUNET_CRYPTO_hash_xorcmp (&p1->hashPubKey,
757 * Consider migrating content to a given peer.
759 * @param cls 'struct MigrationReadyBlock*' to select
760 * targets for (or NULL for none)
761 * @param key ID of the peer
762 * @param value 'struct ConnectedPeer' of the peer
763 * @return GNUNET_YES (always continue iteration)2
766 consider_migration (void *cls,
767 const GNUNET_HashCode *key,
770 struct MigrationReadyBlock *mb = cls;
771 struct ConnectedPeer *cp = value;
772 struct MigrationReadyBlock *pos;
773 struct GNUNET_PeerIdentity cppid;
774 struct GNUNET_PeerIdentity otherpid;
775 struct GNUNET_PeerIdentity worstpid;
780 /* consider 'cp' as a migration target for mb */
783 GNUNET_PEER_resolve (cp->pid,
785 repl = MIGRATION_LIST_SIZE;
786 for (i=0;i<MIGRATION_LIST_SIZE;i++)
788 if (mb->target_list[i] == 0)
790 mb->target_list[i] = cp->pid;
791 GNUNET_PEER_change_rc (mb->target_list[i], 1);
792 repl = MIGRATION_LIST_SIZE;
795 GNUNET_PEER_resolve (mb->target_list[i],
797 if ( (repl == MIGRATION_LIST_SIZE) &&
798 is_closer (&mb->query,
805 else if ( (repl != MIGRATION_LIST_SIZE) &&
806 (is_closer (&mb->query,
814 if (repl != MIGRATION_LIST_SIZE)
816 GNUNET_PEER_change_rc (mb->target_list[repl], -1);
817 mb->target_list[repl] = cp->pid;
818 GNUNET_PEER_change_rc (mb->target_list[repl], 1);
822 /* consider scheduling transmission to cp for content migration */
829 for (i=0;i<MIGRATION_LIST_SIZE;i++)
831 if (cp->pid == pos->target_list[i])
836 msize = GNUNET_MIN (msize,
844 return GNUNET_YES; /* no content available */
845 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
846 "Trying to migrate `%s' (%u bytes) to `%s'\n",
847 GNUNET_h2s (&mb->query),
849 GNUNET_i2s (&cppid));
851 = GNUNET_CORE_notify_transmit_ready (core,
852 0, GNUNET_TIME_UNIT_FOREVER_REL,
853 (const struct GNUNET_PeerIdentity*) key,
854 msize + sizeof (struct PutMessage),
862 * Task that is run periodically to obtain blocks for content
866 * @param tc scheduler context (also unused)
869 gather_migration_blocks (void *cls,
870 const struct GNUNET_SCHEDULER_TaskContext *tc);
874 * If the migration task is not currently running, consider
875 * (re)scheduling it with the appropriate delay.
878 consider_migration_gathering ()
880 struct GNUNET_TIME_Relative delay;
884 if (mig_task != GNUNET_SCHEDULER_NO_TASK)
886 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
888 delay = GNUNET_TIME_relative_divide (delay,
889 MAX_MIGRATION_QUEUE);
890 delay = GNUNET_TIME_relative_max (delay,
891 min_migration_delay);
892 mig_task = GNUNET_SCHEDULER_add_delayed (sched,
894 &gather_migration_blocks,
900 * Process content offered for migration.
903 * @param key key for the content
904 * @param size number of bytes in data
905 * @param data content stored
906 * @param type type of the content
907 * @param priority priority of the content
908 * @param anonymity anonymity-level for the content
909 * @param expiration expiration time for the content
910 * @param uid unique identifier for the datum;
911 * maybe 0 if no unique identifier is available
914 process_migration_content (void *cls,
915 const GNUNET_HashCode * key,
918 enum GNUNET_BLOCK_Type type,
921 struct GNUNET_TIME_Absolute
922 expiration, uint64_t uid)
924 struct MigrationReadyBlock *mb;
929 if (mig_size < MAX_MIGRATION_QUEUE)
930 consider_migration_gathering ();
933 if (type == GNUNET_BLOCK_TYPE_ONDEMAND)
936 GNUNET_FS_handle_on_demand_block (key, size, data,
937 type, priority, anonymity,
939 &process_migration_content,
941 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
945 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
946 "Retrieved block `%s' of type %u for migration\n",
950 mb = GNUNET_malloc (sizeof (struct MigrationReadyBlock) + size);
952 mb->expiration = expiration;
955 memcpy (&mb[1], data, size);
956 GNUNET_CONTAINER_DLL_insert_after (mig_head,
961 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
964 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
969 * Task that is run periodically to obtain blocks for content
973 * @param tc scheduler context (also unused)
976 gather_migration_blocks (void *cls,
977 const struct GNUNET_SCHEDULER_TaskContext *tc)
979 mig_task = GNUNET_SCHEDULER_NO_TASK;
980 mig_qe = GNUNET_DATASTORE_get_random (dsh, 0, -1,
981 GNUNET_TIME_UNIT_FOREVER_REL,
982 &process_migration_content, NULL);
983 GNUNET_assert (mig_qe != NULL);
988 * We're done with a particular message list entry.
989 * Free all associated resources.
991 * @param pml entry to destroy
994 destroy_pending_message_list_entry (struct PendingMessageList *pml)
996 GNUNET_CONTAINER_DLL_remove (pml->req->pending_head,
997 pml->req->pending_tail,
999 GNUNET_CONTAINER_DLL_remove (pml->target->pending_messages_head,
1000 pml->target->pending_messages_tail,
1002 pml->target->pending_requests--;
1003 GNUNET_free (pml->pm);
1009 * Destroy the given pending message (and call the respective
1012 * @param pm message to destroy
1013 * @param tpid id of peer that the message was delivered to, or 0 for none
1016 destroy_pending_message (struct PendingMessage *pm,
1017 GNUNET_PEER_Id tpid)
1019 struct PendingMessageList *pml = pm->pml;
1020 TransmissionContinuation cont;
1023 GNUNET_assert (pml->pm == pm);
1024 GNUNET_assert ( (tpid == 0) || (tpid == pml->target->pid) );
1026 cont_cls = pm->cont_cls;
1027 destroy_pending_message_list_entry (pml);
1028 cont (cont_cls, tpid);
1033 * We're done processing a particular request.
1034 * Free all associated resources.
1036 * @param pr request to destroy
1039 destroy_pending_request (struct PendingRequest *pr)
1041 struct GNUNET_PeerIdentity pid;
1043 if (pr->hnode != NULL)
1045 GNUNET_CONTAINER_heap_remove_node (requests_by_expiration_heap,
1049 if (NULL == pr->client_request_list)
1051 GNUNET_STATISTICS_update (stats,
1052 gettext_noop ("# P2P searches active"),
1058 GNUNET_STATISTICS_update (stats,
1059 gettext_noop ("# client searches active"),
1063 /* might have already been removed from map in 'process_reply' (if
1064 there was a unique reply) or never inserted if it was a
1065 duplicate; hence ignore the return value here */
1066 (void) GNUNET_CONTAINER_multihashmap_remove (query_request_map,
1071 GNUNET_DATASTORE_cancel (pr->qe);
1074 if (pr->client_request_list != NULL)
1076 GNUNET_CONTAINER_DLL_remove (pr->client_request_list->client_list->rl_head,
1077 pr->client_request_list->client_list->rl_tail,
1078 pr->client_request_list);
1079 GNUNET_free (pr->client_request_list);
1080 pr->client_request_list = NULL;
1084 GNUNET_PEER_resolve (pr->cp->pid,
1086 (void) GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
1093 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
1096 if (pr->irc != NULL)
1098 GNUNET_CORE_peer_change_preference_cancel (pr->irc);
1101 if (pr->replies_seen != NULL)
1103 GNUNET_free (pr->replies_seen);
1104 pr->replies_seen = NULL;
1106 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
1108 GNUNET_SCHEDULER_cancel (sched,
1110 pr->task = GNUNET_SCHEDULER_NO_TASK;
1112 while (NULL != pr->pending_head)
1113 destroy_pending_message_list_entry (pr->pending_head);
1114 GNUNET_PEER_change_rc (pr->target_pid, -1);
1115 if (pr->used_pids != NULL)
1117 GNUNET_PEER_decrement_rcs (pr->used_pids, pr->used_pids_off);
1118 GNUNET_free (pr->used_pids);
1119 pr->used_pids_off = 0;
1120 pr->used_pids_size = 0;
1121 pr->used_pids = NULL;
1128 * Method called whenever a given peer connects.
1130 * @param cls closure, not used
1131 * @param peer peer identity this notification is about
1132 * @param latency reported latency of the connection with 'other'
1133 * @param distance reported distance (DV) to 'other'
1136 peer_connect_handler (void *cls,
1138 GNUNET_PeerIdentity * peer,
1139 struct GNUNET_TIME_Relative latency,
1142 struct ConnectedPeer *cp;
1143 struct MigrationReadyBlock *pos;
1145 cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
1146 cp->pid = GNUNET_PEER_intern (peer);
1147 GNUNET_break (GNUNET_OK ==
1148 GNUNET_CONTAINER_multihashmap_put (connected_peers,
1151 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1156 (void) consider_migration (pos, &peer->hashPubKey, cp);
1164 * Free (each) request made by the peer.
1166 * @param cls closure, points to peer that the request belongs to
1167 * @param key current key code
1168 * @param value value in the hash map
1169 * @return GNUNET_YES (we should continue to iterate)
1172 destroy_request (void *cls,
1173 const GNUNET_HashCode * key,
1176 const struct GNUNET_PeerIdentity * peer = cls;
1177 struct PendingRequest *pr = value;
1179 GNUNET_break (GNUNET_YES ==
1180 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
1183 destroy_pending_request (pr);
1189 * Method called whenever a peer disconnects.
1191 * @param cls closure, not used
1192 * @param peer peer identity this notification is about
1195 peer_disconnect_handler (void *cls,
1197 GNUNET_PeerIdentity * peer)
1199 struct ConnectedPeer *cp;
1200 struct PendingMessage *pm;
1202 struct MigrationReadyBlock *pos;
1203 struct MigrationReadyBlock *next;
1205 GNUNET_CONTAINER_multihashmap_get_multiple (peer_request_map,
1209 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1213 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1215 if (NULL != cp->last_client_replies[i])
1217 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1218 cp->last_client_replies[i] = NULL;
1221 GNUNET_break (GNUNET_YES ==
1222 GNUNET_CONTAINER_multihashmap_remove (connected_peers,
1225 /* remove this peer from migration considerations; schedule
1228 while (NULL != (pos = next))
1231 for (i=0;i<MIGRATION_LIST_SIZE;i++)
1233 if (pos->target_list[i] == cp->pid)
1235 GNUNET_PEER_change_rc (pos->target_list[i], -1);
1236 pos->target_list[i] = 0;
1239 if (pos->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers))
1241 delete_migration_block (pos);
1242 consider_migration_gathering ();
1245 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1246 &consider_migration,
1250 GNUNET_PEER_change_rc (cp->pid, -1);
1251 GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
1252 if (NULL != cp->cth)
1253 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
1254 while (NULL != (pm = cp->pending_messages_head))
1255 destroy_pending_message (pm, 0 /* delivery failed */);
1256 GNUNET_break (0 == cp->pending_requests);
1262 * Iterator over hash map entries that removes all occurences
1263 * of the given 'client' from the 'last_client_replies' of the
1264 * given connected peer.
1266 * @param cls closure, the 'struct GNUNET_SERVER_Client*' to remove
1267 * @param key current key code (unused)
1268 * @param value value in the hash map (the 'struct ConnectedPeer*' to change)
1269 * @return GNUNET_YES (we should continue to iterate)
1272 remove_client_from_last_client_replies (void *cls,
1273 const GNUNET_HashCode * key,
1276 struct GNUNET_SERVER_Client *client = cls;
1277 struct ConnectedPeer *cp = value;
1280 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1282 if (cp->last_client_replies[i] == client)
1284 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1285 cp->last_client_replies[i] = NULL;
1293 * A client disconnected. Remove all of its pending queries.
1295 * @param cls closure, NULL
1296 * @param client identification of the client
1299 handle_client_disconnect (void *cls,
1300 struct GNUNET_SERVER_Client
1303 struct ClientList *pos;
1304 struct ClientList *prev;
1305 struct ClientRequestList *rcl;
1306 struct ClientResponseMessage *creply;
1312 while ( (NULL != pos) &&
1313 (pos->client != client) )
1319 return; /* no requests pending for this client */
1320 while (NULL != (rcl = pos->rl_head))
1322 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1323 "Destroying pending request `%s' on disconnect\n",
1324 GNUNET_h2s (&rcl->req->query));
1325 destroy_pending_request (rcl->req);
1328 client_list = pos->next;
1330 prev->next = pos->next;
1331 if (pos->th != NULL)
1333 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
1336 while (NULL != (creply = pos->res_head))
1338 GNUNET_CONTAINER_DLL_remove (pos->res_head,
1341 GNUNET_free (creply);
1343 GNUNET_SERVER_client_drop (pos->client);
1345 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1346 &remove_client_from_last_client_replies,
1352 * Iterator to free peer entries.
1354 * @param cls closure, unused
1355 * @param key current key code
1356 * @param value value in the hash map (peer entry)
1357 * @return GNUNET_YES (we should continue to iterate)
1360 clean_peer (void *cls,
1361 const GNUNET_HashCode * key,
1364 peer_disconnect_handler (NULL, (const struct GNUNET_PeerIdentity*) key);
1370 * Task run during shutdown.
1376 shutdown_task (void *cls,
1377 const struct GNUNET_SCHEDULER_TaskContext *tc)
1381 GNUNET_DATASTORE_cancel (mig_qe);
1384 if (GNUNET_SCHEDULER_NO_TASK != mig_task)
1386 GNUNET_SCHEDULER_cancel (sched, mig_task);
1387 mig_task = GNUNET_SCHEDULER_NO_TASK;
1389 while (client_list != NULL)
1390 handle_client_disconnect (NULL,
1391 client_list->client);
1392 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1395 GNUNET_break (0 == GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap));
1396 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
1397 requests_by_expiration_heap = 0;
1398 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
1399 connected_peers = NULL;
1400 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (query_request_map));
1401 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
1402 query_request_map = NULL;
1403 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (peer_request_map));
1404 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
1405 peer_request_map = NULL;
1406 GNUNET_assert (NULL != core);
1407 GNUNET_CORE_disconnect (core);
1411 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1414 GNUNET_DATASTORE_disconnect (dsh,
1416 while (mig_head != NULL)
1417 delete_migration_block (mig_head);
1418 GNUNET_assert (0 == mig_size);
1425 /* ******************* Utility functions ******************** */
1429 * Transmit messages by copying it to the target buffer
1430 * "buf". "buf" will be NULL and "size" zero if the socket was closed
1431 * for writing in the meantime. In that case, do nothing
1432 * (the disconnect or shutdown handler will take care of the rest).
1433 * If we were able to transmit messages and there are still more
1434 * pending, ask core again for further calls to this function.
1436 * @param cls closure, pointer to the 'struct ConnectedPeer*'
1437 * @param size number of bytes available in buf
1438 * @param buf where the callee should write the message
1439 * @return number of bytes written to buf
1442 transmit_to_peer (void *cls,
1443 size_t size, void *buf)
1445 struct ConnectedPeer *cp = cls;
1447 struct GNUNET_PeerIdentity pid;
1448 struct PendingMessage *pm;
1449 struct MigrationReadyBlock *mb;
1450 struct MigrationReadyBlock *next;
1451 struct PutMessage migm;
1459 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1460 "Dropping message, core too busy.\n");
1465 while ( (NULL != (pm = cp->pending_messages_head) ) &&
1466 (pm->msize <= size) )
1468 memcpy (&cbuf[msize], &pm[1], pm->msize);
1471 destroy_pending_message (pm, cp->pid);
1475 GNUNET_PEER_resolve (cp->pid,
1477 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1479 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1488 while (NULL != (mb = next))
1491 for (i=0;i<MIGRATION_LIST_SIZE;i++)
1493 if ( (cp->pid == mb->target_list[i]) &&
1494 (mb->size + sizeof (migm) <= size) )
1496 GNUNET_PEER_change_rc (mb->target_list[i], -1);
1497 mb->target_list[i] = 0;
1499 migm.header.size = htons (sizeof (migm) + mb->size);
1500 migm.header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
1501 migm.type = htonl (mb->type);
1502 migm.expiration = GNUNET_TIME_absolute_hton (mb->expiration);
1503 memcpy (&cbuf[msize], &migm, sizeof (migm));
1504 msize += sizeof (migm);
1505 size -= sizeof (migm);
1506 memcpy (&cbuf[msize], &mb[1], mb->size);
1510 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1511 "Pushing migration block `%s' (%u bytes) to `%s'\n",
1512 GNUNET_h2s (&mb->query),
1521 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1522 "Migration block `%s' (%u bytes) is not on migration list for peer `%s'\n",
1523 GNUNET_h2s (&mb->query),
1529 if ( (mb->used_targets >= MIGRATION_TARGET_COUNT) ||
1530 (mb->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers)) )
1532 delete_migration_block (mb);
1533 consider_migration_gathering ();
1536 consider_migration (NULL,
1541 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1542 "Transmitting %u bytes to peer %u\n",
1551 * Add a message to the set of pending messages for the given peer.
1553 * @param cp peer to send message to
1554 * @param pm message to queue
1555 * @param pr request on which behalf this message is being queued
1558 add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
1559 struct PendingMessage *pm,
1560 struct PendingRequest *pr)
1562 struct PendingMessage *pos;
1563 struct PendingMessageList *pml;
1564 struct GNUNET_PeerIdentity pid;
1566 GNUNET_assert (pm->next == NULL);
1567 GNUNET_assert (pm->pml == NULL);
1568 pml = GNUNET_malloc (sizeof (struct PendingMessageList));
1573 GNUNET_CONTAINER_DLL_insert (pr->pending_head,
1576 pos = cp->pending_messages_head;
1577 while ( (pos != NULL) &&
1578 (pm->priority < pos->priority) )
1580 GNUNET_CONTAINER_DLL_insert_after (cp->pending_messages_head,
1581 cp->pending_messages_tail,
1584 cp->pending_requests++;
1585 if (cp->pending_requests > MAX_QUEUE_PER_PEER)
1586 destroy_pending_message (cp->pending_messages_tail, 0);
1587 GNUNET_PEER_resolve (cp->pid, &pid);
1588 if (NULL != cp->cth)
1589 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
1590 /* need to schedule transmission */
1591 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1592 cp->pending_messages_head->priority,
1595 cp->pending_messages_head->msize,
1598 if (cp->cth == NULL)
1601 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1602 "Failed to schedule transmission with core!\n");
1604 /* FIXME: call stats (rare, bad case) */
1610 * Mingle hash with the mingle_number to produce different bits.
1613 mingle_hash (const GNUNET_HashCode * in,
1614 int32_t mingle_number,
1615 GNUNET_HashCode * hc)
1619 GNUNET_CRYPTO_hash (&mingle_number,
1622 GNUNET_CRYPTO_hash_xor (&m, in, hc);
1627 * Test if the load on this peer is too high
1628 * to even consider processing the query at
1631 * @return GNUNET_YES if the load is too high, GNUNET_NO otherwise
1634 test_load_too_high ()
1636 return GNUNET_NO; // FIXME
1640 /* ******************* Pending Request Refresh Task ******************** */
1645 * We use a random delay to make the timing of requests less
1646 * predictable. This function returns such a random delay. We add a base
1647 * delay of MAX_CORK_DELAY (1s).
1649 * FIXME: make schedule dependent on the specifics of the request?
1650 * Or bandwidth and number of connected peers and load?
1652 * @return random delay to use for some request, between 1s and 1000+TTL_DECREMENT ms
1654 static struct GNUNET_TIME_Relative
1655 get_processing_delay ()
1658 GNUNET_TIME_relative_add (GNUNET_CONSTANTS_MAX_CORK_DELAY,
1659 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1660 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1666 * We're processing a GET request from another peer and have decided
1667 * to forward it to other peers. This function is called periodically
1668 * and should forward the request to other peers until we have all
1669 * possible replies. If we have transmitted the *only* reply to
1670 * the initiator we should destroy the pending request. If we have
1671 * many replies in the queue to the initiator, we should delay sending
1672 * out more queries until the reply queue has shrunk some.
1674 * @param cls our "struct ProcessGetContext *"
1678 forward_request_task (void *cls,
1679 const struct GNUNET_SCHEDULER_TaskContext *tc);
1683 * Function called after we either failed or succeeded
1684 * at transmitting a query to a peer.
1686 * @param cls the requests "struct PendingRequest*"
1687 * @param tpid ID of receiving peer, 0 on transmission error
1690 transmit_query_continuation (void *cls,
1691 GNUNET_PEER_Id tpid)
1693 struct PendingRequest *pr = cls;
1695 GNUNET_STATISTICS_update (stats,
1696 gettext_noop ("# queries scheduled for forwarding"),
1702 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1703 "Transmission of request failed, will try again later.\n");
1705 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1706 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1707 get_processing_delay (),
1708 &forward_request_task,
1712 GNUNET_STATISTICS_update (stats,
1713 gettext_noop ("# queries forwarded"),
1716 GNUNET_PEER_change_rc (tpid, 1);
1717 if (pr->used_pids_off == pr->used_pids_size)
1718 GNUNET_array_grow (pr->used_pids,
1720 pr->used_pids_size * 2 + 2);
1721 pr->used_pids[pr->used_pids_off++] = tpid;
1722 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1723 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1724 get_processing_delay (),
1725 &forward_request_task,
1731 * How many bytes should a bloomfilter be if we have already seen
1732 * entry_count responses? Note that BLOOMFILTER_K gives us the number
1733 * of bits set per entry. Furthermore, we should not re-size the
1734 * filter too often (to keep it cheap).
1736 * Since other peers will also add entries but not resize the filter,
1737 * we should generally pick a slightly larger size than what the
1738 * strict math would suggest.
1740 * @return must be a power of two and smaller or equal to 2^15.
1743 compute_bloomfilter_size (unsigned int entry_count)
1746 unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
1747 uint16_t max = 1 << 15;
1749 if (entry_count > max)
1752 while ((size < max) && (size < ideal))
1761 * Recalculate our bloom filter for filtering replies. This function
1762 * will create a new bloom filter from scratch, so it should only be
1763 * called if we have no bloomfilter at all (and hence can create a
1764 * fresh one of minimal size without problems) OR if our peer is the
1765 * initiator (in which case we may resize to larger than mimimum size).
1767 * @param pr request for which the BF is to be recomputed
1770 refresh_bloomfilter (struct PendingRequest *pr)
1774 GNUNET_HashCode mhash;
1776 nsize = compute_bloomfilter_size (pr->replies_seen_off);
1777 if (nsize == pr->bf_size)
1778 return; /* size not changed */
1780 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
1781 pr->bf_size = nsize;
1782 pr->mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
1783 pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1786 for (i=0;i<pr->replies_seen_off;i++)
1788 mingle_hash (&pr->replies_seen[i], pr->mingle, &mhash);
1789 GNUNET_CONTAINER_bloomfilter_add (pr->bf, &mhash);
1795 * Function called after we've tried to reserve a certain amount of
1796 * bandwidth for a reply. Check if we succeeded and if so send our
1799 * @param cls the requests "struct PendingRequest*"
1800 * @param peer identifies the peer
1801 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1802 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1803 * @param amount set to the amount that was actually reserved or unreserved
1804 * @param preference current traffic preference for the given peer
1807 target_reservation_cb (void *cls,
1809 GNUNET_PeerIdentity * peer,
1810 struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
1811 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1813 uint64_t preference)
1815 struct PendingRequest *pr = cls;
1816 struct ConnectedPeer *cp;
1817 struct PendingMessage *pm;
1818 struct GetMessage *gm;
1819 GNUNET_HashCode *ext;
1829 /* error in communication with core, try again later */
1830 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1831 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1832 get_processing_delay (),
1833 &forward_request_task,
1837 // (3) transmit, update ttl/priority
1838 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1842 /* Peer must have just left */
1844 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1845 "Selected peer disconnected!\n");
1847 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1848 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1849 get_processing_delay (),
1850 &forward_request_task,
1854 no_route = GNUNET_NO;
1855 /* FIXME: check against DBLOCK_SIZE and possibly return
1856 amount to reserve; however, this also needs to work
1857 with testcases which currently start out with a far
1858 too low per-peer bw limit, so they would never send
1859 anything. Big issue. */
1865 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1866 "Failed to reserve bandwidth for reply (got %d/%u bytes only)!\n",
1870 GNUNET_STATISTICS_update (stats,
1871 gettext_noop ("# reply bandwidth reservation requests failed"),
1874 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1875 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1876 get_processing_delay (),
1877 &forward_request_task,
1879 return; /* this target round failed */
1881 /* FIXME: if we are "quite" busy, we may still want to skip
1882 this round; need more load detection code! */
1883 no_route = GNUNET_YES;
1886 GNUNET_STATISTICS_update (stats,
1887 gettext_noop ("# queries scheduled for forwarding"),
1890 /* build message and insert message into priority queue */
1892 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1893 "Forwarding request `%s' to `%4s'!\n",
1894 GNUNET_h2s (&pr->query),
1899 if (GNUNET_YES == no_route)
1901 bm |= GET_MESSAGE_BIT_RETURN_TO;
1904 if (pr->namespace != NULL)
1906 bm |= GET_MESSAGE_BIT_SKS_NAMESPACE;
1909 if (pr->target_pid != 0)
1911 bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
1914 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
1915 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1916 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1918 gm = (struct GetMessage*) &pm[1];
1919 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
1920 gm->header.size = htons (msize);
1921 gm->type = htonl (pr->type);
1922 pr->remaining_priority /= 2;
1923 gm->priority = htonl (pr->remaining_priority);
1924 gm->ttl = htonl (pr->ttl);
1925 gm->filter_mutator = htonl(pr->mingle);
1926 gm->hash_bitmap = htonl (bm);
1927 gm->query = pr->query;
1928 ext = (GNUNET_HashCode*) &gm[1];
1930 if (GNUNET_YES == no_route)
1931 GNUNET_PEER_resolve (pr->cp->pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1932 if (pr->namespace != NULL)
1933 memcpy (&ext[k++], pr->namespace, sizeof (GNUNET_HashCode));
1934 if (pr->target_pid != 0)
1935 GNUNET_PEER_resolve (pr->target_pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1936 bfdata = (char *) &ext[k];
1938 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
1941 pm->cont = &transmit_query_continuation;
1943 add_to_pending_messages_for_peer (cp, pm, pr);
1948 * Closure used for "target_peer_select_cb".
1950 struct PeerSelectionContext
1953 * The request for which we are selecting
1956 struct PendingRequest *pr;
1959 * Current "prime" target.
1961 struct GNUNET_PeerIdentity target;
1964 * How much do we like this target?
1966 double target_score;
1972 * Function called for each connected peer to determine
1973 * which one(s) would make good targets for forwarding.
1975 * @param cls closure (struct PeerSelectionContext)
1976 * @param key current key code (peer identity)
1977 * @param value value in the hash map (struct ConnectedPeer)
1978 * @return GNUNET_YES if we should continue to
1983 target_peer_select_cb (void *cls,
1984 const GNUNET_HashCode * key,
1987 struct PeerSelectionContext *psc = cls;
1988 struct ConnectedPeer *cp = value;
1989 struct PendingRequest *pr = psc->pr;
1994 /* 1) check that this peer is not the initiator */
1996 return GNUNET_YES; /* skip */
1998 /* 2) check if we have already (recently) forwarded to this peer */
2000 for (i=0;i<pr->used_pids_off;i++)
2001 if (pr->used_pids[i] == cp->pid)
2004 if (0 != GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2005 RETRY_PROBABILITY_INV))
2008 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2009 "NOT re-trying query that was previously transmitted %u times\n",
2010 (unsigned int) pr->used_pids_off);
2012 return GNUNET_YES; /* skip */
2017 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2018 "Re-trying query that was previously transmitted %u times to this peer\n",
2021 // 3) calculate how much we'd like to forward to this peer
2022 score = 42; // FIXME!
2023 // FIXME: also need API to gather data on responsiveness
2024 // of this peer (we have fields for that in 'cp', but
2025 // they are never set!)
2027 /* store best-fit in closure */
2028 if (score > psc->target_score)
2030 psc->target_score = score;
2031 psc->target.hashPubKey = *key;
2038 * The priority level imposes a bound on the maximum
2039 * value for the ttl that can be requested.
2041 * @param ttl_in requested ttl
2042 * @param prio given priority
2043 * @return ttl_in if ttl_in is below the limit,
2044 * otherwise the ttl-limit for the given priority
2047 bound_ttl (int32_t ttl_in, uint32_t prio)
2049 unsigned long long allowed;
2053 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
2054 if (ttl_in > allowed)
2056 if (allowed >= (1 << 30))
2065 * We're processing a GET request from another peer and have decided
2066 * to forward it to other peers. This function is called periodically
2067 * and should forward the request to other peers until we have all
2068 * possible replies. If we have transmitted the *only* reply to
2069 * the initiator we should destroy the pending request. If we have
2070 * many replies in the queue to the initiator, we should delay sending
2071 * out more queries until the reply queue has shrunk some.
2073 * @param cls our "struct ProcessGetContext *"
2077 forward_request_task (void *cls,
2078 const struct GNUNET_SCHEDULER_TaskContext *tc)
2080 struct PendingRequest *pr = cls;
2081 struct PeerSelectionContext psc;
2082 struct ConnectedPeer *cp;
2083 struct GNUNET_TIME_Relative delay;
2085 pr->task = GNUNET_SCHEDULER_NO_TASK;
2086 if (pr->irc != NULL)
2089 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2090 "Forwarding of query `%s' not attempted due to pending local lookup!\n",
2091 GNUNET_h2s (&pr->query));
2093 return; /* already pending */
2095 if (GNUNET_YES == pr->local_only)
2096 return; /* configured to not do P2P search */
2097 /* (1) select target */
2099 psc.target_score = DBL_MIN;
2100 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
2101 &target_peer_select_cb,
2103 if (psc.target_score == DBL_MIN)
2105 delay = get_processing_delay ();
2107 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2108 "No peer selected for forwarding of query `%s', will try again in %llu ms!\n",
2109 GNUNET_h2s (&pr->query),
2112 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
2114 &forward_request_task,
2116 return; /* nobody selected */
2118 /* (3) update TTL/priority */
2120 if (pr->client_request_list != NULL)
2122 /* FIXME: use better algorithm!? */
2123 if (0 == GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2126 /* FIXME: bound priority by "customary" priority used by other peers
2128 pr->ttl = bound_ttl (pr->ttl + TTL_DECREMENT * 2,
2131 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2132 "Trying query `%s' with priority %u and TTL %d.\n",
2133 GNUNET_h2s (&pr->query),
2140 /* FIXME: should we do something here as well!? */
2143 /* (3) reserve reply bandwidth */
2144 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2145 &psc.target.hashPubKey);
2146 GNUNET_assert (NULL != cp);
2147 pr->irc = GNUNET_CORE_peer_change_preference (sched, cfg,
2149 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
2150 GNUNET_BANDWIDTH_value_init ((uint32_t) -1 /* no limit */),
2152 (uint64_t) cp->inc_preference,
2153 &target_reservation_cb,
2155 cp->inc_preference = 0.0;
2159 /* **************************** P2P PUT Handling ************************ */
2163 * Function called after we either failed or succeeded
2164 * at transmitting a reply to a peer.
2166 * @param cls the requests "struct PendingRequest*"
2167 * @param tpid ID of receiving peer, 0 on transmission error
2170 transmit_reply_continuation (void *cls,
2171 GNUNET_PEER_Id tpid)
2173 struct PendingRequest *pr = cls;
2177 case GNUNET_BLOCK_TYPE_DBLOCK:
2178 case GNUNET_BLOCK_TYPE_IBLOCK:
2179 /* only one reply expected, done with the request! */
2180 destroy_pending_request (pr);
2182 case GNUNET_BLOCK_TYPE_ANY:
2183 case GNUNET_BLOCK_TYPE_KBLOCK:
2184 case GNUNET_BLOCK_TYPE_SBLOCK:
2194 * Transmit the given message by copying it to the target buffer
2195 * "buf". "buf" will be NULL and "size" zero if the socket was closed
2196 * for writing in the meantime. In that case, do nothing
2197 * (the disconnect or shutdown handler will take care of the rest).
2198 * If we were able to transmit messages and there are still more
2199 * pending, ask core again for further calls to this function.
2201 * @param cls closure, pointer to the 'struct ClientList*'
2202 * @param size number of bytes available in buf
2203 * @param buf where the callee should write the message
2204 * @return number of bytes written to buf
2207 transmit_to_client (void *cls,
2208 size_t size, void *buf)
2210 struct ClientList *cl = cls;
2212 struct ClientResponseMessage *creply;
2219 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2220 "Not sending reply, client communication problem.\n");
2225 while ( (NULL != (creply = cl->res_head) ) &&
2226 (creply->msize <= size) )
2228 memcpy (&cbuf[msize], &creply[1], creply->msize);
2229 msize += creply->msize;
2230 size -= creply->msize;
2231 GNUNET_CONTAINER_DLL_remove (cl->res_head,
2234 GNUNET_free (creply);
2237 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
2239 GNUNET_TIME_UNIT_FOREVER_REL,
2240 &transmit_to_client,
2243 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2244 "Transmitted %u bytes to client\n",
2245 (unsigned int) msize);
2252 * Closure for "process_reply" function.
2254 struct ProcessReplyClosure
2257 * The data for the reply.
2262 * Who gave us this reply? NULL for local host.
2264 struct ConnectedPeer *sender;
2267 * When the reply expires.
2269 struct GNUNET_TIME_Absolute expiration;
2277 * Namespace that this reply belongs to
2278 * (if it is of type SBLOCK).
2280 GNUNET_HashCode namespace;
2283 * Type of the block.
2285 enum GNUNET_BLOCK_Type type;
2288 * How much was this reply worth to us?
2293 * Did we finish processing the associated request?
2300 * We have received a reply; handle it!
2302 * @param cls response (struct ProcessReplyClosure)
2303 * @param key our query
2304 * @param value value in the hash map (info about the query)
2305 * @return GNUNET_YES (we should continue to iterate)
2308 process_reply (void *cls,
2309 const GNUNET_HashCode * key,
2312 struct ProcessReplyClosure *prq = cls;
2313 struct PendingRequest *pr = value;
2314 struct PendingMessage *reply;
2315 struct ClientResponseMessage *creply;
2316 struct ClientList *cl;
2317 struct PutMessage *pm;
2318 struct ConnectedPeer *cp;
2319 struct GNUNET_TIME_Relative cur_delay;
2320 GNUNET_HashCode chash;
2321 GNUNET_HashCode mhash;
2325 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2326 "Matched result (type %u) for query `%s' with pending request\n",
2327 (unsigned int) prq->type,
2330 GNUNET_STATISTICS_update (stats,
2331 gettext_noop ("# replies received and matched"),
2334 if (prq->sender != NULL)
2336 /* FIXME: should we be more precise here and not use
2337 "start_time" but a peer-specific time stamp? */
2338 cur_delay = GNUNET_TIME_absolute_get_duration (pr->start_time);
2339 prq->sender->avg_delay.value
2340 = (prq->sender->avg_delay.value *
2341 (RUNAVG_DELAY_N - 1) + cur_delay.value) / RUNAVG_DELAY_N;
2342 prq->sender->avg_priority
2343 = (prq->sender->avg_priority *
2344 (RUNAVG_DELAY_N - 1) + pr->priority) / (double) RUNAVG_DELAY_N;
2347 GNUNET_PEER_change_rc (prq->sender->last_p2p_replies
2348 [prq->sender->last_p2p_replies_woff % P2P_SUCCESS_LIST_SIZE], -1);
2349 GNUNET_PEER_change_rc (pr->cp->pid, 1);
2350 prq->sender->last_p2p_replies
2351 [(prq->sender->last_p2p_replies_woff++) % P2P_SUCCESS_LIST_SIZE]
2356 if (NULL != prq->sender->last_client_replies
2357 [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE])
2358 GNUNET_SERVER_client_drop (prq->sender->last_client_replies
2359 [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE]);
2360 prq->sender->last_client_replies
2361 [(prq->sender->last_client_replies_woff++) % CS2P_SUCCESS_LIST_SIZE]
2362 = pr->client_request_list->client_list->client;
2363 GNUNET_SERVER_client_keep (pr->client_request_list->client_list->client);
2366 GNUNET_CRYPTO_hash (prq->data,
2371 case GNUNET_BLOCK_TYPE_DBLOCK:
2372 case GNUNET_BLOCK_TYPE_IBLOCK:
2373 /* only possible reply, stop requesting! */
2374 while (NULL != pr->pending_head)
2375 destroy_pending_message_list_entry (pr->pending_head);
2378 if (pr->client_request_list != NULL)
2379 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
2381 GNUNET_DATASTORE_cancel (pr->qe);
2384 pr->do_remove = GNUNET_YES;
2385 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
2387 GNUNET_SCHEDULER_cancel (sched,
2389 pr->task = GNUNET_SCHEDULER_NO_TASK;
2391 GNUNET_break (GNUNET_YES ==
2392 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
2396 case GNUNET_BLOCK_TYPE_SBLOCK:
2397 if (pr->namespace == NULL)
2402 if (0 != memcmp (pr->namespace,
2404 sizeof (GNUNET_HashCode)))
2406 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2407 _("Reply mismatched in terms of namespace. Discarded.\n"));
2408 return GNUNET_YES; /* wrong namespace */
2410 /* then: fall-through! */
2411 case GNUNET_BLOCK_TYPE_KBLOCK:
2412 case GNUNET_BLOCK_TYPE_NBLOCK:
2415 mingle_hash (&chash, pr->mingle, &mhash);
2416 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
2419 GNUNET_STATISTICS_update (stats,
2420 gettext_noop ("# duplicate replies discarded (bloomfilter)"),
2424 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2425 "Duplicate response `%s', discarding.\n",
2426 GNUNET_h2s (&mhash));
2428 return GNUNET_YES; /* duplicate */
2431 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2432 "New response `%s', adding to filter.\n",
2433 GNUNET_h2s (&mhash));
2436 if (pr->client_request_list != NULL)
2438 if (pr->replies_seen_size == pr->replies_seen_off)
2439 GNUNET_array_grow (pr->replies_seen,
2440 pr->replies_seen_size,
2441 pr->replies_seen_size * 2 + 4);
2442 pr->replies_seen[pr->replies_seen_off++] = chash;
2444 if ( (pr->bf == NULL) ||
2445 (pr->client_request_list != NULL) )
2446 refresh_bloomfilter (pr);
2447 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
2454 prq->priority += pr->remaining_priority;
2455 pr->remaining_priority = 0;
2456 if (NULL != pr->client_request_list)
2458 GNUNET_STATISTICS_update (stats,
2459 gettext_noop ("# replies received for local clients"),
2462 cl = pr->client_request_list->client_list;
2463 msize = sizeof (struct PutMessage) + prq->size;
2464 creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
2465 creply->msize = msize;
2466 creply->client_list = cl;
2467 GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
2471 pm = (struct PutMessage*) &creply[1];
2472 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2473 pm->header.size = htons (msize);
2474 pm->type = htonl (prq->type);
2475 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
2476 memcpy (&pm[1], prq->data, prq->size);
2480 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2481 "Transmitting result for query `%s' to client\n",
2484 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
2486 GNUNET_TIME_UNIT_FOREVER_REL,
2487 &transmit_to_client,
2490 GNUNET_break (cl->th != NULL);
2493 prq->finished = GNUNET_YES;
2494 destroy_pending_request (pr);
2501 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2502 "Transmitting result for query `%s' to other peer (PID=%u)\n",
2504 (unsigned int) cp->pid);
2506 GNUNET_STATISTICS_update (stats,
2507 gettext_noop ("# replies received for other peers"),
2510 msize = sizeof (struct PutMessage) + prq->size;
2511 reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
2512 reply->cont = &transmit_reply_continuation;
2513 reply->cont_cls = pr;
2514 reply->msize = msize;
2515 reply->priority = (uint32_t) -1; /* send replies first! */
2516 pm = (struct PutMessage*) &reply[1];
2517 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2518 pm->header.size = htons (msize);
2519 pm->type = htonl (prq->type);
2520 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
2521 memcpy (&pm[1], prq->data, prq->size);
2522 add_to_pending_messages_for_peer (cp, reply, pr);
2529 * Continuation called to notify client about result of the
2532 * @param cls closure
2533 * @param success GNUNET_SYSERR on failure
2534 * @param msg NULL on success, otherwise an error message
2537 put_migration_continuation (void *cls,
2546 * Handle P2P "PUT" message.
2548 * @param cls closure, always NULL
2549 * @param other the other peer involved (sender or receiver, NULL
2550 * for loopback messages where we are both sender and receiver)
2551 * @param message the actual message
2552 * @param latency reported latency of the connection with 'other'
2553 * @param distance reported distance (DV) to 'other'
2554 * @return GNUNET_OK to keep the connection open,
2555 * GNUNET_SYSERR to close it (signal serious error)
2558 handle_p2p_put (void *cls,
2559 const struct GNUNET_PeerIdentity *other,
2560 const struct GNUNET_MessageHeader *message,
2561 struct GNUNET_TIME_Relative latency,
2564 const struct PutMessage *put;
2567 enum GNUNET_BLOCK_Type type;
2568 struct GNUNET_TIME_Absolute expiration;
2569 GNUNET_HashCode query;
2570 struct ProcessReplyClosure prq;
2571 const struct SBlock *sb;
2573 msize = ntohs (message->size);
2574 if (msize < sizeof (struct PutMessage))
2577 return GNUNET_SYSERR;
2579 put = (const struct PutMessage*) message;
2580 dsize = msize - sizeof (struct PutMessage);
2581 type = ntohl (put->type);
2582 expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
2585 GNUNET_BLOCK_check_block (type,
2590 GNUNET_break_op (0);
2591 return GNUNET_SYSERR;
2593 if (type == GNUNET_BLOCK_TYPE_ONDEMAND)
2594 return GNUNET_SYSERR;
2595 if (GNUNET_BLOCK_TYPE_SBLOCK == type)
2597 sb = (const struct SBlock*) &put[1];
2598 GNUNET_CRYPTO_hash (&sb->subspace,
2599 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2604 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2605 "Received result for query `%s' from peer `%4s'\n",
2606 GNUNET_h2s (&query),
2607 GNUNET_i2s (other));
2609 GNUNET_STATISTICS_update (stats,
2610 gettext_noop ("# replies received (overall)"),
2613 /* now, lookup 'query' */
2614 prq.data = (const void*) &put[1];
2616 prq.sender = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2617 &other->hashPubKey);
2620 prq.expiration = expiration;
2622 prq.finished = GNUNET_NO;
2623 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2627 if (GNUNET_YES == active_migration)
2630 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2631 "Replicating result for query `%s' with priority %u\n",
2632 GNUNET_h2s (&query),
2635 GNUNET_DATASTORE_put (dsh,
2636 0, &query, dsize, &put[1],
2637 type, prq.priority, 1 /* anonymity */,
2639 1 + prq.priority, MAX_DATASTORE_QUEUE,
2640 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
2641 &put_migration_continuation,
2648 /* **************************** P2P GET Handling ************************ */
2652 * Closure for 'check_duplicate_request_{peer,client}'.
2654 struct CheckDuplicateRequestClosure
2657 * The new request we should check if it already exists.
2659 const struct PendingRequest *pr;
2662 * Existing request found by the checker, NULL if none.
2664 struct PendingRequest *have;
2669 * Iterator over entries in the 'query_request_map' that
2670 * tries to see if we have the same request pending from
2671 * the same client already.
2673 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
2674 * @param key current key code (query, ignored, must match)
2675 * @param value value in the hash map (a 'struct PendingRequest'
2676 * that already exists)
2677 * @return GNUNET_YES if we should continue to
2678 * iterate (no match yet)
2679 * GNUNET_NO if not (match found).
2682 check_duplicate_request_client (void *cls,
2683 const GNUNET_HashCode * key,
2686 struct CheckDuplicateRequestClosure *cdc = cls;
2687 struct PendingRequest *have = value;
2689 if (have->client_request_list == NULL)
2691 if ( (cdc->pr->client_request_list->client_list->client == have->client_request_list->client_list->client) &&
2702 * We're processing (local) results for a search request
2703 * from another peer. Pass applicable results to the
2704 * peer and if we are done either clean up (operation
2705 * complete) or forward to other peers (more results possible).
2707 * @param cls our closure (struct LocalGetContext)
2708 * @param key key for the content
2709 * @param size number of bytes in data
2710 * @param data content stored
2711 * @param type type of the content
2712 * @param priority priority of the content
2713 * @param anonymity anonymity-level for the content
2714 * @param expiration expiration time for the content
2715 * @param uid unique identifier for the datum;
2716 * maybe 0 if no unique identifier is available
2719 process_local_reply (void *cls,
2720 const GNUNET_HashCode * key,
2723 enum GNUNET_BLOCK_Type type,
2726 struct GNUNET_TIME_Absolute
2730 struct PendingRequest *pr = cls;
2731 struct ProcessReplyClosure prq;
2732 struct CheckDuplicateRequestClosure cdrc;
2733 const struct SBlock *sb;
2734 GNUNET_HashCode dhash;
2735 GNUNET_HashCode mhash;
2736 GNUNET_HashCode query;
2741 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2742 "Done processing local replies, forwarding request to other peers.\n");
2745 if (pr->client_request_list != NULL)
2747 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
2749 /* Figure out if this is a duplicate request and possibly
2750 merge 'struct PendingRequest' entries */
2753 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2755 &check_duplicate_request_client,
2757 if (cdrc.have != NULL)
2760 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2761 "Received request for block `%s' twice from client, will only request once.\n",
2762 GNUNET_h2s (&pr->query));
2765 destroy_pending_request (pr);
2770 /* no more results */
2771 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2772 pr->task = GNUNET_SCHEDULER_add_now (sched,
2773 &forward_request_task,
2778 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2779 "New local response to `%s' of type %u.\n",
2783 if (type == GNUNET_BLOCK_TYPE_ONDEMAND)
2786 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2787 "Found ONDEMAND block, performing on-demand encoding\n");
2789 GNUNET_STATISTICS_update (stats,
2790 gettext_noop ("# on-demand blocks matched requests"),
2794 GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
2795 anonymity, expiration, uid,
2796 &process_local_reply,
2799 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2802 /* check for duplicates */
2803 GNUNET_CRYPTO_hash (data, size, &dhash);
2804 mingle_hash (&dhash,
2807 if ( (pr->bf != NULL) &&
2809 GNUNET_CONTAINER_bloomfilter_test (pr->bf,
2813 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2814 "Result from datastore filtered by bloomfilter (duplicate).\n");
2816 GNUNET_STATISTICS_update (stats,
2817 gettext_noop ("# results filtered by query bloomfilter"),
2821 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2825 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2826 "Found result for query `%s' in local datastore\n",
2829 GNUNET_STATISTICS_update (stats,
2830 gettext_noop ("# results found locally"),
2833 pr->results_found++;
2834 memset (&prq, 0, sizeof (prq));
2836 prq.expiration = expiration;
2838 if (GNUNET_BLOCK_TYPE_SBLOCK == type)
2840 sb = (const struct SBlock*) data;
2841 GNUNET_CRYPTO_hash (&sb->subspace,
2842 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2845 if (GNUNET_OK != GNUNET_BLOCK_check_block (type,
2851 GNUNET_DATASTORE_remove (dsh,
2855 GNUNET_TIME_UNIT_FOREVER_REL,
2857 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2861 prq.priority = priority;
2862 prq.finished = GNUNET_NO;
2863 process_reply (&prq, key, pr);
2864 if (prq.finished == GNUNET_YES)
2867 return; /* done here */
2868 if ( (type == GNUNET_BLOCK_TYPE_DBLOCK) ||
2869 (type == GNUNET_BLOCK_TYPE_IBLOCK) )
2871 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
2874 if ( (pr->client_request_list == NULL) &&
2875 ( (GNUNET_YES == test_load_too_high()) ||
2876 (pr->results_found > 5 + 2 * pr->priority) ) )
2879 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2880 "Load too high, done with request\n");
2882 GNUNET_STATISTICS_update (stats,
2883 gettext_noop ("# processing result set cut short due to load"),
2886 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
2889 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2894 * We've received a request with the specified priority. Bound it
2895 * according to how much we trust the given peer.
2897 * @param prio_in requested priority
2898 * @param cp the peer making the request
2899 * @return effective priority
2902 bound_priority (uint32_t prio_in,
2903 struct ConnectedPeer *cp)
2910 * Iterator over entries in the 'query_request_map' that
2911 * tries to see if we have the same request pending from
2912 * the same peer already.
2914 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
2915 * @param key current key code (query, ignored, must match)
2916 * @param value value in the hash map (a 'struct PendingRequest'
2917 * that already exists)
2918 * @return GNUNET_YES if we should continue to
2919 * iterate (no match yet)
2920 * GNUNET_NO if not (match found).
2923 check_duplicate_request_peer (void *cls,
2924 const GNUNET_HashCode * key,
2927 struct CheckDuplicateRequestClosure *cdc = cls;
2928 struct PendingRequest *have = value;
2930 if (cdc->pr->target_pid == have->target_pid)
2940 * Handle P2P "GET" request.
2942 * @param cls closure, always NULL
2943 * @param other the other peer involved (sender or receiver, NULL
2944 * for loopback messages where we are both sender and receiver)
2945 * @param message the actual message
2946 * @param latency reported latency of the connection with 'other'
2947 * @param distance reported distance (DV) to 'other'
2948 * @return GNUNET_OK to keep the connection open,
2949 * GNUNET_SYSERR to close it (signal serious error)
2952 handle_p2p_get (void *cls,
2953 const struct GNUNET_PeerIdentity *other,
2954 const struct GNUNET_MessageHeader *message,
2955 struct GNUNET_TIME_Relative latency,
2958 struct PendingRequest *pr;
2959 struct ConnectedPeer *cp;
2960 struct ConnectedPeer *cps;
2961 struct CheckDuplicateRequestClosure cdc;
2962 struct GNUNET_TIME_Relative timeout;
2964 const struct GetMessage *gm;
2966 const GNUNET_HashCode *opt;
2969 uint32_t ttl_decrement;
2970 enum GNUNET_BLOCK_Type type;
2974 msize = ntohs(message->size);
2975 if (msize < sizeof (struct GetMessage))
2977 GNUNET_break_op (0);
2978 return GNUNET_SYSERR;
2980 gm = (const struct GetMessage*) message;
2981 type = ntohl (gm->type);
2984 case GNUNET_BLOCK_TYPE_ANY:
2985 case GNUNET_BLOCK_TYPE_DBLOCK:
2986 case GNUNET_BLOCK_TYPE_IBLOCK:
2987 case GNUNET_BLOCK_TYPE_KBLOCK:
2988 case GNUNET_BLOCK_TYPE_SBLOCK:
2991 GNUNET_break_op (0);
2992 return GNUNET_SYSERR;
2994 bm = ntohl (gm->hash_bitmap);
3002 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
3004 GNUNET_break_op (0);
3005 return GNUNET_SYSERR;
3007 opt = (const GNUNET_HashCode*) &gm[1];
3008 bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
3009 bm = ntohl (gm->hash_bitmap);
3010 if ( (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)) &&
3011 (type != GNUNET_BLOCK_TYPE_SBLOCK) )
3013 GNUNET_break_op (0);
3014 return GNUNET_SYSERR;
3017 cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3018 &other->hashPubKey);
3021 /* peer must have just disconnected */
3022 GNUNET_STATISTICS_update (stats,
3023 gettext_noop ("# requests dropped due to initiator not being connected"),
3026 return GNUNET_SYSERR;
3028 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
3029 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3036 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
3037 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3038 "Failed to find RETURN-TO peer `%4s' in connection set. Dropping query.\n",
3039 GNUNET_i2s ((const struct GNUNET_PeerIdentity*) &opt[bits-1]));
3042 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3043 "Failed to find peer `%4s' in connection set. Dropping query.\n",
3044 GNUNET_i2s (other));
3046 GNUNET_STATISTICS_update (stats,
3047 gettext_noop ("# requests dropped due to missing reverse route"),
3050 /* FIXME: try connect? */
3053 /* note that we can really only check load here since otherwise
3054 peers could find out that we are overloaded by not being
3055 disconnected after sending us a malformed query... */
3056 if (GNUNET_YES == test_load_too_high ())
3059 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3060 "Dropping query from `%s', this peer is too busy.\n",
3061 GNUNET_i2s (other));
3063 GNUNET_STATISTICS_update (stats,
3064 gettext_noop ("# requests dropped due to high load"),
3071 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3072 "Received request for `%s' of type %u from peer `%4s' with flags %u\n",
3073 GNUNET_h2s (&gm->query),
3074 (unsigned int) type,
3078 have_ns = (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE));
3079 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
3080 (have_ns ? sizeof(GNUNET_HashCode) : 0));
3082 pr->namespace = (GNUNET_HashCode*) &pr[1];
3084 pr->mingle = ntohl (gm->filter_mutator);
3085 if (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
3086 memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
3087 if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
3088 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
3090 pr->anonymity_level = 1;
3091 pr->priority = bound_priority (ntohl (gm->priority), cps);
3092 pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
3093 pr->query = gm->query;
3094 /* decrement ttl (always) */
3095 ttl_decrement = 2 * TTL_DECREMENT +
3096 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3098 if ( (pr->ttl < 0) &&
3099 (((int32_t)(pr->ttl - ttl_decrement)) > 0) )
3102 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3103 "Dropping query from `%s' due to TTL underflow (%d - %u).\n",
3108 GNUNET_STATISTICS_update (stats,
3109 gettext_noop ("# requests dropped due TTL underflow"),
3112 /* integer underflow => drop (should be very rare)! */
3116 pr->ttl -= ttl_decrement;
3117 pr->start_time = GNUNET_TIME_absolute_get ();
3119 /* get bloom filter */
3122 pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
3125 pr->bf_size = bfsize;
3130 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
3132 &check_duplicate_request_peer,
3134 if (cdc.have != NULL)
3136 if (cdc.have->start_time.value + cdc.have->ttl >=
3137 pr->start_time.value + pr->ttl)
3139 /* existing request has higher TTL, drop new one! */
3140 cdc.have->priority += pr->priority;
3141 destroy_pending_request (pr);
3143 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3144 "Have existing request with higher TTL, dropping new request.\n",
3145 GNUNET_i2s (other));
3147 GNUNET_STATISTICS_update (stats,
3148 gettext_noop ("# requests dropped due to higher-TTL request"),
3155 /* existing request has lower TTL, drop old one! */
3156 pr->priority += cdc.have->priority;
3157 /* Possible optimization: if we have applicable pending
3158 replies in 'cdc.have', we might want to move those over
3159 (this is a really rare special-case, so it is not clear
3160 that this would be worth it) */
3161 destroy_pending_request (cdc.have);
3162 /* keep processing 'pr'! */
3167 GNUNET_break (GNUNET_OK ==
3168 GNUNET_CONTAINER_multihashmap_put (query_request_map,
3171 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
3172 GNUNET_break (GNUNET_OK ==
3173 GNUNET_CONTAINER_multihashmap_put (peer_request_map,
3176 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
3178 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
3180 pr->start_time.value + pr->ttl);
3182 GNUNET_STATISTICS_update (stats,
3183 gettext_noop ("# P2P searches received"),
3186 GNUNET_STATISTICS_update (stats,
3187 gettext_noop ("# P2P searches active"),
3191 /* calculate change in traffic preference */
3192 preference = (double) pr->priority;
3193 if (preference < QUERY_BANDWIDTH_VALUE)
3194 preference = QUERY_BANDWIDTH_VALUE;
3195 cps->inc_preference += preference;
3197 /* process locally */
3198 if (type == GNUNET_BLOCK_TYPE_DBLOCK)
3199 type = GNUNET_BLOCK_TYPE_ANY; /* to get on-demand as well */
3200 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
3201 (pr->priority + 1));
3202 pr->qe = GNUNET_DATASTORE_get (dsh,
3206 MAX_DATASTORE_QUEUE,
3208 &process_local_reply,
3211 /* Are multiple results possible? If so, start processing remotely now! */
3214 case GNUNET_BLOCK_TYPE_DBLOCK:
3215 case GNUNET_BLOCK_TYPE_IBLOCK:
3216 /* only one result, wait for datastore */
3219 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
3220 pr->task = GNUNET_SCHEDULER_add_now (sched,
3221 &forward_request_task,
3225 /* make sure we don't track too many requests */
3226 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
3228 pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
3229 destroy_pending_request (pr);
3235 /* **************************** CS GET Handling ************************ */
3239 * Handle START_SEARCH-message (search request from client).
3241 * @param cls closure
3242 * @param client identification of the client
3243 * @param message the actual message
3246 handle_start_search (void *cls,
3247 struct GNUNET_SERVER_Client *client,
3248 const struct GNUNET_MessageHeader *message)
3250 static GNUNET_HashCode all_zeros;
3251 const struct SearchMessage *sm;
3252 struct ClientList *cl;
3253 struct ClientRequestList *crl;
3254 struct PendingRequest *pr;
3257 enum GNUNET_BLOCK_Type type;
3259 msize = ntohs (message->size);
3260 if ( (msize < sizeof (struct SearchMessage)) ||
3261 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
3264 GNUNET_SERVER_receive_done (client,
3268 GNUNET_STATISTICS_update (stats,
3269 gettext_noop ("# client searches received"),
3272 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
3273 sm = (const struct SearchMessage*) message;
3274 type = ntohl (sm->type);
3276 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3277 "Received request for `%s' of type %u from local client\n",
3278 GNUNET_h2s (&sm->query),
3279 (unsigned int) type);
3283 case GNUNET_BLOCK_TYPE_ANY:
3284 case GNUNET_BLOCK_TYPE_DBLOCK:
3285 case GNUNET_BLOCK_TYPE_IBLOCK:
3286 case GNUNET_BLOCK_TYPE_KBLOCK:
3287 case GNUNET_BLOCK_TYPE_SBLOCK:
3288 case GNUNET_BLOCK_TYPE_NBLOCK:
3292 GNUNET_SERVER_receive_done (client,
3298 while ( (cl != NULL) &&
3299 (cl->client != client) )
3303 cl = GNUNET_malloc (sizeof (struct ClientList));
3304 cl->client = client;
3305 GNUNET_SERVER_client_keep (client);
3306 cl->next = client_list;
3309 /* detect duplicate KBLOCK requests */
3310 if ( (type == GNUNET_BLOCK_TYPE_KBLOCK) ||
3311 (type == GNUNET_BLOCK_TYPE_NBLOCK) ||
3312 (type == GNUNET_BLOCK_TYPE_ANY) )
3315 while ( (crl != NULL) &&
3316 ( (0 != memcmp (&crl->req->query,
3318 sizeof (GNUNET_HashCode))) ||
3319 (crl->req->type != type) ) )
3324 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3325 "Have existing request, merging content-seen lists.\n");
3328 /* Duplicate request (used to send long list of
3329 known/blocked results); merge 'pr->replies_seen'
3330 and update bloom filter */
3331 GNUNET_array_grow (pr->replies_seen,
3332 pr->replies_seen_size,
3333 pr->replies_seen_off + sc);
3334 memcpy (&pr->replies_seen[pr->replies_seen_off],
3336 sc * sizeof (GNUNET_HashCode));
3337 pr->replies_seen_off += sc;
3338 refresh_bloomfilter (pr);
3339 GNUNET_STATISTICS_update (stats,
3340 gettext_noop ("# client searches updated (merged content seen list)"),
3343 GNUNET_SERVER_receive_done (client,
3348 GNUNET_STATISTICS_update (stats,
3349 gettext_noop ("# client searches active"),
3352 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
3353 ((type == GNUNET_BLOCK_TYPE_SBLOCK) ? sizeof(GNUNET_HashCode) : 0));
3354 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
3355 memset (crl, 0, sizeof (struct ClientRequestList));
3356 crl->client_list = cl;
3357 GNUNET_CONTAINER_DLL_insert (cl->rl_head,
3362 pr->client_request_list = crl;
3363 GNUNET_array_grow (pr->replies_seen,
3364 pr->replies_seen_size,
3366 memcpy (pr->replies_seen,
3368 sc * sizeof (GNUNET_HashCode));
3369 pr->replies_seen_off = sc;
3370 pr->anonymity_level = ntohl (sm->anonymity_level);
3371 refresh_bloomfilter (pr);
3372 pr->query = sm->query;
3373 if (0 == (1 & ntohl (sm->options)))
3374 pr->local_only = GNUNET_NO;
3376 pr->local_only = GNUNET_YES;
3379 case GNUNET_BLOCK_TYPE_DBLOCK:
3380 case GNUNET_BLOCK_TYPE_IBLOCK:
3381 if (0 != memcmp (&sm->target,
3383 sizeof (GNUNET_HashCode)))
3384 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
3386 case GNUNET_BLOCK_TYPE_SBLOCK:
3387 pr->namespace = (GNUNET_HashCode*) &pr[1];
3388 memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
3393 GNUNET_break (GNUNET_OK ==
3394 GNUNET_CONTAINER_multihashmap_put (query_request_map,
3397 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
3398 if (type == GNUNET_BLOCK_TYPE_DBLOCK)
3399 type = GNUNET_BLOCK_TYPE_ANY; /* get on-demand blocks too! */
3400 pr->qe = GNUNET_DATASTORE_get (dsh,
3404 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
3405 &process_local_reply,
3410 /* **************************** Startup ************************ */
3414 * List of handlers for P2P messages
3415 * that we care about.
3417 static struct GNUNET_CORE_MessageHandler p2p_handlers[] =
3420 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
3422 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
3428 * List of handlers for the messages understood by this
3431 static struct GNUNET_SERVER_MessageHandler handlers[] = {
3432 {&GNUNET_FS_handle_index_start, NULL,
3433 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
3434 {&GNUNET_FS_handle_index_list_get, NULL,
3435 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
3436 {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
3437 sizeof (struct UnindexMessage) },
3438 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
3445 * Process fs requests.
3447 * @param s scheduler to use
3448 * @param server the initialized server
3449 * @param c configuration to use
3452 main_init (struct GNUNET_SCHEDULER_Handle *s,
3453 struct GNUNET_SERVER_Handle *server,
3454 const struct GNUNET_CONFIGURATION_Handle *c)
3458 stats = GNUNET_STATISTICS_create (sched, "fs", cfg);
3459 min_migration_delay = GNUNET_TIME_UNIT_SECONDS; // FIXME: get from config
3460 connected_peers = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3461 query_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3462 peer_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3463 requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
3464 core = GNUNET_CORE_connect (sched,
3466 GNUNET_TIME_UNIT_FOREVER_REL,
3469 &peer_connect_handler,
3470 &peer_disconnect_handler,
3476 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3477 _("Failed to connect to `%s' service.\n"),
3479 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
3480 connected_peers = NULL;
3481 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
3482 query_request_map = NULL;
3483 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
3484 requests_by_expiration_heap = NULL;
3485 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
3486 peer_request_map = NULL;
3489 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
3492 return GNUNET_SYSERR;
3494 /* FIXME: distinguish between sending and storing in options? */
3495 if (active_migration)
3497 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3498 _("Content migration is enabled, will start to gather data\n"));
3499 consider_migration_gathering ();
3501 GNUNET_SERVER_disconnect_notify (server,
3502 &handle_client_disconnect,
3504 GNUNET_SERVER_add_handlers (server, handlers);
3505 GNUNET_SCHEDULER_add_delayed (sched,
3506 GNUNET_TIME_UNIT_FOREVER_REL,
3514 * Process fs requests.
3516 * @param cls closure
3517 * @param sched scheduler to use
3518 * @param server the initialized server
3519 * @param cfg configuration to use
3523 struct GNUNET_SCHEDULER_Handle *sched,
3524 struct GNUNET_SERVER_Handle *server,
3525 const struct GNUNET_CONFIGURATION_Handle *cfg)
3527 active_migration = GNUNET_CONFIGURATION_get_value_yesno (cfg,
3530 dsh = GNUNET_DATASTORE_connect (cfg,
3534 GNUNET_SCHEDULER_shutdown (sched);
3537 if ( (GNUNET_OK != GNUNET_FS_indexing_init (sched, cfg, dsh)) ||
3538 (GNUNET_OK != main_init (sched, server, cfg)) )
3540 GNUNET_SCHEDULER_shutdown (sched);
3541 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
3549 * The main function for the fs service.
3551 * @param argc number of arguments from the command line
3552 * @param argv command line arguments
3553 * @return 0 ok, 1 on error
3556 main (int argc, char *const *argv)
3558 return (GNUNET_OK ==
3559 GNUNET_SERVICE_run (argc,
3562 GNUNET_SERVICE_OPTION_NONE,
3563 &run, NULL)) ? 0 : 1;
3566 /* end of gnunet-service-fs.c */