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 * - 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;
2617 struct ConnectedPeer *cps;
2619 msize = ntohs (message->size);
2620 if (msize < sizeof (struct PutMessage))
2623 return GNUNET_SYSERR;
2625 put = (const struct PutMessage*) message;
2626 dsize = msize - sizeof (struct PutMessage);
2627 type = ntohl (put->type);
2628 expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
2631 GNUNET_BLOCK_check_block (type,
2636 GNUNET_break_op (0);
2637 return GNUNET_SYSERR;
2639 if (type == GNUNET_BLOCK_TYPE_ONDEMAND)
2640 return GNUNET_SYSERR;
2641 if (GNUNET_BLOCK_TYPE_SBLOCK == type)
2643 sb = (const struct SBlock*) &put[1];
2644 GNUNET_CRYPTO_hash (&sb->subspace,
2645 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2650 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2651 "Received result for query `%s' from peer `%4s'\n",
2652 GNUNET_h2s (&query),
2653 GNUNET_i2s (other));
2655 GNUNET_STATISTICS_update (stats,
2656 gettext_noop ("# replies received (overall)"),
2659 /* now, lookup 'query' */
2660 prq.data = (const void*) &put[1];
2662 prq.sender = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2663 &other->hashPubKey);
2666 prq.expiration = expiration;
2668 prq.finished = GNUNET_NO;
2669 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2673 cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2674 &other->hashPubKey);
2677 cps->inc_preference += CONTENT_BANDWIDTH_VALUE + 1000 * prq.priority;
2678 cps->trust_delta += prq.priority;
2684 if (GNUNET_YES == active_migration)
2687 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2688 "Replicating result for query `%s' with priority %u\n",
2689 GNUNET_h2s (&query),
2692 GNUNET_DATASTORE_put (dsh,
2693 0, &query, dsize, &put[1],
2694 type, prq.priority, 1 /* anonymity */,
2696 1 + prq.priority, MAX_DATASTORE_QUEUE,
2697 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
2698 &put_migration_continuation,
2705 /* **************************** P2P GET Handling ************************ */
2709 * Closure for 'check_duplicate_request_{peer,client}'.
2711 struct CheckDuplicateRequestClosure
2714 * The new request we should check if it already exists.
2716 const struct PendingRequest *pr;
2719 * Existing request found by the checker, NULL if none.
2721 struct PendingRequest *have;
2726 * Iterator over entries in the 'query_request_map' that
2727 * tries to see if we have the same request pending from
2728 * the same client already.
2730 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
2731 * @param key current key code (query, ignored, must match)
2732 * @param value value in the hash map (a 'struct PendingRequest'
2733 * that already exists)
2734 * @return GNUNET_YES if we should continue to
2735 * iterate (no match yet)
2736 * GNUNET_NO if not (match found).
2739 check_duplicate_request_client (void *cls,
2740 const GNUNET_HashCode * key,
2743 struct CheckDuplicateRequestClosure *cdc = cls;
2744 struct PendingRequest *have = value;
2746 if (have->client_request_list == NULL)
2748 if ( (cdc->pr->client_request_list->client_list->client == have->client_request_list->client_list->client) &&
2759 * We're processing (local) results for a search request
2760 * from another peer. Pass applicable results to the
2761 * peer and if we are done either clean up (operation
2762 * complete) or forward to other peers (more results possible).
2764 * @param cls our closure (struct LocalGetContext)
2765 * @param key key for the content
2766 * @param size number of bytes in data
2767 * @param data content stored
2768 * @param type type of the content
2769 * @param priority priority of the content
2770 * @param anonymity anonymity-level for the content
2771 * @param expiration expiration time for the content
2772 * @param uid unique identifier for the datum;
2773 * maybe 0 if no unique identifier is available
2776 process_local_reply (void *cls,
2777 const GNUNET_HashCode * key,
2780 enum GNUNET_BLOCK_Type type,
2783 struct GNUNET_TIME_Absolute
2787 struct PendingRequest *pr = cls;
2788 struct ProcessReplyClosure prq;
2789 struct CheckDuplicateRequestClosure cdrc;
2790 const struct SBlock *sb;
2791 GNUNET_HashCode dhash;
2792 GNUNET_HashCode mhash;
2793 GNUNET_HashCode query;
2798 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2799 "Done processing local replies, forwarding request to other peers.\n");
2802 if (pr->client_request_list != NULL)
2804 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
2806 /* Figure out if this is a duplicate request and possibly
2807 merge 'struct PendingRequest' entries */
2810 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2812 &check_duplicate_request_client,
2814 if (cdrc.have != NULL)
2817 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2818 "Received request for block `%s' twice from client, will only request once.\n",
2819 GNUNET_h2s (&pr->query));
2822 destroy_pending_request (pr);
2827 /* no more results */
2828 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2829 pr->task = GNUNET_SCHEDULER_add_now (sched,
2830 &forward_request_task,
2835 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2836 "New local response to `%s' of type %u.\n",
2840 if (type == GNUNET_BLOCK_TYPE_ONDEMAND)
2843 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2844 "Found ONDEMAND block, performing on-demand encoding\n");
2846 GNUNET_STATISTICS_update (stats,
2847 gettext_noop ("# on-demand blocks matched requests"),
2851 GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
2852 anonymity, expiration, uid,
2853 &process_local_reply,
2856 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2859 /* check for duplicates */
2860 GNUNET_CRYPTO_hash (data, size, &dhash);
2861 mingle_hash (&dhash,
2864 if ( (pr->bf != NULL) &&
2866 GNUNET_CONTAINER_bloomfilter_test (pr->bf,
2870 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2871 "Result from datastore filtered by bloomfilter (duplicate).\n");
2873 GNUNET_STATISTICS_update (stats,
2874 gettext_noop ("# results filtered by query bloomfilter"),
2878 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2882 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2883 "Found result for query `%s' in local datastore\n",
2886 GNUNET_STATISTICS_update (stats,
2887 gettext_noop ("# results found locally"),
2890 pr->results_found++;
2891 memset (&prq, 0, sizeof (prq));
2893 prq.expiration = expiration;
2895 if (GNUNET_BLOCK_TYPE_SBLOCK == type)
2897 sb = (const struct SBlock*) data;
2898 GNUNET_CRYPTO_hash (&sb->subspace,
2899 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2902 if (GNUNET_OK != GNUNET_BLOCK_check_block (type,
2908 GNUNET_DATASTORE_remove (dsh,
2912 GNUNET_TIME_UNIT_FOREVER_REL,
2914 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2918 prq.priority = priority;
2919 prq.finished = GNUNET_NO;
2920 process_reply (&prq, key, pr);
2921 if (prq.finished == GNUNET_YES)
2924 return; /* done here */
2925 if ( (type == GNUNET_BLOCK_TYPE_DBLOCK) ||
2926 (type == GNUNET_BLOCK_TYPE_IBLOCK) )
2928 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
2931 if ( (pr->client_request_list == NULL) &&
2932 ( (GNUNET_YES == test_load_too_high()) ||
2933 (pr->results_found > 5 + 2 * pr->priority) ) )
2936 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2937 "Load too high, done with request\n");
2939 GNUNET_STATISTICS_update (stats,
2940 gettext_noop ("# processing result set cut short due to load"),
2943 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
2946 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2951 * We've received a request with the specified priority. Bound it
2952 * according to how much we trust the given peer.
2954 * @param prio_in requested priority
2955 * @param cp the peer making the request
2956 * @return effective priority
2959 bound_priority (uint32_t prio_in,
2960 struct ConnectedPeer *cp)
2962 if (cp->trust_delta > prio_in)
2964 cp->trust_delta -= prio_in;
2967 // FIXME: get out trust in the target peer from peerinfo!
2973 * Iterator over entries in the 'query_request_map' that
2974 * tries to see if we have the same request pending from
2975 * the same peer already.
2977 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
2978 * @param key current key code (query, ignored, must match)
2979 * @param value value in the hash map (a 'struct PendingRequest'
2980 * that already exists)
2981 * @return GNUNET_YES if we should continue to
2982 * iterate (no match yet)
2983 * GNUNET_NO if not (match found).
2986 check_duplicate_request_peer (void *cls,
2987 const GNUNET_HashCode * key,
2990 struct CheckDuplicateRequestClosure *cdc = cls;
2991 struct PendingRequest *have = value;
2993 if (cdc->pr->target_pid == have->target_pid)
3003 * Handle P2P "GET" request.
3005 * @param cls closure, always NULL
3006 * @param other the other peer involved (sender or receiver, NULL
3007 * for loopback messages where we are both sender and receiver)
3008 * @param message the actual message
3009 * @param latency reported latency of the connection with 'other'
3010 * @param distance reported distance (DV) to 'other'
3011 * @return GNUNET_OK to keep the connection open,
3012 * GNUNET_SYSERR to close it (signal serious error)
3015 handle_p2p_get (void *cls,
3016 const struct GNUNET_PeerIdentity *other,
3017 const struct GNUNET_MessageHeader *message,
3018 struct GNUNET_TIME_Relative latency,
3021 struct PendingRequest *pr;
3022 struct ConnectedPeer *cp;
3023 struct ConnectedPeer *cps;
3024 struct CheckDuplicateRequestClosure cdc;
3025 struct GNUNET_TIME_Relative timeout;
3027 const struct GetMessage *gm;
3029 const GNUNET_HashCode *opt;
3032 uint32_t ttl_decrement;
3033 enum GNUNET_BLOCK_Type type;
3036 msize = ntohs(message->size);
3037 if (msize < sizeof (struct GetMessage))
3039 GNUNET_break_op (0);
3040 return GNUNET_SYSERR;
3042 gm = (const struct GetMessage*) message;
3043 type = ntohl (gm->type);
3046 case GNUNET_BLOCK_TYPE_ANY:
3047 case GNUNET_BLOCK_TYPE_DBLOCK:
3048 case GNUNET_BLOCK_TYPE_IBLOCK:
3049 case GNUNET_BLOCK_TYPE_KBLOCK:
3050 case GNUNET_BLOCK_TYPE_SBLOCK:
3053 GNUNET_break_op (0);
3054 return GNUNET_SYSERR;
3056 bm = ntohl (gm->hash_bitmap);
3064 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
3066 GNUNET_break_op (0);
3067 return GNUNET_SYSERR;
3069 opt = (const GNUNET_HashCode*) &gm[1];
3070 bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
3071 bm = ntohl (gm->hash_bitmap);
3072 if ( (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)) &&
3073 (type != GNUNET_BLOCK_TYPE_SBLOCK) )
3075 GNUNET_break_op (0);
3076 return GNUNET_SYSERR;
3079 cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3080 &other->hashPubKey);
3083 /* peer must have just disconnected */
3084 GNUNET_STATISTICS_update (stats,
3085 gettext_noop ("# requests dropped due to initiator not being connected"),
3088 return GNUNET_SYSERR;
3090 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
3091 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3098 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
3099 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3100 "Failed to find RETURN-TO peer `%4s' in connection set. Dropping query.\n",
3101 GNUNET_i2s ((const struct GNUNET_PeerIdentity*) &opt[bits-1]));
3104 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3105 "Failed to find peer `%4s' in connection set. Dropping query.\n",
3106 GNUNET_i2s (other));
3108 GNUNET_STATISTICS_update (stats,
3109 gettext_noop ("# requests dropped due to missing reverse route"),
3112 /* FIXME: try connect? */
3115 /* note that we can really only check load here since otherwise
3116 peers could find out that we are overloaded by not being
3117 disconnected after sending us a malformed query... */
3118 if (GNUNET_YES == test_load_too_high ())
3121 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3122 "Dropping query from `%s', this peer is too busy.\n",
3123 GNUNET_i2s (other));
3125 GNUNET_STATISTICS_update (stats,
3126 gettext_noop ("# requests dropped due to high load"),
3133 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3134 "Received request for `%s' of type %u from peer `%4s' with flags %u\n",
3135 GNUNET_h2s (&gm->query),
3136 (unsigned int) type,
3140 have_ns = (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE));
3141 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
3142 (have_ns ? sizeof(GNUNET_HashCode) : 0));
3145 pr->namespace = (GNUNET_HashCode*) &pr[1];
3146 memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
3149 pr->mingle = ntohl (gm->filter_mutator);
3150 if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
3151 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
3153 pr->anonymity_level = 1;
3154 pr->priority = bound_priority (ntohl (gm->priority), cps);
3155 pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
3156 pr->query = gm->query;
3157 /* decrement ttl (always) */
3158 ttl_decrement = 2 * TTL_DECREMENT +
3159 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3161 if ( (pr->ttl < 0) &&
3162 (((int32_t)(pr->ttl - ttl_decrement)) > 0) )
3165 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3166 "Dropping query from `%s' due to TTL underflow (%d - %u).\n",
3171 GNUNET_STATISTICS_update (stats,
3172 gettext_noop ("# requests dropped due TTL underflow"),
3175 /* integer underflow => drop (should be very rare)! */
3179 pr->ttl -= ttl_decrement;
3180 pr->start_time = GNUNET_TIME_absolute_get ();
3182 /* get bloom filter */
3185 pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
3188 pr->bf_size = bfsize;
3193 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
3195 &check_duplicate_request_peer,
3197 if (cdc.have != NULL)
3199 if (cdc.have->start_time.value + cdc.have->ttl >=
3200 pr->start_time.value + pr->ttl)
3202 /* existing request has higher TTL, drop new one! */
3203 cdc.have->priority += pr->priority;
3204 destroy_pending_request (pr);
3206 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3207 "Have existing request with higher TTL, dropping new request.\n",
3208 GNUNET_i2s (other));
3210 GNUNET_STATISTICS_update (stats,
3211 gettext_noop ("# requests dropped due to higher-TTL request"),
3218 /* existing request has lower TTL, drop old one! */
3219 pr->priority += cdc.have->priority;
3220 /* Possible optimization: if we have applicable pending
3221 replies in 'cdc.have', we might want to move those over
3222 (this is a really rare special-case, so it is not clear
3223 that this would be worth it) */
3224 destroy_pending_request (cdc.have);
3225 /* keep processing 'pr'! */
3230 GNUNET_break (GNUNET_OK ==
3231 GNUNET_CONTAINER_multihashmap_put (query_request_map,
3234 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
3235 GNUNET_break (GNUNET_OK ==
3236 GNUNET_CONTAINER_multihashmap_put (peer_request_map,
3239 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
3241 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
3243 pr->start_time.value + pr->ttl);
3245 GNUNET_STATISTICS_update (stats,
3246 gettext_noop ("# P2P searches received"),
3249 GNUNET_STATISTICS_update (stats,
3250 gettext_noop ("# P2P searches active"),
3254 /* calculate change in traffic preference */
3255 cps->inc_preference += pr->priority * 1000 + QUERY_BANDWIDTH_VALUE;
3256 /* process locally */
3257 if (type == GNUNET_BLOCK_TYPE_DBLOCK)
3258 type = GNUNET_BLOCK_TYPE_ANY; /* to get on-demand as well */
3259 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
3260 (pr->priority + 1));
3261 pr->qe = GNUNET_DATASTORE_get (dsh,
3265 MAX_DATASTORE_QUEUE,
3267 &process_local_reply,
3270 /* Are multiple results possible? If so, start processing remotely now! */
3273 case GNUNET_BLOCK_TYPE_DBLOCK:
3274 case GNUNET_BLOCK_TYPE_IBLOCK:
3275 /* only one result, wait for datastore */
3278 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
3279 pr->task = GNUNET_SCHEDULER_add_now (sched,
3280 &forward_request_task,
3284 /* make sure we don't track too many requests */
3285 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
3287 pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
3288 destroy_pending_request (pr);
3294 /* **************************** CS GET Handling ************************ */
3298 * Handle START_SEARCH-message (search request from client).
3300 * @param cls closure
3301 * @param client identification of the client
3302 * @param message the actual message
3305 handle_start_search (void *cls,
3306 struct GNUNET_SERVER_Client *client,
3307 const struct GNUNET_MessageHeader *message)
3309 static GNUNET_HashCode all_zeros;
3310 const struct SearchMessage *sm;
3311 struct ClientList *cl;
3312 struct ClientRequestList *crl;
3313 struct PendingRequest *pr;
3316 enum GNUNET_BLOCK_Type type;
3318 msize = ntohs (message->size);
3319 if ( (msize < sizeof (struct SearchMessage)) ||
3320 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
3323 GNUNET_SERVER_receive_done (client,
3327 GNUNET_STATISTICS_update (stats,
3328 gettext_noop ("# client searches received"),
3331 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
3332 sm = (const struct SearchMessage*) message;
3333 type = ntohl (sm->type);
3335 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3336 "Received request for `%s' of type %u from local client\n",
3337 GNUNET_h2s (&sm->query),
3338 (unsigned int) type);
3342 case GNUNET_BLOCK_TYPE_ANY:
3343 case GNUNET_BLOCK_TYPE_DBLOCK:
3344 case GNUNET_BLOCK_TYPE_IBLOCK:
3345 case GNUNET_BLOCK_TYPE_KBLOCK:
3346 case GNUNET_BLOCK_TYPE_SBLOCK:
3347 case GNUNET_BLOCK_TYPE_NBLOCK:
3351 GNUNET_SERVER_receive_done (client,
3357 while ( (cl != NULL) &&
3358 (cl->client != client) )
3362 cl = GNUNET_malloc (sizeof (struct ClientList));
3363 cl->client = client;
3364 GNUNET_SERVER_client_keep (client);
3365 cl->next = client_list;
3368 /* detect duplicate KBLOCK requests */
3369 if ( (type == GNUNET_BLOCK_TYPE_KBLOCK) ||
3370 (type == GNUNET_BLOCK_TYPE_NBLOCK) ||
3371 (type == GNUNET_BLOCK_TYPE_ANY) )
3374 while ( (crl != NULL) &&
3375 ( (0 != memcmp (&crl->req->query,
3377 sizeof (GNUNET_HashCode))) ||
3378 (crl->req->type != type) ) )
3383 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3384 "Have existing request, merging content-seen lists.\n");
3387 /* Duplicate request (used to send long list of
3388 known/blocked results); merge 'pr->replies_seen'
3389 and update bloom filter */
3390 GNUNET_array_grow (pr->replies_seen,
3391 pr->replies_seen_size,
3392 pr->replies_seen_off + sc);
3393 memcpy (&pr->replies_seen[pr->replies_seen_off],
3395 sc * sizeof (GNUNET_HashCode));
3396 pr->replies_seen_off += sc;
3397 refresh_bloomfilter (pr);
3398 GNUNET_STATISTICS_update (stats,
3399 gettext_noop ("# client searches updated (merged content seen list)"),
3402 GNUNET_SERVER_receive_done (client,
3407 GNUNET_STATISTICS_update (stats,
3408 gettext_noop ("# client searches active"),
3411 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
3412 ((type == GNUNET_BLOCK_TYPE_SBLOCK) ? sizeof(GNUNET_HashCode) : 0));
3413 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
3414 memset (crl, 0, sizeof (struct ClientRequestList));
3415 crl->client_list = cl;
3416 GNUNET_CONTAINER_DLL_insert (cl->rl_head,
3421 pr->client_request_list = crl;
3422 GNUNET_array_grow (pr->replies_seen,
3423 pr->replies_seen_size,
3425 memcpy (pr->replies_seen,
3427 sc * sizeof (GNUNET_HashCode));
3428 pr->replies_seen_off = sc;
3429 pr->anonymity_level = ntohl (sm->anonymity_level);
3430 refresh_bloomfilter (pr);
3431 pr->query = sm->query;
3432 if (0 == (1 & ntohl (sm->options)))
3433 pr->local_only = GNUNET_NO;
3435 pr->local_only = GNUNET_YES;
3438 case GNUNET_BLOCK_TYPE_DBLOCK:
3439 case GNUNET_BLOCK_TYPE_IBLOCK:
3440 if (0 != memcmp (&sm->target,
3442 sizeof (GNUNET_HashCode)))
3443 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
3445 case GNUNET_BLOCK_TYPE_SBLOCK:
3446 pr->namespace = (GNUNET_HashCode*) &pr[1];
3447 memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
3452 GNUNET_break (GNUNET_OK ==
3453 GNUNET_CONTAINER_multihashmap_put (query_request_map,
3456 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
3457 if (type == GNUNET_BLOCK_TYPE_DBLOCK)
3458 type = GNUNET_BLOCK_TYPE_ANY; /* get on-demand blocks too! */
3459 pr->qe = GNUNET_DATASTORE_get (dsh,
3463 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
3464 &process_local_reply,
3469 /* **************************** Startup ************************ */
3472 * Process fs requests.
3474 * @param s scheduler to use
3475 * @param server the initialized server
3476 * @param c configuration to use
3479 main_init (struct GNUNET_SCHEDULER_Handle *s,
3480 struct GNUNET_SERVER_Handle *server,
3481 const struct GNUNET_CONFIGURATION_Handle *c)
3483 static const struct GNUNET_CORE_MessageHandler p2p_handlers[] =
3486 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
3488 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
3491 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
3492 {&GNUNET_FS_handle_index_start, NULL,
3493 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
3494 {&GNUNET_FS_handle_index_list_get, NULL,
3495 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
3496 {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
3497 sizeof (struct UnindexMessage) },
3498 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
3505 stats = GNUNET_STATISTICS_create (sched, "fs", cfg);
3506 min_migration_delay = GNUNET_TIME_UNIT_SECONDS; // FIXME: get from config
3507 connected_peers = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3508 query_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3509 peer_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3510 requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
3511 core = GNUNET_CORE_connect (sched,
3513 GNUNET_TIME_UNIT_FOREVER_REL,
3516 &peer_connect_handler,
3517 &peer_disconnect_handler,
3523 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3524 _("Failed to connect to `%s' service.\n"),
3526 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
3527 connected_peers = NULL;
3528 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
3529 query_request_map = NULL;
3530 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
3531 requests_by_expiration_heap = NULL;
3532 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
3533 peer_request_map = NULL;
3536 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
3539 return GNUNET_SYSERR;
3541 /* FIXME: distinguish between sending and storing in options? */
3542 if (active_migration)
3544 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3545 _("Content migration is enabled, will start to gather data\n"));
3546 consider_migration_gathering ();
3548 GNUNET_SERVER_disconnect_notify (server,
3549 &handle_client_disconnect,
3551 GNUNET_SERVER_add_handlers (server, handlers);
3552 GNUNET_SCHEDULER_add_delayed (sched,
3553 GNUNET_TIME_UNIT_FOREVER_REL,
3561 * Process fs requests.
3563 * @param cls closure
3564 * @param sched scheduler to use
3565 * @param server the initialized server
3566 * @param cfg configuration to use
3570 struct GNUNET_SCHEDULER_Handle *sched,
3571 struct GNUNET_SERVER_Handle *server,
3572 const struct GNUNET_CONFIGURATION_Handle *cfg)
3574 active_migration = GNUNET_CONFIGURATION_get_value_yesno (cfg,
3577 dsh = GNUNET_DATASTORE_connect (cfg,
3581 GNUNET_SCHEDULER_shutdown (sched);
3584 if ( (GNUNET_OK != GNUNET_FS_indexing_init (sched, cfg, dsh)) ||
3585 (GNUNET_OK != main_init (sched, server, cfg)) )
3587 GNUNET_SCHEDULER_shutdown (sched);
3588 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
3596 * The main function for the fs service.
3598 * @param argc number of arguments from the command line
3599 * @param argv command line arguments
3600 * @return 0 ok, 1 on error
3603 main (int argc, char *const *argv)
3605 return (GNUNET_OK ==
3606 GNUNET_SERVICE_run (argc,
3609 GNUNET_SERVICE_OPTION_NONE,
3610 &run, NULL)) ? 0 : 1;
3613 /* end of gnunet-service-fs.c */