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 3, 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 * - trust not properly received and pushed back to peerinfo!
28 * - bound_priority by priorities used by other peers
29 * - have a way to drop queries based on load
30 * - introduce random latency in processing
31 * - consider more precise latency estimation (per-peer & request)
32 * - better algorithm for priority selection for requests we initiate?
33 * - tell other peers to stop migration if our PUTs fail (or if
34 * we don't support migration per configuration?)
39 #include "gnunet_constants.h"
40 #include "gnunet_core_service.h"
41 #include "gnunet_datastore_service.h"
42 #include "gnunet_peer_lib.h"
43 #include "gnunet_protocols.h"
44 #include "gnunet_signatures.h"
45 #include "gnunet_statistics_service.h"
46 #include "gnunet_util_lib.h"
47 #include "gnunet-service-fs_indexing.h"
50 #define DEBUG_FS GNUNET_NO
53 * Maximum number of outgoing messages we queue per peer.
55 #define MAX_QUEUE_PER_PEER 16
58 * Inverse of the probability that we will submit the same query
59 * to the same peer again. If the same peer already got the query
60 * repeatedly recently, the probability is multiplied by the inverse
61 * of this number each time. Note that we only try about every TTL_DECREMENT/2
62 * plus MAX_CORK_DELAY (so roughly every 3.5s).
64 #define RETRY_PROBABILITY_INV 3
67 * What is the maximum delay for a P2P FS message (in our interaction
68 * with core)? FS-internal delays are another story. The value is
69 * chosen based on the 32k block size. Given that peers typcially
70 * have at least 1 kb/s bandwidth, 45s waits give us a chance to
71 * transmit one message even to the lowest-bandwidth peers.
73 #define MAX_TRANSMIT_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 45)
78 * Maximum number of requests (from other peers) that we're
79 * willing to have pending at any given point in time.
80 * FIXME: set from configuration.
82 static uint64_t max_pending_requests = (32 * 1024);
86 * Information we keep for each pending reply. The
87 * actual message follows at the end of this struct.
89 struct PendingMessage;
92 * Our connection to the datastore.
94 static struct GNUNET_DATASTORE_Handle *dsh;
98 * Function called upon completion of a transmission.
101 * @param pid ID of receiving peer, 0 on transmission error
103 typedef void (*TransmissionContinuation)(void * cls,
104 GNUNET_PEER_Id tpid);
108 * Information we keep for each pending message (GET/PUT). The
109 * actual message follows at the end of this struct.
111 struct PendingMessage
114 * This is a doubly-linked list of messages to the same peer.
116 struct PendingMessage *next;
119 * This is a doubly-linked list of messages to the same peer.
121 struct PendingMessage *prev;
124 * Entry in pending message list for this pending message.
126 struct PendingMessageList *pml;
129 * Function to call immediately once we have transmitted this
132 TransmissionContinuation cont;
140 * Size of the reply; actual reply message follows
141 * at the end of this struct.
146 * How important is this message for us?
154 * Information about a peer that we are connected to.
155 * We track data that is useful for determining which
156 * peers should receive our requests. We also keep
157 * a list of messages to transmit to this peer.
163 * List of the last clients for which this peer successfully
166 struct GNUNET_SERVER_Client *last_client_replies[CS2P_SUCCESS_LIST_SIZE];
169 * List of the last PIDs for which
170 * this peer successfully answered a query;
171 * We use 0 to indicate no successful reply.
173 GNUNET_PEER_Id last_p2p_replies[P2P_SUCCESS_LIST_SIZE];
176 * Average delay between sending the peer a request and
177 * getting a reply (only calculated over the requests for
178 * which we actually got a reply). Calculated
179 * as a moving average: new_delay = ((n-1)*last_delay+curr_delay) / n
181 struct GNUNET_TIME_Relative avg_delay;
184 * Handle for an active request for transmission to this
187 struct GNUNET_CORE_TransmitHandle *cth;
190 * Messages (replies, queries, content migration) we would like to
191 * send to this peer in the near future. Sorted by priority, head.
193 struct PendingMessage *pending_messages_head;
196 * Messages (replies, queries, content migration) we would like to
197 * send to this peer in the near future. Sorted by priority, tail.
199 struct PendingMessage *pending_messages_tail;
202 * Average priority of successful replies. Calculated
203 * as a moving average: new_avg = ((n-1)*last_avg+curr_prio) / n
208 * Increase in traffic preference still to be submitted
209 * to the core service for this peer.
211 uint64_t inc_preference;
214 * Trust delta to still commit to the system.
216 uint32_t trust_delta;
219 * The peer's identity.
224 * Size of the linked list of 'pending_messages'.
226 unsigned int pending_requests;
229 * Which offset in "last_p2p_replies" will be updated next?
230 * (we go round-robin).
232 unsigned int last_p2p_replies_woff;
235 * Which offset in "last_client_replies" will be updated next?
236 * (we go round-robin).
238 unsigned int last_client_replies_woff;
244 * Information we keep for each pending request. We should try to
245 * keep this struct as small as possible since its memory consumption
246 * is key to how many requests we can have pending at once.
248 struct PendingRequest;
252 * Doubly-linked list of requests we are performing
253 * on behalf of the same client.
255 struct ClientRequestList
259 * This is a doubly-linked list.
261 struct ClientRequestList *next;
264 * This is a doubly-linked list.
266 struct ClientRequestList *prev;
269 * Request this entry represents.
271 struct PendingRequest *req;
274 * Client list this request belongs to.
276 struct ClientList *client_list;
282 * Replies to be transmitted to the client. The actual
283 * response message is allocated after this struct.
285 struct ClientResponseMessage
288 * This is a doubly-linked list.
290 struct ClientResponseMessage *next;
293 * This is a doubly-linked list.
295 struct ClientResponseMessage *prev;
298 * Client list entry this response belongs to.
300 struct ClientList *client_list;
303 * Number of bytes in the response.
310 * Linked list of clients we are performing requests
316 * This is a linked list.
318 struct ClientList *next;
321 * ID of a client making a request, NULL if this entry is for a
324 struct GNUNET_SERVER_Client *client;
327 * Head of list of requests performed on behalf
328 * of this client right now.
330 struct ClientRequestList *rl_head;
333 * Tail of list of requests performed on behalf
334 * of this client right now.
336 struct ClientRequestList *rl_tail;
339 * Head of linked list of responses.
341 struct ClientResponseMessage *res_head;
344 * Tail of linked list of responses.
346 struct ClientResponseMessage *res_tail;
349 * Context for sending replies.
351 struct GNUNET_CONNECTION_TransmitHandle *th;
357 * Doubly-linked list of messages we are performing
358 * due to a pending request.
360 struct PendingMessageList
364 * This is a doubly-linked list of messages on behalf of the same request.
366 struct PendingMessageList *next;
369 * This is a doubly-linked list of messages on behalf of the same request.
371 struct PendingMessageList *prev;
374 * Message this entry represents.
376 struct PendingMessage *pm;
379 * Request this entry belongs to.
381 struct PendingRequest *req;
384 * Peer this message is targeted for.
386 struct ConnectedPeer *target;
392 * Information we keep for each pending request. We should try to
393 * keep this struct as small as possible since its memory consumption
394 * is key to how many requests we can have pending at once.
396 struct PendingRequest
400 * If this request was made by a client, this is our entry in the
401 * client request list; otherwise NULL.
403 struct ClientRequestList *client_request_list;
406 * Entry of peer responsible for this entry (if this request
407 * was made by a peer).
409 struct ConnectedPeer *cp;
412 * If this is a namespace query, pointer to the hash of the public
413 * key of the namespace; otherwise NULL. Pointer will be to the
414 * end of this struct (so no need to free it).
416 const GNUNET_HashCode *namespace;
419 * Bloomfilter we use to filter out replies that we don't care about
420 * (anymore). NULL as long as we are interested in all replies.
422 struct GNUNET_CONTAINER_BloomFilter *bf;
425 * Context of our GNUNET_CORE_peer_change_preference call.
427 struct GNUNET_CORE_InformationRequestContext *irc;
430 * Hash code of all replies that we have seen so far (only valid
431 * if client is not NULL since we only track replies like this for
434 GNUNET_HashCode *replies_seen;
437 * Node in the heap representing this entry; NULL
438 * if we have no heap node.
440 struct GNUNET_CONTAINER_HeapNode *hnode;
443 * Head of list of messages being performed on behalf of this
446 struct PendingMessageList *pending_head;
449 * Tail of list of messages being performed on behalf of this
452 struct PendingMessageList *pending_tail;
455 * When did we first see this request (form this peer), or, if our
456 * client is initiating, when did we last initiate a search?
458 struct GNUNET_TIME_Absolute start_time;
461 * The query that this request is for.
463 GNUNET_HashCode query;
466 * The task responsible for transmitting queries
469 GNUNET_SCHEDULER_TaskIdentifier task;
472 * (Interned) Peer identifier that identifies a preferred target
475 GNUNET_PEER_Id target_pid;
478 * (Interned) Peer identifiers of peers that have already
479 * received our query for this content.
481 GNUNET_PEER_Id *used_pids;
484 * Our entry in the queue (non-NULL while we wait for our
485 * turn to interact with the local database).
487 struct GNUNET_DATASTORE_QueueEntry *qe;
490 * Size of the 'bf' (in bytes).
495 * Desired anonymity level; only valid for requests from a local client.
497 uint32_t anonymity_level;
500 * How many entries in "used_pids" are actually valid?
502 unsigned int used_pids_off;
505 * How long is the "used_pids" array?
507 unsigned int used_pids_size;
510 * Number of results found for this request.
512 unsigned int results_found;
515 * How many entries in "replies_seen" are actually valid?
517 unsigned int replies_seen_off;
520 * How long is the "replies_seen" array?
522 unsigned int replies_seen_size;
525 * Priority with which this request was made. If one of our clients
526 * made the request, then this is the current priority that we are
527 * using when initiating the request. This value is used when
528 * we decide to reward other peers with trust for providing a reply.
533 * Priority points left for us to spend when forwarding this request
536 uint32_t remaining_priority;
539 * Number to mingle hashes for bloom-filter tests with.
544 * TTL with which we saw this request (or, if we initiated, TTL that
545 * we used for the request).
550 * Type of the content that this request is for.
552 enum GNUNET_BLOCK_Type type;
555 * Remove this request after transmission of the current response.
560 * GNUNET_YES if we should not forward this request to other peers.
568 * Block that is ready for migration to other peers. Actual data is at the end of the block.
570 struct MigrationReadyBlock
574 * This is a doubly-linked list.
576 struct MigrationReadyBlock *next;
579 * This is a doubly-linked list.
581 struct MigrationReadyBlock *prev;
584 * Query for the block.
586 GNUNET_HashCode query;
589 * When does this block expire?
591 struct GNUNET_TIME_Absolute expiration;
594 * Peers we would consider forwarding this
595 * block to. Zero for empty entries.
597 GNUNET_PEER_Id target_list[MIGRATION_LIST_SIZE];
605 * Number of targets already used.
607 unsigned int used_targets;
612 enum GNUNET_BLOCK_Type type;
619 static struct GNUNET_SCHEDULER_Handle *sched;
624 static const struct GNUNET_CONFIGURATION_Handle *cfg;
627 * Map of peer identifiers to "struct ConnectedPeer" (for that peer).
629 static struct GNUNET_CONTAINER_MultiHashMap *connected_peers;
632 * Map of peer identifiers to "struct PendingRequest" (for that peer).
634 static struct GNUNET_CONTAINER_MultiHashMap *peer_request_map;
637 * Map of query identifiers to "struct PendingRequest" (for that query).
639 static struct GNUNET_CONTAINER_MultiHashMap *query_request_map;
642 * Heap with the request that will expire next at the top. Contains
643 * pointers of type "struct PendingRequest*"; these will *also* be
644 * aliased from the "requests_by_peer" data structures and the
645 * "requests_by_query" table. Note that requests from our clients
646 * don't expire and are thus NOT in the "requests_by_expiration"
647 * (or the "requests_by_peer" tables).
649 static struct GNUNET_CONTAINER_Heap *requests_by_expiration_heap;
652 * Handle for reporting statistics.
654 static struct GNUNET_STATISTICS_Handle *stats;
657 * Linked list of clients we are currently processing requests for.
659 static struct ClientList *client_list;
662 * Pointer to handle to the core service (points to NULL until we've
665 static struct GNUNET_CORE_Handle *core;
668 * Head of linked list of blocks that can be migrated.
670 static struct MigrationReadyBlock *mig_head;
673 * Tail of linked list of blocks that can be migrated.
675 static struct MigrationReadyBlock *mig_tail;
678 * Request to datastore for migration (or NULL).
680 static struct GNUNET_DATASTORE_QueueEntry *mig_qe;
683 * ID of task that collects blocks for migration.
685 static GNUNET_SCHEDULER_TaskIdentifier mig_task;
688 * What is the maximum frequency at which we are allowed to
689 * poll the datastore for migration content?
691 static struct GNUNET_TIME_Relative min_migration_delay;
694 * Size of the doubly-linked list of migration blocks.
696 static unsigned int mig_size;
699 * Are we allowed to migrate content to this peer.
701 static int active_migration;
705 * Transmit messages by copying it to the target buffer
706 * "buf". "buf" will be NULL and "size" zero if the socket was closed
707 * for writing in the meantime. In that case, do nothing
708 * (the disconnect or shutdown handler will take care of the rest).
709 * If we were able to transmit messages and there are still more
710 * pending, ask core again for further calls to this function.
712 * @param cls closure, pointer to the 'struct ConnectedPeer*'
713 * @param size number of bytes available in buf
714 * @param buf where the callee should write the message
715 * @return number of bytes written to buf
718 transmit_to_peer (void *cls,
719 size_t size, void *buf);
722 /* ******************* clean up functions ************************ */
726 * Delete the given migration block.
728 * @param mb block to delete
731 delete_migration_block (struct MigrationReadyBlock *mb)
733 GNUNET_CONTAINER_DLL_remove (mig_head,
736 GNUNET_PEER_decrement_rcs (mb->target_list,
737 MIGRATION_LIST_SIZE);
744 * Compare the distance of two peers to a key.
747 * @param p1 first peer
748 * @param p2 second peer
749 * @return GNUNET_YES if P1 is closer to key than P2
752 is_closer (const GNUNET_HashCode *key,
753 const struct GNUNET_PeerIdentity *p1,
754 const struct GNUNET_PeerIdentity *p2)
756 return GNUNET_CRYPTO_hash_xorcmp (&p1->hashPubKey,
763 * Consider migrating content to a given peer.
765 * @param cls 'struct MigrationReadyBlock*' to select
766 * targets for (or NULL for none)
767 * @param key ID of the peer
768 * @param value 'struct ConnectedPeer' of the peer
769 * @return GNUNET_YES (always continue iteration)
772 consider_migration (void *cls,
773 const GNUNET_HashCode *key,
776 struct MigrationReadyBlock *mb = cls;
777 struct ConnectedPeer *cp = value;
778 struct MigrationReadyBlock *pos;
779 struct GNUNET_PeerIdentity cppid;
780 struct GNUNET_PeerIdentity otherpid;
781 struct GNUNET_PeerIdentity worstpid;
786 /* consider 'cp' as a migration target for mb */
789 GNUNET_PEER_resolve (cp->pid,
791 repl = MIGRATION_LIST_SIZE;
792 for (i=0;i<MIGRATION_LIST_SIZE;i++)
794 if (mb->target_list[i] == 0)
796 mb->target_list[i] = cp->pid;
797 GNUNET_PEER_change_rc (mb->target_list[i], 1);
798 repl = MIGRATION_LIST_SIZE;
801 GNUNET_PEER_resolve (mb->target_list[i],
803 if ( (repl == MIGRATION_LIST_SIZE) &&
804 is_closer (&mb->query,
811 else if ( (repl != MIGRATION_LIST_SIZE) &&
812 (is_closer (&mb->query,
820 if (repl != MIGRATION_LIST_SIZE)
822 GNUNET_PEER_change_rc (mb->target_list[repl], -1);
823 mb->target_list[repl] = cp->pid;
824 GNUNET_PEER_change_rc (mb->target_list[repl], 1);
828 /* consider scheduling transmission to cp for content migration */
835 for (i=0;i<MIGRATION_LIST_SIZE;i++)
837 if (cp->pid == pos->target_list[i])
842 msize = GNUNET_MIN (msize,
850 return GNUNET_YES; /* no content available */
852 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
853 "Trying to migrate at least %u bytes to peer `%s'\n",
858 = GNUNET_CORE_notify_transmit_ready (core,
859 0, GNUNET_TIME_UNIT_FOREVER_REL,
860 (const struct GNUNET_PeerIdentity*) key,
861 msize + sizeof (struct PutMessage),
869 * Task that is run periodically to obtain blocks for content
873 * @param tc scheduler context (also unused)
876 gather_migration_blocks (void *cls,
877 const struct GNUNET_SCHEDULER_TaskContext *tc);
881 * If the migration task is not currently running, consider
882 * (re)scheduling it with the appropriate delay.
885 consider_migration_gathering ()
887 struct GNUNET_TIME_Relative delay;
891 if (mig_task != GNUNET_SCHEDULER_NO_TASK)
893 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
895 delay = GNUNET_TIME_relative_divide (delay,
896 MAX_MIGRATION_QUEUE);
897 delay = GNUNET_TIME_relative_max (delay,
898 min_migration_delay);
899 mig_task = GNUNET_SCHEDULER_add_delayed (sched,
901 &gather_migration_blocks,
907 * Process content offered for migration.
910 * @param key key for the content
911 * @param size number of bytes in data
912 * @param data content stored
913 * @param type type of the content
914 * @param priority priority of the content
915 * @param anonymity anonymity-level for the content
916 * @param expiration expiration time for the content
917 * @param uid unique identifier for the datum;
918 * maybe 0 if no unique identifier is available
921 process_migration_content (void *cls,
922 const GNUNET_HashCode * key,
925 enum GNUNET_BLOCK_Type type,
928 struct GNUNET_TIME_Absolute
929 expiration, uint64_t uid)
931 struct MigrationReadyBlock *mb;
936 if (mig_size < MAX_MIGRATION_QUEUE)
937 consider_migration_gathering ();
940 if (type == GNUNET_BLOCK_TYPE_ONDEMAND)
943 GNUNET_FS_handle_on_demand_block (key, size, data,
944 type, priority, anonymity,
946 &process_migration_content,
948 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
952 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
953 "Retrieved block `%s' of type %u for migration\n",
957 mb = GNUNET_malloc (sizeof (struct MigrationReadyBlock) + size);
959 mb->expiration = expiration;
962 memcpy (&mb[1], data, size);
963 GNUNET_CONTAINER_DLL_insert_after (mig_head,
968 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
971 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
976 * Task that is run periodically to obtain blocks for content
980 * @param tc scheduler context (also unused)
983 gather_migration_blocks (void *cls,
984 const struct GNUNET_SCHEDULER_TaskContext *tc)
986 mig_task = GNUNET_SCHEDULER_NO_TASK;
987 mig_qe = GNUNET_DATASTORE_get_random (dsh, 0, -1,
988 GNUNET_TIME_UNIT_FOREVER_REL,
989 &process_migration_content, NULL);
990 GNUNET_assert (mig_qe != NULL);
995 * We're done with a particular message list entry.
996 * Free all associated resources.
998 * @param pml entry to destroy
1001 destroy_pending_message_list_entry (struct PendingMessageList *pml)
1003 GNUNET_CONTAINER_DLL_remove (pml->req->pending_head,
1004 pml->req->pending_tail,
1006 GNUNET_CONTAINER_DLL_remove (pml->target->pending_messages_head,
1007 pml->target->pending_messages_tail,
1009 pml->target->pending_requests--;
1010 GNUNET_free (pml->pm);
1016 * Destroy the given pending message (and call the respective
1019 * @param pm message to destroy
1020 * @param tpid id of peer that the message was delivered to, or 0 for none
1023 destroy_pending_message (struct PendingMessage *pm,
1024 GNUNET_PEER_Id tpid)
1026 struct PendingMessageList *pml = pm->pml;
1027 TransmissionContinuation cont;
1030 GNUNET_assert (pml->pm == pm);
1031 GNUNET_assert ( (tpid == 0) || (tpid == pml->target->pid) );
1033 cont_cls = pm->cont_cls;
1034 destroy_pending_message_list_entry (pml);
1035 cont (cont_cls, tpid);
1040 * We're done processing a particular request.
1041 * Free all associated resources.
1043 * @param pr request to destroy
1046 destroy_pending_request (struct PendingRequest *pr)
1048 struct GNUNET_PeerIdentity pid;
1050 if (pr->hnode != NULL)
1052 GNUNET_CONTAINER_heap_remove_node (requests_by_expiration_heap,
1056 if (NULL == pr->client_request_list)
1058 GNUNET_STATISTICS_update (stats,
1059 gettext_noop ("# P2P searches active"),
1065 GNUNET_STATISTICS_update (stats,
1066 gettext_noop ("# client searches active"),
1070 /* might have already been removed from map in 'process_reply' (if
1071 there was a unique reply) or never inserted if it was a
1072 duplicate; hence ignore the return value here */
1073 (void) GNUNET_CONTAINER_multihashmap_remove (query_request_map,
1078 GNUNET_DATASTORE_cancel (pr->qe);
1081 if (pr->client_request_list != NULL)
1083 GNUNET_CONTAINER_DLL_remove (pr->client_request_list->client_list->rl_head,
1084 pr->client_request_list->client_list->rl_tail,
1085 pr->client_request_list);
1086 GNUNET_free (pr->client_request_list);
1087 pr->client_request_list = NULL;
1091 GNUNET_PEER_resolve (pr->cp->pid,
1093 (void) GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
1100 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
1103 if (pr->irc != NULL)
1105 GNUNET_CORE_peer_change_preference_cancel (pr->irc);
1108 if (pr->replies_seen != NULL)
1110 GNUNET_free (pr->replies_seen);
1111 pr->replies_seen = NULL;
1113 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
1115 GNUNET_SCHEDULER_cancel (sched,
1117 pr->task = GNUNET_SCHEDULER_NO_TASK;
1119 while (NULL != pr->pending_head)
1120 destroy_pending_message_list_entry (pr->pending_head);
1121 GNUNET_PEER_change_rc (pr->target_pid, -1);
1122 if (pr->used_pids != NULL)
1124 GNUNET_PEER_decrement_rcs (pr->used_pids, pr->used_pids_off);
1125 GNUNET_free (pr->used_pids);
1126 pr->used_pids_off = 0;
1127 pr->used_pids_size = 0;
1128 pr->used_pids = NULL;
1135 * Method called whenever a given peer connects.
1137 * @param cls closure, not used
1138 * @param peer peer identity this notification is about
1139 * @param latency reported latency of the connection with 'other'
1140 * @param distance reported distance (DV) to 'other'
1143 peer_connect_handler (void *cls,
1145 GNUNET_PeerIdentity * peer,
1146 struct GNUNET_TIME_Relative latency,
1149 struct ConnectedPeer *cp;
1150 struct MigrationReadyBlock *pos;
1152 cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
1153 cp->pid = GNUNET_PEER_intern (peer);
1154 GNUNET_break (GNUNET_OK ==
1155 GNUNET_CONTAINER_multihashmap_put (connected_peers,
1158 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1163 (void) consider_migration (pos, &peer->hashPubKey, cp);
1171 * Free (each) request made by the peer.
1173 * @param cls closure, points to peer that the request belongs to
1174 * @param key current key code
1175 * @param value value in the hash map
1176 * @return GNUNET_YES (we should continue to iterate)
1179 destroy_request (void *cls,
1180 const GNUNET_HashCode * key,
1183 const struct GNUNET_PeerIdentity * peer = cls;
1184 struct PendingRequest *pr = value;
1186 GNUNET_break (GNUNET_YES ==
1187 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
1190 destroy_pending_request (pr);
1196 * Method called whenever a peer disconnects.
1198 * @param cls closure, not used
1199 * @param peer peer identity this notification is about
1202 peer_disconnect_handler (void *cls,
1204 GNUNET_PeerIdentity * peer)
1206 struct ConnectedPeer *cp;
1207 struct PendingMessage *pm;
1209 struct MigrationReadyBlock *pos;
1210 struct MigrationReadyBlock *next;
1212 GNUNET_CONTAINER_multihashmap_get_multiple (peer_request_map,
1216 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1220 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1222 if (NULL != cp->last_client_replies[i])
1224 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1225 cp->last_client_replies[i] = NULL;
1228 GNUNET_break (GNUNET_YES ==
1229 GNUNET_CONTAINER_multihashmap_remove (connected_peers,
1232 /* remove this peer from migration considerations; schedule
1235 while (NULL != (pos = next))
1238 for (i=0;i<MIGRATION_LIST_SIZE;i++)
1240 if (pos->target_list[i] == cp->pid)
1242 GNUNET_PEER_change_rc (pos->target_list[i], -1);
1243 pos->target_list[i] = 0;
1246 if (pos->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers))
1248 delete_migration_block (pos);
1249 consider_migration_gathering ();
1252 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1253 &consider_migration,
1256 if (cp->trust_delta > 0)
1258 /* FIXME: push trust back to peerinfo!
1259 (need better peerinfo API!) */
1261 GNUNET_PEER_change_rc (cp->pid, -1);
1262 GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
1263 if (NULL != cp->cth)
1264 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
1265 while (NULL != (pm = cp->pending_messages_head))
1266 destroy_pending_message (pm, 0 /* delivery failed */);
1267 GNUNET_break (0 == cp->pending_requests);
1273 * Iterator over hash map entries that removes all occurences
1274 * of the given 'client' from the 'last_client_replies' of the
1275 * given connected peer.
1277 * @param cls closure, the 'struct GNUNET_SERVER_Client*' to remove
1278 * @param key current key code (unused)
1279 * @param value value in the hash map (the 'struct ConnectedPeer*' to change)
1280 * @return GNUNET_YES (we should continue to iterate)
1283 remove_client_from_last_client_replies (void *cls,
1284 const GNUNET_HashCode * key,
1287 struct GNUNET_SERVER_Client *client = cls;
1288 struct ConnectedPeer *cp = value;
1291 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1293 if (cp->last_client_replies[i] == client)
1295 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1296 cp->last_client_replies[i] = NULL;
1304 * A client disconnected. Remove all of its pending queries.
1306 * @param cls closure, NULL
1307 * @param client identification of the client
1310 handle_client_disconnect (void *cls,
1311 struct GNUNET_SERVER_Client
1314 struct ClientList *pos;
1315 struct ClientList *prev;
1316 struct ClientRequestList *rcl;
1317 struct ClientResponseMessage *creply;
1323 while ( (NULL != pos) &&
1324 (pos->client != client) )
1330 return; /* no requests pending for this client */
1331 while (NULL != (rcl = pos->rl_head))
1333 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1334 "Destroying pending request `%s' on disconnect\n",
1335 GNUNET_h2s (&rcl->req->query));
1336 destroy_pending_request (rcl->req);
1339 client_list = pos->next;
1341 prev->next = pos->next;
1342 if (pos->th != NULL)
1344 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
1347 while (NULL != (creply = pos->res_head))
1349 GNUNET_CONTAINER_DLL_remove (pos->res_head,
1352 GNUNET_free (creply);
1354 GNUNET_SERVER_client_drop (pos->client);
1356 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1357 &remove_client_from_last_client_replies,
1363 * Iterator to free peer entries.
1365 * @param cls closure, unused
1366 * @param key current key code
1367 * @param value value in the hash map (peer entry)
1368 * @return GNUNET_YES (we should continue to iterate)
1371 clean_peer (void *cls,
1372 const GNUNET_HashCode * key,
1375 peer_disconnect_handler (NULL, (const struct GNUNET_PeerIdentity*) key);
1381 * Task run during shutdown.
1387 shutdown_task (void *cls,
1388 const struct GNUNET_SCHEDULER_TaskContext *tc)
1392 GNUNET_DATASTORE_cancel (mig_qe);
1395 if (GNUNET_SCHEDULER_NO_TASK != mig_task)
1397 GNUNET_SCHEDULER_cancel (sched, mig_task);
1398 mig_task = GNUNET_SCHEDULER_NO_TASK;
1400 while (client_list != NULL)
1401 handle_client_disconnect (NULL,
1402 client_list->client);
1403 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1406 GNUNET_break (0 == GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap));
1407 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
1408 requests_by_expiration_heap = 0;
1409 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
1410 connected_peers = NULL;
1411 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (query_request_map));
1412 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
1413 query_request_map = NULL;
1414 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (peer_request_map));
1415 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
1416 peer_request_map = NULL;
1417 GNUNET_assert (NULL != core);
1418 GNUNET_CORE_disconnect (core);
1422 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1425 GNUNET_DATASTORE_disconnect (dsh,
1427 while (mig_head != NULL)
1428 delete_migration_block (mig_head);
1429 GNUNET_assert (0 == mig_size);
1436 /* ******************* Utility functions ******************** */
1440 * Transmit messages by copying it to the target buffer
1441 * "buf". "buf" will be NULL and "size" zero if the socket was closed
1442 * for writing in the meantime. In that case, do nothing
1443 * (the disconnect or shutdown handler will take care of the rest).
1444 * If we were able to transmit messages and there are still more
1445 * pending, ask core again for further calls to this function.
1447 * @param cls closure, pointer to the 'struct ConnectedPeer*'
1448 * @param size number of bytes available in buf
1449 * @param buf where the callee should write the message
1450 * @return number of bytes written to buf
1453 transmit_to_peer (void *cls,
1454 size_t size, void *buf)
1456 struct ConnectedPeer *cp = cls;
1458 struct GNUNET_PeerIdentity pid;
1459 struct PendingMessage *pm;
1460 struct MigrationReadyBlock *mb;
1461 struct MigrationReadyBlock *next;
1462 struct PutMessage migm;
1470 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1471 "Dropping message, core too busy.\n");
1476 while ( (NULL != (pm = cp->pending_messages_head) ) &&
1477 (pm->msize <= size) )
1479 memcpy (&cbuf[msize], &pm[1], pm->msize);
1482 destroy_pending_message (pm, cp->pid);
1486 GNUNET_PEER_resolve (cp->pid,
1488 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1490 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1499 while (NULL != (mb = next))
1502 for (i=0;i<MIGRATION_LIST_SIZE;i++)
1504 if ( (cp->pid == mb->target_list[i]) &&
1505 (mb->size + sizeof (migm) <= size) )
1507 GNUNET_PEER_change_rc (mb->target_list[i], -1);
1508 mb->target_list[i] = 0;
1510 migm.header.size = htons (sizeof (migm) + mb->size);
1511 migm.header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
1512 migm.type = htonl (mb->type);
1513 migm.expiration = GNUNET_TIME_absolute_hton (mb->expiration);
1514 memcpy (&cbuf[msize], &migm, sizeof (migm));
1515 msize += sizeof (migm);
1516 size -= sizeof (migm);
1517 memcpy (&cbuf[msize], &mb[1], mb->size);
1521 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1522 "Pushing migration block `%s' (%u bytes) to `%s'\n",
1523 GNUNET_h2s (&mb->query),
1532 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1533 "Migration block `%s' (%u bytes) is not on migration list for peer `%s'\n",
1534 GNUNET_h2s (&mb->query),
1540 if ( (mb->used_targets >= MIGRATION_TARGET_COUNT) ||
1541 (mb->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers)) )
1543 delete_migration_block (mb);
1544 consider_migration_gathering ();
1547 consider_migration (NULL,
1552 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1553 "Transmitting %u bytes to peer %u\n",
1562 * Add a message to the set of pending messages for the given peer.
1564 * @param cp peer to send message to
1565 * @param pm message to queue
1566 * @param pr request on which behalf this message is being queued
1569 add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
1570 struct PendingMessage *pm,
1571 struct PendingRequest *pr)
1573 struct PendingMessage *pos;
1574 struct PendingMessageList *pml;
1575 struct GNUNET_PeerIdentity pid;
1577 GNUNET_assert (pm->next == NULL);
1578 GNUNET_assert (pm->pml == NULL);
1579 pml = GNUNET_malloc (sizeof (struct PendingMessageList));
1584 GNUNET_CONTAINER_DLL_insert (pr->pending_head,
1587 pos = cp->pending_messages_head;
1588 while ( (pos != NULL) &&
1589 (pm->priority < pos->priority) )
1591 GNUNET_CONTAINER_DLL_insert_after (cp->pending_messages_head,
1592 cp->pending_messages_tail,
1595 cp->pending_requests++;
1596 if (cp->pending_requests > MAX_QUEUE_PER_PEER)
1597 destroy_pending_message (cp->pending_messages_tail, 0);
1598 GNUNET_PEER_resolve (cp->pid, &pid);
1599 if (NULL != cp->cth)
1600 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
1601 /* need to schedule transmission */
1602 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1603 cp->pending_messages_head->priority,
1606 cp->pending_messages_head->msize,
1609 if (cp->cth == NULL)
1612 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1613 "Failed to schedule transmission with core!\n");
1615 GNUNET_STATISTICS_update (stats,
1616 gettext_noop ("# CORE transmission failures"),
1624 * Mingle hash with the mingle_number to produce different bits.
1627 mingle_hash (const GNUNET_HashCode * in,
1628 int32_t mingle_number,
1629 GNUNET_HashCode * hc)
1633 GNUNET_CRYPTO_hash (&mingle_number,
1636 GNUNET_CRYPTO_hash_xor (&m, in, hc);
1641 * Test if the load on this peer is too high
1642 * to even consider processing the query at
1645 * @return GNUNET_YES if the load is too high, GNUNET_NO otherwise
1648 test_load_too_high ()
1650 return GNUNET_NO; // FIXME
1654 /* ******************* Pending Request Refresh Task ******************** */
1659 * We use a random delay to make the timing of requests less
1660 * predictable. This function returns such a random delay. We add a base
1661 * delay of MAX_CORK_DELAY (1s).
1663 * FIXME: make schedule dependent on the specifics of the request?
1664 * Or bandwidth and number of connected peers and load?
1666 * @return random delay to use for some request, between 1s and 1000+TTL_DECREMENT ms
1668 static struct GNUNET_TIME_Relative
1669 get_processing_delay ()
1672 GNUNET_TIME_relative_add (GNUNET_CONSTANTS_MAX_CORK_DELAY,
1673 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1674 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1680 * We're processing a GET request from another peer and have decided
1681 * to forward it to other peers. This function is called periodically
1682 * and should forward the request to other peers until we have all
1683 * possible replies. If we have transmitted the *only* reply to
1684 * the initiator we should destroy the pending request. If we have
1685 * many replies in the queue to the initiator, we should delay sending
1686 * out more queries until the reply queue has shrunk some.
1688 * @param cls our "struct ProcessGetContext *"
1692 forward_request_task (void *cls,
1693 const struct GNUNET_SCHEDULER_TaskContext *tc);
1697 * Function called after we either failed or succeeded
1698 * at transmitting a query to a peer.
1700 * @param cls the requests "struct PendingRequest*"
1701 * @param tpid ID of receiving peer, 0 on transmission error
1704 transmit_query_continuation (void *cls,
1705 GNUNET_PEER_Id tpid)
1707 struct PendingRequest *pr = cls;
1709 GNUNET_STATISTICS_update (stats,
1710 gettext_noop ("# queries scheduled for forwarding"),
1716 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1717 "Transmission of request failed, will try again later.\n");
1719 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1720 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1721 get_processing_delay (),
1722 &forward_request_task,
1726 GNUNET_STATISTICS_update (stats,
1727 gettext_noop ("# queries forwarded"),
1730 GNUNET_PEER_change_rc (tpid, 1);
1731 if (pr->used_pids_off == pr->used_pids_size)
1732 GNUNET_array_grow (pr->used_pids,
1734 pr->used_pids_size * 2 + 2);
1735 pr->used_pids[pr->used_pids_off++] = tpid;
1736 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1737 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1738 get_processing_delay (),
1739 &forward_request_task,
1745 * How many bytes should a bloomfilter be if we have already seen
1746 * entry_count responses? Note that BLOOMFILTER_K gives us the number
1747 * of bits set per entry. Furthermore, we should not re-size the
1748 * filter too often (to keep it cheap).
1750 * Since other peers will also add entries but not resize the filter,
1751 * we should generally pick a slightly larger size than what the
1752 * strict math would suggest.
1754 * @return must be a power of two and smaller or equal to 2^15.
1757 compute_bloomfilter_size (unsigned int entry_count)
1760 unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
1761 uint16_t max = 1 << 15;
1763 if (entry_count > max)
1766 while ((size < max) && (size < ideal))
1775 * Recalculate our bloom filter for filtering replies. This function
1776 * will create a new bloom filter from scratch, so it should only be
1777 * called if we have no bloomfilter at all (and hence can create a
1778 * fresh one of minimal size without problems) OR if our peer is the
1779 * initiator (in which case we may resize to larger than mimimum size).
1781 * @param pr request for which the BF is to be recomputed
1784 refresh_bloomfilter (struct PendingRequest *pr)
1788 GNUNET_HashCode mhash;
1790 nsize = compute_bloomfilter_size (pr->replies_seen_off);
1791 if (nsize == pr->bf_size)
1792 return; /* size not changed */
1794 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
1795 pr->bf_size = nsize;
1796 pr->mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
1797 pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1800 for (i=0;i<pr->replies_seen_off;i++)
1802 mingle_hash (&pr->replies_seen[i], pr->mingle, &mhash);
1803 GNUNET_CONTAINER_bloomfilter_add (pr->bf, &mhash);
1809 * Function called after we've tried to reserve a certain amount of
1810 * bandwidth for a reply. Check if we succeeded and if so send our
1813 * @param cls the requests "struct PendingRequest*"
1814 * @param peer identifies the peer
1815 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1816 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1817 * @param amount set to the amount that was actually reserved or unreserved
1818 * @param preference current traffic preference for the given peer
1821 target_reservation_cb (void *cls,
1823 GNUNET_PeerIdentity * peer,
1824 struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
1825 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1827 uint64_t preference)
1829 struct PendingRequest *pr = cls;
1830 struct ConnectedPeer *cp;
1831 struct PendingMessage *pm;
1832 struct GetMessage *gm;
1833 GNUNET_HashCode *ext;
1843 /* error in communication with core, try again later */
1844 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1845 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1846 get_processing_delay (),
1847 &forward_request_task,
1851 // (3) transmit, update ttl/priority
1852 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1856 /* Peer must have just left */
1858 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1859 "Selected peer disconnected!\n");
1861 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1862 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1863 get_processing_delay (),
1864 &forward_request_task,
1868 no_route = GNUNET_NO;
1874 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1875 "Failed to reserve bandwidth for reply (got %d/%u bytes only)!\n",
1879 GNUNET_STATISTICS_update (stats,
1880 gettext_noop ("# reply bandwidth reservation requests failed"),
1883 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1884 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1885 get_processing_delay (),
1886 &forward_request_task,
1888 return; /* this target round failed */
1890 /* FIXME: if we are "quite" busy, we may still want to skip
1891 this round; need more load detection code! */
1892 no_route = GNUNET_YES;
1895 GNUNET_STATISTICS_update (stats,
1896 gettext_noop ("# queries scheduled for forwarding"),
1899 /* build message and insert message into priority queue */
1901 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1902 "Forwarding request `%s' to `%4s'!\n",
1903 GNUNET_h2s (&pr->query),
1908 if (GNUNET_YES == no_route)
1910 bm |= GET_MESSAGE_BIT_RETURN_TO;
1913 if (pr->namespace != NULL)
1915 bm |= GET_MESSAGE_BIT_SKS_NAMESPACE;
1918 if (pr->target_pid != 0)
1920 bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
1923 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
1924 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1925 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1927 gm = (struct GetMessage*) &pm[1];
1928 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
1929 gm->header.size = htons (msize);
1930 gm->type = htonl (pr->type);
1931 pr->remaining_priority /= 2;
1932 gm->priority = htonl (pr->remaining_priority);
1933 gm->ttl = htonl (pr->ttl);
1934 gm->filter_mutator = htonl(pr->mingle);
1935 gm->hash_bitmap = htonl (bm);
1936 gm->query = pr->query;
1937 ext = (GNUNET_HashCode*) &gm[1];
1939 if (GNUNET_YES == no_route)
1940 GNUNET_PEER_resolve (pr->cp->pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1941 if (pr->namespace != NULL)
1942 memcpy (&ext[k++], pr->namespace, sizeof (GNUNET_HashCode));
1943 if (pr->target_pid != 0)
1944 GNUNET_PEER_resolve (pr->target_pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1945 bfdata = (char *) &ext[k];
1947 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
1950 pm->cont = &transmit_query_continuation;
1952 add_to_pending_messages_for_peer (cp, pm, pr);
1957 * Closure used for "target_peer_select_cb".
1959 struct PeerSelectionContext
1962 * The request for which we are selecting
1965 struct PendingRequest *pr;
1968 * Current "prime" target.
1970 struct GNUNET_PeerIdentity target;
1973 * How much do we like this target?
1975 double target_score;
1981 * Function called for each connected peer to determine
1982 * which one(s) would make good targets for forwarding.
1984 * @param cls closure (struct PeerSelectionContext)
1985 * @param key current key code (peer identity)
1986 * @param value value in the hash map (struct ConnectedPeer)
1987 * @return GNUNET_YES if we should continue to
1992 target_peer_select_cb (void *cls,
1993 const GNUNET_HashCode * key,
1996 struct PeerSelectionContext *psc = cls;
1997 struct ConnectedPeer *cp = value;
1998 struct PendingRequest *pr = psc->pr;
2003 /* 1) check that this peer is not the initiator */
2007 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2008 "Skipping initiator in forwarding selection\n");
2010 return GNUNET_YES; /* skip */
2013 /* 2) check if we have already (recently) forwarded to this peer */
2015 for (i=0;i<pr->used_pids_off;i++)
2016 if (pr->used_pids[i] == cp->pid)
2019 if (0 != GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2020 RETRY_PROBABILITY_INV))
2023 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2024 "NOT re-trying query that was previously transmitted %u times\n",
2025 (unsigned int) pr->used_pids_off);
2027 return GNUNET_YES; /* skip */
2032 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2033 "Re-trying query that was previously transmitted %u times to this peer\n",
2036 /* 3) calculate how much we'd like to forward to this peer,
2037 starting with a random value that is strong enough
2038 to at least give any peer a chance sometimes
2039 (compared to the other factors that come later) */
2040 /* 3a) count successful (recent) routes from cp for same source */
2043 score = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2044 P2P_SUCCESS_LIST_SIZE);
2045 for (i=0;i<P2P_SUCCESS_LIST_SIZE;i++)
2046 if (cp->last_p2p_replies[i] == pr->cp->pid)
2047 score += 1; /* likely successful based on hot path */
2051 score = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2052 CS2P_SUCCESS_LIST_SIZE);
2053 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
2054 if (cp->last_client_replies[i] == pr->client_request_list->client_list->client)
2055 score += 1; /* likely successful based on hot path */
2057 /* 3b) include latency */
2058 if (cp->avg_delay.value < 4 * TTL_DECREMENT)
2059 score += 1; /* likely fast based on latency */
2060 /* 3c) include priorities */
2061 if (cp->avg_priority <= pr->remaining_priority / 2.0)
2062 score += 1; /* likely successful based on priorities */
2063 /* 3d) penalize for queue size */
2064 score -= (2.0 * cp->pending_requests / (double) MAX_QUEUE_PER_PEER);
2065 /* 3e) include peer proximity */
2066 score -= (2.0 * (GNUNET_CRYPTO_hash_distance_u32 (key,
2067 &pr->query)) / (double) UINT32_MAX);
2068 /* store best-fit in closure */
2070 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2071 "Peer `%s' gets score %f for forwarding query, max is %f\n",
2076 score++; /* avoid zero */
2077 if (score > psc->target_score)
2079 psc->target_score = score;
2080 psc->target.hashPubKey = *key;
2087 * The priority level imposes a bound on the maximum
2088 * value for the ttl that can be requested.
2090 * @param ttl_in requested ttl
2091 * @param prio given priority
2092 * @return ttl_in if ttl_in is below the limit,
2093 * otherwise the ttl-limit for the given priority
2096 bound_ttl (int32_t ttl_in, uint32_t prio)
2098 unsigned long long allowed;
2102 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
2103 if (ttl_in > allowed)
2105 if (allowed >= (1 << 30))
2114 * We're processing a GET request and have decided
2115 * to forward it to other peers. This function is called periodically
2116 * and should forward the request to other peers until we have all
2117 * possible replies. If we have transmitted the *only* reply to
2118 * the initiator we should destroy the pending request. If we have
2119 * many replies in the queue to the initiator, we should delay sending
2120 * out more queries until the reply queue has shrunk some.
2122 * @param cls our "struct ProcessGetContext *"
2126 forward_request_task (void *cls,
2127 const struct GNUNET_SCHEDULER_TaskContext *tc)
2129 struct PendingRequest *pr = cls;
2130 struct PeerSelectionContext psc;
2131 struct ConnectedPeer *cp;
2132 struct GNUNET_TIME_Relative delay;
2134 pr->task = GNUNET_SCHEDULER_NO_TASK;
2135 if (pr->irc != NULL)
2138 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2139 "Forwarding of query `%s' not attempted due to pending local lookup!\n",
2140 GNUNET_h2s (&pr->query));
2142 return; /* already pending */
2144 if (GNUNET_YES == pr->local_only)
2145 return; /* configured to not do P2P search */
2146 /* (1) select target */
2148 psc.target_score = -DBL_MAX;
2149 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
2150 &target_peer_select_cb,
2152 if (psc.target_score == -DBL_MAX)
2154 delay = get_processing_delay ();
2156 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2157 "No peer selected for forwarding of query `%s', will try again in %llu ms!\n",
2158 GNUNET_h2s (&pr->query),
2161 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
2163 &forward_request_task,
2165 return; /* nobody selected */
2167 /* (3) update TTL/priority */
2168 if (pr->client_request_list != NULL)
2170 /* FIXME: use better algorithm!? */
2171 if (0 == GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2174 /* FIXME: bound priority by "customary" priority used by other peers
2176 pr->ttl = bound_ttl (pr->ttl + TTL_DECREMENT * 2,
2179 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2180 "Trying query `%s' with priority %u and TTL %d.\n",
2181 GNUNET_h2s (&pr->query),
2187 /* (3) reserve reply bandwidth */
2188 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2189 &psc.target.hashPubKey);
2190 GNUNET_assert (NULL != cp);
2191 pr->irc = GNUNET_CORE_peer_change_preference (sched, cfg,
2193 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
2194 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
2197 &target_reservation_cb,
2199 cp->inc_preference = 0;
2203 /* **************************** P2P PUT Handling ************************ */
2207 * Function called after we either failed or succeeded
2208 * at transmitting a reply to a peer.
2210 * @param cls the requests "struct PendingRequest*"
2211 * @param tpid ID of receiving peer, 0 on transmission error
2214 transmit_reply_continuation (void *cls,
2215 GNUNET_PEER_Id tpid)
2217 struct PendingRequest *pr = cls;
2221 case GNUNET_BLOCK_TYPE_DBLOCK:
2222 case GNUNET_BLOCK_TYPE_IBLOCK:
2223 /* only one reply expected, done with the request! */
2224 destroy_pending_request (pr);
2226 case GNUNET_BLOCK_TYPE_ANY:
2227 case GNUNET_BLOCK_TYPE_KBLOCK:
2228 case GNUNET_BLOCK_TYPE_SBLOCK:
2238 * Transmit the given message by copying it to the target buffer
2239 * "buf". "buf" will be NULL and "size" zero if the socket was closed
2240 * for writing in the meantime. In that case, do nothing
2241 * (the disconnect or shutdown handler will take care of the rest).
2242 * If we were able to transmit messages and there are still more
2243 * pending, ask core again for further calls to this function.
2245 * @param cls closure, pointer to the 'struct ClientList*'
2246 * @param size number of bytes available in buf
2247 * @param buf where the callee should write the message
2248 * @return number of bytes written to buf
2251 transmit_to_client (void *cls,
2252 size_t size, void *buf)
2254 struct ClientList *cl = cls;
2256 struct ClientResponseMessage *creply;
2263 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2264 "Not sending reply, client communication problem.\n");
2269 while ( (NULL != (creply = cl->res_head) ) &&
2270 (creply->msize <= size) )
2272 memcpy (&cbuf[msize], &creply[1], creply->msize);
2273 msize += creply->msize;
2274 size -= creply->msize;
2275 GNUNET_CONTAINER_DLL_remove (cl->res_head,
2278 GNUNET_free (creply);
2281 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
2283 GNUNET_TIME_UNIT_FOREVER_REL,
2284 &transmit_to_client,
2287 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2288 "Transmitted %u bytes to client\n",
2289 (unsigned int) msize);
2296 * Closure for "process_reply" function.
2298 struct ProcessReplyClosure
2301 * The data for the reply.
2306 * Who gave us this reply? NULL for local host.
2308 struct ConnectedPeer *sender;
2311 * When the reply expires.
2313 struct GNUNET_TIME_Absolute expiration;
2321 * Namespace that this reply belongs to
2322 * (if it is of type SBLOCK).
2324 GNUNET_HashCode namespace;
2327 * Type of the block.
2329 enum GNUNET_BLOCK_Type type;
2332 * How much was this reply worth to us?
2337 * Did we finish processing the associated request?
2344 * We have received a reply; handle it!
2346 * @param cls response (struct ProcessReplyClosure)
2347 * @param key our query
2348 * @param value value in the hash map (info about the query)
2349 * @return GNUNET_YES (we should continue to iterate)
2352 process_reply (void *cls,
2353 const GNUNET_HashCode * key,
2356 struct ProcessReplyClosure *prq = cls;
2357 struct PendingRequest *pr = value;
2358 struct PendingMessage *reply;
2359 struct ClientResponseMessage *creply;
2360 struct ClientList *cl;
2361 struct PutMessage *pm;
2362 struct ConnectedPeer *cp;
2363 struct GNUNET_TIME_Relative cur_delay;
2364 GNUNET_HashCode chash;
2365 GNUNET_HashCode mhash;
2369 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2370 "Matched result (type %u) for query `%s' with pending request\n",
2371 (unsigned int) prq->type,
2374 GNUNET_STATISTICS_update (stats,
2375 gettext_noop ("# replies received and matched"),
2378 if (prq->sender != NULL)
2380 /* FIXME: should we be more precise here and not use
2381 "start_time" but a peer-specific time stamp? */
2382 cur_delay = GNUNET_TIME_absolute_get_duration (pr->start_time);
2383 prq->sender->avg_delay.value
2384 = (prq->sender->avg_delay.value *
2385 (RUNAVG_DELAY_N - 1) + cur_delay.value) / RUNAVG_DELAY_N;
2386 prq->sender->avg_priority
2387 = (prq->sender->avg_priority *
2388 (RUNAVG_DELAY_N - 1) + pr->priority) / (double) RUNAVG_DELAY_N;
2391 GNUNET_PEER_change_rc (prq->sender->last_p2p_replies
2392 [prq->sender->last_p2p_replies_woff % P2P_SUCCESS_LIST_SIZE],
2394 GNUNET_PEER_change_rc (pr->cp->pid, 1);
2395 prq->sender->last_p2p_replies
2396 [(prq->sender->last_p2p_replies_woff++) % P2P_SUCCESS_LIST_SIZE]
2401 if (NULL != prq->sender->last_client_replies
2402 [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE])
2403 GNUNET_SERVER_client_drop (prq->sender->last_client_replies
2404 [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE]);
2405 prq->sender->last_client_replies
2406 [(prq->sender->last_client_replies_woff++) % CS2P_SUCCESS_LIST_SIZE]
2407 = pr->client_request_list->client_list->client;
2408 GNUNET_SERVER_client_keep (pr->client_request_list->client_list->client);
2411 GNUNET_CRYPTO_hash (prq->data,
2416 case GNUNET_BLOCK_TYPE_DBLOCK:
2417 case GNUNET_BLOCK_TYPE_IBLOCK:
2418 /* only possible reply, stop requesting! */
2419 while (NULL != pr->pending_head)
2420 destroy_pending_message_list_entry (pr->pending_head);
2423 if (pr->client_request_list != NULL)
2424 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
2426 GNUNET_DATASTORE_cancel (pr->qe);
2429 pr->do_remove = GNUNET_YES;
2430 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
2432 GNUNET_SCHEDULER_cancel (sched,
2434 pr->task = GNUNET_SCHEDULER_NO_TASK;
2436 GNUNET_break (GNUNET_YES ==
2437 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
2441 case GNUNET_BLOCK_TYPE_SBLOCK:
2442 if (pr->namespace == NULL)
2447 if (0 != memcmp (pr->namespace,
2449 sizeof (GNUNET_HashCode)))
2451 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2452 _("Reply mismatched in terms of namespace. Discarded.\n"));
2453 return GNUNET_YES; /* wrong namespace */
2455 /* then: fall-through! */
2456 case GNUNET_BLOCK_TYPE_KBLOCK:
2457 case GNUNET_BLOCK_TYPE_NBLOCK:
2460 mingle_hash (&chash, pr->mingle, &mhash);
2461 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
2464 GNUNET_STATISTICS_update (stats,
2465 gettext_noop ("# duplicate replies discarded (bloomfilter)"),
2469 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2470 "Duplicate response `%s', discarding.\n",
2471 GNUNET_h2s (&mhash));
2473 return GNUNET_YES; /* duplicate */
2476 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2477 "New response `%s', adding to filter.\n",
2478 GNUNET_h2s (&mhash));
2481 if (pr->client_request_list != NULL)
2483 if (pr->replies_seen_size == pr->replies_seen_off)
2484 GNUNET_array_grow (pr->replies_seen,
2485 pr->replies_seen_size,
2486 pr->replies_seen_size * 2 + 4);
2487 pr->replies_seen[pr->replies_seen_off++] = chash;
2489 if ( (pr->bf == NULL) ||
2490 (pr->client_request_list != NULL) )
2491 refresh_bloomfilter (pr);
2492 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
2499 prq->priority += pr->remaining_priority;
2500 pr->remaining_priority = 0;
2501 if (NULL != pr->client_request_list)
2503 GNUNET_STATISTICS_update (stats,
2504 gettext_noop ("# replies received for local clients"),
2507 cl = pr->client_request_list->client_list;
2508 msize = sizeof (struct PutMessage) + prq->size;
2509 creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
2510 creply->msize = msize;
2511 creply->client_list = cl;
2512 GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
2516 pm = (struct PutMessage*) &creply[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);
2525 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2526 "Transmitting result for query `%s' to client\n",
2529 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
2531 GNUNET_TIME_UNIT_FOREVER_REL,
2532 &transmit_to_client,
2535 GNUNET_break (cl->th != NULL);
2538 prq->finished = GNUNET_YES;
2539 destroy_pending_request (pr);
2546 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2547 "Transmitting result for query `%s' to other peer (PID=%u)\n",
2549 (unsigned int) cp->pid);
2551 GNUNET_STATISTICS_update (stats,
2552 gettext_noop ("# replies received for other peers"),
2555 msize = sizeof (struct PutMessage) + prq->size;
2556 reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
2557 reply->cont = &transmit_reply_continuation;
2558 reply->cont_cls = pr;
2559 reply->msize = msize;
2560 reply->priority = UINT32_MAX; /* send replies first! */
2561 pm = (struct PutMessage*) &reply[1];
2562 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2563 pm->header.size = htons (msize);
2564 pm->type = htonl (prq->type);
2565 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
2566 memcpy (&pm[1], prq->data, prq->size);
2567 add_to_pending_messages_for_peer (cp, reply, pr);
2574 * Continuation called to notify client about result of the
2577 * @param cls closure
2578 * @param success GNUNET_SYSERR on failure
2579 * @param msg NULL on success, otherwise an error message
2582 put_migration_continuation (void *cls,
2591 * Handle P2P "PUT" message.
2593 * @param cls closure, always NULL
2594 * @param other the other peer involved (sender or receiver, NULL
2595 * for loopback messages where we are both sender and receiver)
2596 * @param message the actual message
2597 * @param latency reported latency of the connection with 'other'
2598 * @param distance reported distance (DV) to 'other'
2599 * @return GNUNET_OK to keep the connection open,
2600 * GNUNET_SYSERR to close it (signal serious error)
2603 handle_p2p_put (void *cls,
2604 const struct GNUNET_PeerIdentity *other,
2605 const struct GNUNET_MessageHeader *message,
2606 struct GNUNET_TIME_Relative latency,
2609 const struct PutMessage *put;
2612 enum GNUNET_BLOCK_Type type;
2613 struct GNUNET_TIME_Absolute expiration;
2614 GNUNET_HashCode query;
2615 struct ProcessReplyClosure prq;
2616 const struct SBlock *sb;
2618 msize = ntohs (message->size);
2619 if (msize < sizeof (struct PutMessage))
2622 return GNUNET_SYSERR;
2624 put = (const struct PutMessage*) message;
2625 dsize = msize - sizeof (struct PutMessage);
2626 type = ntohl (put->type);
2627 expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
2630 GNUNET_BLOCK_check_block (type,
2635 GNUNET_break_op (0);
2636 return GNUNET_SYSERR;
2638 if (type == GNUNET_BLOCK_TYPE_ONDEMAND)
2639 return GNUNET_SYSERR;
2640 if (GNUNET_BLOCK_TYPE_SBLOCK == type)
2642 sb = (const struct SBlock*) &put[1];
2643 GNUNET_CRYPTO_hash (&sb->subspace,
2644 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2649 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2650 "Received result for query `%s' from peer `%4s'\n",
2651 GNUNET_h2s (&query),
2652 GNUNET_i2s (other));
2654 GNUNET_STATISTICS_update (stats,
2655 gettext_noop ("# replies received (overall)"),
2658 /* now, lookup 'query' */
2659 prq.data = (const void*) &put[1];
2661 prq.sender = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2662 &other->hashPubKey);
2667 prq.expiration = expiration;
2669 prq.finished = GNUNET_NO;
2670 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2674 if (prq.sender != NULL)
2676 prq.sender->inc_preference += CONTENT_BANDWIDTH_VALUE + 1000 * prq.priority;
2677 prq.sender->trust_delta += prq.priority;
2679 if (GNUNET_YES == active_migration)
2682 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2683 "Replicating result for query `%s' with priority %u\n",
2684 GNUNET_h2s (&query),
2687 GNUNET_DATASTORE_put (dsh,
2688 0, &query, dsize, &put[1],
2689 type, prq.priority, 1 /* anonymity */,
2691 1 + prq.priority, MAX_DATASTORE_QUEUE,
2692 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
2693 &put_migration_continuation,
2700 /* **************************** P2P GET Handling ************************ */
2704 * Closure for 'check_duplicate_request_{peer,client}'.
2706 struct CheckDuplicateRequestClosure
2709 * The new request we should check if it already exists.
2711 const struct PendingRequest *pr;
2714 * Existing request found by the checker, NULL if none.
2716 struct PendingRequest *have;
2721 * Iterator over entries in the 'query_request_map' that
2722 * tries to see if we have the same request pending from
2723 * the same client already.
2725 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
2726 * @param key current key code (query, ignored, must match)
2727 * @param value value in the hash map (a 'struct PendingRequest'
2728 * that already exists)
2729 * @return GNUNET_YES if we should continue to
2730 * iterate (no match yet)
2731 * GNUNET_NO if not (match found).
2734 check_duplicate_request_client (void *cls,
2735 const GNUNET_HashCode * key,
2738 struct CheckDuplicateRequestClosure *cdc = cls;
2739 struct PendingRequest *have = value;
2741 if (have->client_request_list == NULL)
2743 if ( (cdc->pr->client_request_list->client_list->client == have->client_request_list->client_list->client) &&
2754 * We're processing (local) results for a search request
2755 * from another peer. Pass applicable results to the
2756 * peer and if we are done either clean up (operation
2757 * complete) or forward to other peers (more results possible).
2759 * @param cls our closure (struct LocalGetContext)
2760 * @param key key for the content
2761 * @param size number of bytes in data
2762 * @param data content stored
2763 * @param type type of the content
2764 * @param priority priority of the content
2765 * @param anonymity anonymity-level for the content
2766 * @param expiration expiration time for the content
2767 * @param uid unique identifier for the datum;
2768 * maybe 0 if no unique identifier is available
2771 process_local_reply (void *cls,
2772 const GNUNET_HashCode * key,
2775 enum GNUNET_BLOCK_Type type,
2778 struct GNUNET_TIME_Absolute
2782 struct PendingRequest *pr = cls;
2783 struct ProcessReplyClosure prq;
2784 struct CheckDuplicateRequestClosure cdrc;
2785 const struct SBlock *sb;
2786 GNUNET_HashCode dhash;
2787 GNUNET_HashCode mhash;
2788 GNUNET_HashCode query;
2793 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2794 "Done processing local replies, forwarding request to other peers.\n");
2797 if (pr->client_request_list != NULL)
2799 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
2801 /* Figure out if this is a duplicate request and possibly
2802 merge 'struct PendingRequest' entries */
2805 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2807 &check_duplicate_request_client,
2809 if (cdrc.have != NULL)
2812 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2813 "Received request for block `%s' twice from client, will only request once.\n",
2814 GNUNET_h2s (&pr->query));
2817 destroy_pending_request (pr);
2822 /* no more results */
2823 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2824 pr->task = GNUNET_SCHEDULER_add_now (sched,
2825 &forward_request_task,
2830 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2831 "New local response to `%s' of type %u.\n",
2835 if (type == GNUNET_BLOCK_TYPE_ONDEMAND)
2838 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2839 "Found ONDEMAND block, performing on-demand encoding\n");
2841 GNUNET_STATISTICS_update (stats,
2842 gettext_noop ("# on-demand blocks matched requests"),
2846 GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
2847 anonymity, expiration, uid,
2848 &process_local_reply,
2851 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2854 /* check for duplicates */
2855 GNUNET_CRYPTO_hash (data, size, &dhash);
2856 mingle_hash (&dhash,
2859 if ( (pr->bf != NULL) &&
2861 GNUNET_CONTAINER_bloomfilter_test (pr->bf,
2865 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2866 "Result from datastore filtered by bloomfilter (duplicate).\n");
2868 GNUNET_STATISTICS_update (stats,
2869 gettext_noop ("# results filtered by query bloomfilter"),
2873 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2877 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2878 "Found result for query `%s' in local datastore\n",
2881 GNUNET_STATISTICS_update (stats,
2882 gettext_noop ("# results found locally"),
2885 pr->results_found++;
2886 memset (&prq, 0, sizeof (prq));
2888 prq.expiration = expiration;
2890 if (GNUNET_BLOCK_TYPE_SBLOCK == type)
2892 sb = (const struct SBlock*) data;
2893 GNUNET_CRYPTO_hash (&sb->subspace,
2894 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2897 if (GNUNET_OK != GNUNET_BLOCK_check_block (type,
2903 GNUNET_DATASTORE_remove (dsh,
2907 GNUNET_TIME_UNIT_FOREVER_REL,
2909 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2913 prq.priority = priority;
2914 prq.finished = GNUNET_NO;
2915 process_reply (&prq, key, pr);
2916 if (prq.finished == GNUNET_YES)
2919 return; /* done here */
2920 if ( (type == GNUNET_BLOCK_TYPE_DBLOCK) ||
2921 (type == GNUNET_BLOCK_TYPE_IBLOCK) )
2923 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
2926 if ( (pr->client_request_list == NULL) &&
2927 ( (GNUNET_YES == test_load_too_high()) ||
2928 (pr->results_found > 5 + 2 * pr->priority) ) )
2931 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2932 "Load too high, done with request\n");
2934 GNUNET_STATISTICS_update (stats,
2935 gettext_noop ("# processing result set cut short due to load"),
2938 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
2941 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2946 * We've received a request with the specified priority. Bound it
2947 * according to how much we trust the given peer.
2949 * @param prio_in requested priority
2950 * @param cp the peer making the request
2951 * @return effective priority
2954 bound_priority (uint32_t prio_in,
2955 struct ConnectedPeer *cp)
2957 if (cp->trust_delta > prio_in)
2959 cp->trust_delta -= prio_in;
2962 // FIXME: get out trust in the target peer from peerinfo!
2968 * Iterator over entries in the 'query_request_map' that
2969 * tries to see if we have the same request pending from
2970 * the same peer already.
2972 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
2973 * @param key current key code (query, ignored, must match)
2974 * @param value value in the hash map (a 'struct PendingRequest'
2975 * that already exists)
2976 * @return GNUNET_YES if we should continue to
2977 * iterate (no match yet)
2978 * GNUNET_NO if not (match found).
2981 check_duplicate_request_peer (void *cls,
2982 const GNUNET_HashCode * key,
2985 struct CheckDuplicateRequestClosure *cdc = cls;
2986 struct PendingRequest *have = value;
2988 if (cdc->pr->target_pid == have->target_pid)
2998 * Handle P2P "GET" request.
3000 * @param cls closure, always NULL
3001 * @param other the other peer involved (sender or receiver, NULL
3002 * for loopback messages where we are both sender and receiver)
3003 * @param message the actual message
3004 * @param latency reported latency of the connection with 'other'
3005 * @param distance reported distance (DV) to 'other'
3006 * @return GNUNET_OK to keep the connection open,
3007 * GNUNET_SYSERR to close it (signal serious error)
3010 handle_p2p_get (void *cls,
3011 const struct GNUNET_PeerIdentity *other,
3012 const struct GNUNET_MessageHeader *message,
3013 struct GNUNET_TIME_Relative latency,
3016 struct PendingRequest *pr;
3017 struct ConnectedPeer *cp;
3018 struct ConnectedPeer *cps;
3019 struct CheckDuplicateRequestClosure cdc;
3020 struct GNUNET_TIME_Relative timeout;
3022 const struct GetMessage *gm;
3024 const GNUNET_HashCode *opt;
3027 uint32_t ttl_decrement;
3028 enum GNUNET_BLOCK_Type type;
3031 msize = ntohs(message->size);
3032 if (msize < sizeof (struct GetMessage))
3034 GNUNET_break_op (0);
3035 return GNUNET_SYSERR;
3037 gm = (const struct GetMessage*) message;
3038 type = ntohl (gm->type);
3041 case GNUNET_BLOCK_TYPE_ANY:
3042 case GNUNET_BLOCK_TYPE_DBLOCK:
3043 case GNUNET_BLOCK_TYPE_IBLOCK:
3044 case GNUNET_BLOCK_TYPE_KBLOCK:
3045 case GNUNET_BLOCK_TYPE_SBLOCK:
3048 GNUNET_break_op (0);
3049 return GNUNET_SYSERR;
3051 bm = ntohl (gm->hash_bitmap);
3059 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
3061 GNUNET_break_op (0);
3062 return GNUNET_SYSERR;
3064 opt = (const GNUNET_HashCode*) &gm[1];
3065 bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
3066 bm = ntohl (gm->hash_bitmap);
3067 if ( (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)) &&
3068 (type != GNUNET_BLOCK_TYPE_SBLOCK) )
3070 GNUNET_break_op (0);
3071 return GNUNET_SYSERR;
3074 cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3075 &other->hashPubKey);
3078 /* peer must have just disconnected */
3079 GNUNET_STATISTICS_update (stats,
3080 gettext_noop ("# requests dropped due to initiator not being connected"),
3083 return GNUNET_SYSERR;
3085 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
3086 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3093 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
3094 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3095 "Failed to find RETURN-TO peer `%4s' in connection set. Dropping query.\n",
3096 GNUNET_i2s ((const struct GNUNET_PeerIdentity*) &opt[bits-1]));
3099 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3100 "Failed to find peer `%4s' in connection set. Dropping query.\n",
3101 GNUNET_i2s (other));
3103 GNUNET_STATISTICS_update (stats,
3104 gettext_noop ("# requests dropped due to missing reverse route"),
3107 /* FIXME: try connect? */
3110 /* note that we can really only check load here since otherwise
3111 peers could find out that we are overloaded by not being
3112 disconnected after sending us a malformed query... */
3113 if (GNUNET_YES == test_load_too_high ())
3116 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3117 "Dropping query from `%s', this peer is too busy.\n",
3118 GNUNET_i2s (other));
3120 GNUNET_STATISTICS_update (stats,
3121 gettext_noop ("# requests dropped due to high load"),
3128 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3129 "Received request for `%s' of type %u from peer `%4s' with flags %u\n",
3130 GNUNET_h2s (&gm->query),
3131 (unsigned int) type,
3135 have_ns = (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE));
3136 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
3137 (have_ns ? sizeof(GNUNET_HashCode) : 0));
3140 pr->namespace = (GNUNET_HashCode*) &pr[1];
3141 memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
3144 pr->mingle = ntohl (gm->filter_mutator);
3145 if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
3146 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
3148 pr->anonymity_level = 1;
3149 pr->priority = bound_priority (ntohl (gm->priority), cps);
3150 pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
3151 pr->query = gm->query;
3152 /* decrement ttl (always) */
3153 ttl_decrement = 2 * TTL_DECREMENT +
3154 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3156 if ( (pr->ttl < 0) &&
3157 (((int32_t)(pr->ttl - ttl_decrement)) > 0) )
3160 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3161 "Dropping query from `%s' due to TTL underflow (%d - %u).\n",
3166 GNUNET_STATISTICS_update (stats,
3167 gettext_noop ("# requests dropped due TTL underflow"),
3170 /* integer underflow => drop (should be very rare)! */
3174 pr->ttl -= ttl_decrement;
3175 pr->start_time = GNUNET_TIME_absolute_get ();
3177 /* get bloom filter */
3180 pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
3183 pr->bf_size = bfsize;
3188 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
3190 &check_duplicate_request_peer,
3192 if (cdc.have != NULL)
3194 if (cdc.have->start_time.value + cdc.have->ttl >=
3195 pr->start_time.value + pr->ttl)
3197 /* existing request has higher TTL, drop new one! */
3198 cdc.have->priority += pr->priority;
3199 destroy_pending_request (pr);
3201 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3202 "Have existing request with higher TTL, dropping new request.\n",
3203 GNUNET_i2s (other));
3205 GNUNET_STATISTICS_update (stats,
3206 gettext_noop ("# requests dropped due to higher-TTL request"),
3213 /* existing request has lower TTL, drop old one! */
3214 pr->priority += cdc.have->priority;
3215 /* Possible optimization: if we have applicable pending
3216 replies in 'cdc.have', we might want to move those over
3217 (this is a really rare special-case, so it is not clear
3218 that this would be worth it) */
3219 destroy_pending_request (cdc.have);
3220 /* keep processing 'pr'! */
3225 GNUNET_break (GNUNET_OK ==
3226 GNUNET_CONTAINER_multihashmap_put (query_request_map,
3229 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
3230 GNUNET_break (GNUNET_OK ==
3231 GNUNET_CONTAINER_multihashmap_put (peer_request_map,
3234 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
3236 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
3238 pr->start_time.value + pr->ttl);
3240 GNUNET_STATISTICS_update (stats,
3241 gettext_noop ("# P2P searches received"),
3244 GNUNET_STATISTICS_update (stats,
3245 gettext_noop ("# P2P searches active"),
3249 /* calculate change in traffic preference */
3250 cps->inc_preference += pr->priority * 1000 + QUERY_BANDWIDTH_VALUE;
3251 /* process locally */
3252 if (type == GNUNET_BLOCK_TYPE_DBLOCK)
3253 type = GNUNET_BLOCK_TYPE_ANY; /* to get on-demand as well */
3254 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
3255 (pr->priority + 1));
3256 pr->qe = GNUNET_DATASTORE_get (dsh,
3260 MAX_DATASTORE_QUEUE,
3262 &process_local_reply,
3265 /* Are multiple results possible? If so, start processing remotely now! */
3268 case GNUNET_BLOCK_TYPE_DBLOCK:
3269 case GNUNET_BLOCK_TYPE_IBLOCK:
3270 /* only one result, wait for datastore */
3273 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
3274 pr->task = GNUNET_SCHEDULER_add_now (sched,
3275 &forward_request_task,
3279 /* make sure we don't track too many requests */
3280 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
3282 pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
3283 destroy_pending_request (pr);
3289 /* **************************** CS GET Handling ************************ */
3293 * Handle START_SEARCH-message (search request from client).
3295 * @param cls closure
3296 * @param client identification of the client
3297 * @param message the actual message
3300 handle_start_search (void *cls,
3301 struct GNUNET_SERVER_Client *client,
3302 const struct GNUNET_MessageHeader *message)
3304 static GNUNET_HashCode all_zeros;
3305 const struct SearchMessage *sm;
3306 struct ClientList *cl;
3307 struct ClientRequestList *crl;
3308 struct PendingRequest *pr;
3311 enum GNUNET_BLOCK_Type type;
3313 msize = ntohs (message->size);
3314 if ( (msize < sizeof (struct SearchMessage)) ||
3315 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
3318 GNUNET_SERVER_receive_done (client,
3322 GNUNET_STATISTICS_update (stats,
3323 gettext_noop ("# client searches received"),
3326 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
3327 sm = (const struct SearchMessage*) message;
3328 type = ntohl (sm->type);
3330 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3331 "Received request for `%s' of type %u from local client\n",
3332 GNUNET_h2s (&sm->query),
3333 (unsigned int) type);
3337 case GNUNET_BLOCK_TYPE_ANY:
3338 case GNUNET_BLOCK_TYPE_DBLOCK:
3339 case GNUNET_BLOCK_TYPE_IBLOCK:
3340 case GNUNET_BLOCK_TYPE_KBLOCK:
3341 case GNUNET_BLOCK_TYPE_SBLOCK:
3342 case GNUNET_BLOCK_TYPE_NBLOCK:
3346 GNUNET_SERVER_receive_done (client,
3352 while ( (cl != NULL) &&
3353 (cl->client != client) )
3357 cl = GNUNET_malloc (sizeof (struct ClientList));
3358 cl->client = client;
3359 GNUNET_SERVER_client_keep (client);
3360 cl->next = client_list;
3363 /* detect duplicate KBLOCK requests */
3364 if ( (type == GNUNET_BLOCK_TYPE_KBLOCK) ||
3365 (type == GNUNET_BLOCK_TYPE_NBLOCK) ||
3366 (type == GNUNET_BLOCK_TYPE_ANY) )
3369 while ( (crl != NULL) &&
3370 ( (0 != memcmp (&crl->req->query,
3372 sizeof (GNUNET_HashCode))) ||
3373 (crl->req->type != type) ) )
3378 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3379 "Have existing request, merging content-seen lists.\n");
3382 /* Duplicate request (used to send long list of
3383 known/blocked results); merge 'pr->replies_seen'
3384 and update bloom filter */
3385 GNUNET_array_grow (pr->replies_seen,
3386 pr->replies_seen_size,
3387 pr->replies_seen_off + sc);
3388 memcpy (&pr->replies_seen[pr->replies_seen_off],
3390 sc * sizeof (GNUNET_HashCode));
3391 pr->replies_seen_off += sc;
3392 refresh_bloomfilter (pr);
3393 GNUNET_STATISTICS_update (stats,
3394 gettext_noop ("# client searches updated (merged content seen list)"),
3397 GNUNET_SERVER_receive_done (client,
3402 GNUNET_STATISTICS_update (stats,
3403 gettext_noop ("# client searches active"),
3406 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
3407 ((type == GNUNET_BLOCK_TYPE_SBLOCK) ? sizeof(GNUNET_HashCode) : 0));
3408 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
3409 memset (crl, 0, sizeof (struct ClientRequestList));
3410 crl->client_list = cl;
3411 GNUNET_CONTAINER_DLL_insert (cl->rl_head,
3416 pr->client_request_list = crl;
3417 GNUNET_array_grow (pr->replies_seen,
3418 pr->replies_seen_size,
3420 memcpy (pr->replies_seen,
3422 sc * sizeof (GNUNET_HashCode));
3423 pr->replies_seen_off = sc;
3424 pr->anonymity_level = ntohl (sm->anonymity_level);
3425 refresh_bloomfilter (pr);
3426 pr->query = sm->query;
3427 if (0 == (1 & ntohl (sm->options)))
3428 pr->local_only = GNUNET_NO;
3430 pr->local_only = GNUNET_YES;
3433 case GNUNET_BLOCK_TYPE_DBLOCK:
3434 case GNUNET_BLOCK_TYPE_IBLOCK:
3435 if (0 != memcmp (&sm->target,
3437 sizeof (GNUNET_HashCode)))
3438 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
3440 case GNUNET_BLOCK_TYPE_SBLOCK:
3441 pr->namespace = (GNUNET_HashCode*) &pr[1];
3442 memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
3447 GNUNET_break (GNUNET_OK ==
3448 GNUNET_CONTAINER_multihashmap_put (query_request_map,
3451 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
3452 if (type == GNUNET_BLOCK_TYPE_DBLOCK)
3453 type = GNUNET_BLOCK_TYPE_ANY; /* get on-demand blocks too! */
3454 pr->qe = GNUNET_DATASTORE_get (dsh,
3458 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
3459 &process_local_reply,
3464 /* **************************** Startup ************************ */
3467 * Process fs requests.
3469 * @param s scheduler to use
3470 * @param server the initialized server
3471 * @param c configuration to use
3474 main_init (struct GNUNET_SCHEDULER_Handle *s,
3475 struct GNUNET_SERVER_Handle *server,
3476 const struct GNUNET_CONFIGURATION_Handle *c)
3478 static const struct GNUNET_CORE_MessageHandler p2p_handlers[] =
3481 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
3483 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
3486 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
3487 {&GNUNET_FS_handle_index_start, NULL,
3488 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
3489 {&GNUNET_FS_handle_index_list_get, NULL,
3490 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
3491 {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
3492 sizeof (struct UnindexMessage) },
3493 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
3500 stats = GNUNET_STATISTICS_create (sched, "fs", cfg);
3501 min_migration_delay = GNUNET_TIME_UNIT_SECONDS; // FIXME: get from config
3502 connected_peers = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3503 query_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3504 peer_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3505 requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
3506 core = GNUNET_CORE_connect (sched,
3508 GNUNET_TIME_UNIT_FOREVER_REL,
3511 &peer_connect_handler,
3512 &peer_disconnect_handler,
3518 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3519 _("Failed to connect to `%s' service.\n"),
3521 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
3522 connected_peers = NULL;
3523 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
3524 query_request_map = NULL;
3525 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
3526 requests_by_expiration_heap = NULL;
3527 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
3528 peer_request_map = NULL;
3531 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
3534 return GNUNET_SYSERR;
3536 /* FIXME: distinguish between sending and storing in options? */
3537 if (active_migration)
3539 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3540 _("Content migration is enabled, will start to gather data\n"));
3541 consider_migration_gathering ();
3543 GNUNET_SERVER_disconnect_notify (server,
3544 &handle_client_disconnect,
3546 GNUNET_SERVER_add_handlers (server, handlers);
3547 GNUNET_SCHEDULER_add_delayed (sched,
3548 GNUNET_TIME_UNIT_FOREVER_REL,
3556 * Process fs requests.
3558 * @param cls closure
3559 * @param sched scheduler to use
3560 * @param server the initialized server
3561 * @param cfg configuration to use
3565 struct GNUNET_SCHEDULER_Handle *sched,
3566 struct GNUNET_SERVER_Handle *server,
3567 const struct GNUNET_CONFIGURATION_Handle *cfg)
3569 active_migration = GNUNET_CONFIGURATION_get_value_yesno (cfg,
3572 dsh = GNUNET_DATASTORE_connect (cfg,
3576 GNUNET_SCHEDULER_shutdown (sched);
3579 if ( (GNUNET_OK != GNUNET_FS_indexing_init (sched, cfg, dsh)) ||
3580 (GNUNET_OK != main_init (sched, server, cfg)) )
3582 GNUNET_SCHEDULER_shutdown (sched);
3583 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
3591 * The main function for the fs service.
3593 * @param argc number of arguments from the command line
3594 * @param argv command line arguments
3595 * @return 0 ok, 1 on error
3598 main (int argc, char *const *argv)
3600 return (GNUNET_OK ==
3601 GNUNET_SERVICE_run (argc,
3604 GNUNET_SERVICE_OPTION_NONE,
3605 &run, NULL)) ? 0 : 1;
3608 /* end of gnunet-service-fs.c */