2 This file is part of GNUnet.
3 (C) 2009, 2010 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 2, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file fs/gnunet-service-fs.c
23 * @brief gnunet anonymity protocol implementation
24 * @author Christian Grothoff
27 * - TTL/priority calculations are absent!
29 * - have non-zero preference / priority for requests we initiate!
30 * - implement hot-path routing decision procedure
31 * - implement: bound_priority, test_load_too_high
36 #include "gnunet_constants.h"
37 #include "gnunet_core_service.h"
38 #include "gnunet_datastore_service.h"
39 #include "gnunet_peer_lib.h"
40 #include "gnunet_protocols.h"
41 #include "gnunet_signatures.h"
42 #include "gnunet_statistics_service.h"
43 #include "gnunet_util_lib.h"
44 #include "gnunet-service-fs_indexing.h"
47 #define DEBUG_FS GNUNET_NO
50 * Maximum number of outgoing messages we queue per peer.
51 * FIXME: make configurable?
53 #define MAX_QUEUE_PER_PEER 16
56 * Inverse of the probability that we will submit the same query
57 * to the same peer again. If the same peer already got the query
58 * repeatedly recently, the probability is multiplied by the inverse
59 * of this number each time. Note that we only try about every TTL_DECREMENT/2
60 * plus MAX_CORK_DELAY (so roughly every 3.5s).
62 #define RETRY_PROBABILITY_INV 3
65 * What is the maximum delay for a P2P FS message (in our interaction
66 * with core)? FS-internal delays are another story. The value is
67 * chosen based on the 32k block size. Given that peers typcially
68 * have at least 1 kb/s bandwidth, 45s waits give us a chance to
69 * transmit one message even to the lowest-bandwidth peers.
71 #define MAX_TRANSMIT_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 45)
76 * Maximum number of requests (from other peers) that we're
77 * willing to have pending at any given point in time.
78 * FIXME: set from configuration.
80 static uint64_t max_pending_requests = (32 * 1024);
84 * Information we keep for each pending reply. The
85 * actual message follows at the end of this struct.
87 struct PendingMessage;
90 * Our connection to the datastore.
92 static struct GNUNET_DATASTORE_Handle *dsh;
96 * Function called upon completion of a transmission.
99 * @param pid ID of receiving peer, 0 on transmission error
101 typedef void (*TransmissionContinuation)(void * cls,
102 GNUNET_PEER_Id tpid);
106 * Information we keep for each pending message (GET/PUT). The
107 * actual message follows at the end of this struct.
109 struct PendingMessage
112 * This is a doubly-linked list of messages to the same peer.
114 struct PendingMessage *next;
117 * This is a doubly-linked list of messages to the same peer.
119 struct PendingMessage *prev;
122 * Entry in pending message list for this pending message.
124 struct PendingMessageList *pml;
127 * Function to call immediately once we have transmitted this
130 TransmissionContinuation cont;
138 * Size of the reply; actual reply message follows
139 * at the end of this struct.
144 * How important is this message for us?
152 * Information about a peer that we are connected to.
153 * We track data that is useful for determining which
154 * peers should receive our requests. We also keep
155 * a list of messages to transmit to this peer.
161 * List of the last clients for which this peer successfully
164 struct GNUNET_SERVER_Client *last_client_replies[CS2P_SUCCESS_LIST_SIZE];
167 * List of the last PIDs for which
168 * this peer successfully answered a query;
169 * We use 0 to indicate no successful reply.
171 GNUNET_PEER_Id last_p2p_replies[P2P_SUCCESS_LIST_SIZE];
174 * Average delay between sending the peer a request and
175 * getting a reply (only calculated over the requests for
176 * which we actually got a reply). Calculated
177 * as a moving average: new_delay = ((n-1)*last_delay+curr_delay) / n
179 struct GNUNET_TIME_Relative avg_delay;
182 * Handle for an active request for transmission to this
185 struct GNUNET_CORE_TransmitHandle *cth;
188 * Messages (replies, queries, content migration) we would like to
189 * send to this peer in the near future. Sorted by priority, head.
191 struct PendingMessage *pending_messages_head;
194 * Messages (replies, queries, content migration) we would like to
195 * send to this peer in the near future. Sorted by priority, tail.
197 struct PendingMessage *pending_messages_tail;
200 * Average priority of successful replies. Calculated
201 * as a moving average: new_avg = ((n-1)*last_avg+curr_prio) / n
206 * Increase in traffic preference still to be submitted
207 * to the core service for this peer. FIXME: double or 'uint64_t'?
209 double inc_preference;
212 * The peer's identity.
217 * Size of the linked list of 'pending_messages'.
219 unsigned int pending_requests;
222 * Which offset in "last_p2p_replies" will be updated next?
223 * (we go round-robin).
225 unsigned int last_p2p_replies_woff;
228 * Which offset in "last_client_replies" will be updated next?
229 * (we go round-robin).
231 unsigned int last_client_replies_woff;
237 * Information we keep for each pending request. We should try to
238 * keep this struct as small as possible since its memory consumption
239 * is key to how many requests we can have pending at once.
241 struct PendingRequest;
245 * Doubly-linked list of requests we are performing
246 * on behalf of the same client.
248 struct ClientRequestList
252 * This is a doubly-linked list.
254 struct ClientRequestList *next;
257 * This is a doubly-linked list.
259 struct ClientRequestList *prev;
262 * Request this entry represents.
264 struct PendingRequest *req;
267 * Client list this request belongs to.
269 struct ClientList *client_list;
275 * Replies to be transmitted to the client. The actual
276 * response message is allocated after this struct.
278 struct ClientResponseMessage
281 * This is a doubly-linked list.
283 struct ClientResponseMessage *next;
286 * This is a doubly-linked list.
288 struct ClientResponseMessage *prev;
291 * Client list entry this response belongs to.
293 struct ClientList *client_list;
296 * Number of bytes in the response.
303 * Linked list of clients we are performing requests
309 * This is a linked list.
311 struct ClientList *next;
314 * ID of a client making a request, NULL if this entry is for a
317 struct GNUNET_SERVER_Client *client;
320 * Head of list of requests performed on behalf
321 * of this client right now.
323 struct ClientRequestList *rl_head;
326 * Tail of list of requests performed on behalf
327 * of this client right now.
329 struct ClientRequestList *rl_tail;
332 * Head of linked list of responses.
334 struct ClientResponseMessage *res_head;
337 * Tail of linked list of responses.
339 struct ClientResponseMessage *res_tail;
342 * Context for sending replies.
344 struct GNUNET_CONNECTION_TransmitHandle *th;
350 * Doubly-linked list of messages we are performing
351 * due to a pending request.
353 struct PendingMessageList
357 * This is a doubly-linked list of messages on behalf of the same request.
359 struct PendingMessageList *next;
362 * This is a doubly-linked list of messages on behalf of the same request.
364 struct PendingMessageList *prev;
367 * Message this entry represents.
369 struct PendingMessage *pm;
372 * Request this entry belongs to.
374 struct PendingRequest *req;
377 * Peer this message is targeted for.
379 struct ConnectedPeer *target;
385 * Information we keep for each pending request. We should try to
386 * keep this struct as small as possible since its memory consumption
387 * is key to how many requests we can have pending at once.
389 struct PendingRequest
393 * If this request was made by a client, this is our entry in the
394 * client request list; otherwise NULL.
396 struct ClientRequestList *client_request_list;
399 * Entry of peer responsible for this entry (if this request
400 * was made by a peer).
402 struct ConnectedPeer *cp;
405 * If this is a namespace query, pointer to the hash of the public
406 * key of the namespace; otherwise NULL. Pointer will be to the
407 * end of this struct (so no need to free it).
409 const GNUNET_HashCode *namespace;
412 * Bloomfilter we use to filter out replies that we don't care about
413 * (anymore). NULL as long as we are interested in all replies.
415 struct GNUNET_CONTAINER_BloomFilter *bf;
418 * Context of our GNUNET_CORE_peer_change_preference call.
420 struct GNUNET_CORE_InformationRequestContext *irc;
423 * Hash code of all replies that we have seen so far (only valid
424 * if client is not NULL since we only track replies like this for
427 GNUNET_HashCode *replies_seen;
430 * Node in the heap representing this entry; NULL
431 * if we have no heap node.
433 struct GNUNET_CONTAINER_HeapNode *hnode;
436 * Head of list of messages being performed on behalf of this
439 struct PendingMessageList *pending_head;
442 * Tail of list of messages being performed on behalf of this
445 struct PendingMessageList *pending_tail;
448 * When did we first see this request (form this peer), or, if our
449 * client is initiating, when did we last initiate a search?
451 struct GNUNET_TIME_Absolute start_time;
454 * The query that this request is for.
456 GNUNET_HashCode query;
459 * The task responsible for transmitting queries
462 GNUNET_SCHEDULER_TaskIdentifier task;
465 * (Interned) Peer identifier that identifies a preferred target
468 GNUNET_PEER_Id target_pid;
471 * (Interned) Peer identifiers of peers that have already
472 * received our query for this content.
474 GNUNET_PEER_Id *used_pids;
477 * Our entry in the queue (non-NULL while we wait for our
478 * turn to interact with the local database).
480 struct GNUNET_DATASTORE_QueueEntry *qe;
484 * Size of the 'bf' (in bytes).
489 * Desired anonymity level; only valid for requests from a local client.
491 uint32_t anonymity_level;
494 * How many entries in "used_pids" are actually valid?
496 unsigned int used_pids_off;
499 * How long is the "used_pids" array?
501 unsigned int used_pids_size;
504 * Number of results found for this request.
506 unsigned int results_found;
509 * How many entries in "replies_seen" are actually valid?
511 unsigned int replies_seen_off;
514 * How long is the "replies_seen" array?
516 unsigned int replies_seen_size;
519 * Priority with which this request was made. If one of our clients
520 * made the request, then this is the current priority that we are
521 * using when initiating the request. This value is used when
522 * we decide to reward other peers with trust for providing a reply.
527 * Priority points left for us to spend when forwarding this request
530 uint32_t remaining_priority;
533 * Number to mingle hashes for bloom-filter tests with.
538 * TTL with which we saw this request (or, if we initiated, TTL that
539 * we used for the request).
544 * Type of the content that this request is for.
546 enum GNUNET_BLOCK_Type type;
549 * Remove this request after transmission of the current response.
554 * GNUNET_YES if we should not forward this request to other peers.
562 * Block that is ready for migration to other peers. Actual data is at the end of the block.
564 struct MigrationReadyBlock
568 * This is a doubly-linked list.
570 struct MigrationReadyBlock *next;
573 * This is a doubly-linked list.
575 struct MigrationReadyBlock *prev;
578 * Query for the block.
580 GNUNET_HashCode query;
583 * When does this block expire?
585 struct GNUNET_TIME_Absolute expiration;
588 * Peers we would consider forwarding this
589 * block to. Zero for empty entries.
591 GNUNET_PEER_Id target_list[MIGRATION_LIST_SIZE];
599 * Number of targets already used.
601 unsigned int used_targets;
606 enum GNUNET_BLOCK_Type type;
613 static struct GNUNET_SCHEDULER_Handle *sched;
618 static const struct GNUNET_CONFIGURATION_Handle *cfg;
621 * Map of peer identifiers to "struct ConnectedPeer" (for that peer).
623 static struct GNUNET_CONTAINER_MultiHashMap *connected_peers;
626 * Map of peer identifiers to "struct PendingRequest" (for that peer).
628 static struct GNUNET_CONTAINER_MultiHashMap *peer_request_map;
631 * Map of query identifiers to "struct PendingRequest" (for that query).
633 static struct GNUNET_CONTAINER_MultiHashMap *query_request_map;
636 * Heap with the request that will expire next at the top. Contains
637 * pointers of type "struct PendingRequest*"; these will *also* be
638 * aliased from the "requests_by_peer" data structures and the
639 * "requests_by_query" table. Note that requests from our clients
640 * don't expire and are thus NOT in the "requests_by_expiration"
641 * (or the "requests_by_peer" tables).
643 static struct GNUNET_CONTAINER_Heap *requests_by_expiration_heap;
646 * Handle for reporting statistics.
648 static struct GNUNET_STATISTICS_Handle *stats;
651 * Linked list of clients we are currently processing requests for.
653 static struct ClientList *client_list;
656 * Pointer to handle to the core service (points to NULL until we've
659 static struct GNUNET_CORE_Handle *core;
662 * Head of linked list of blocks that can be migrated.
664 static struct MigrationReadyBlock *mig_head;
667 * Tail of linked list of blocks that can be migrated.
669 static struct MigrationReadyBlock *mig_tail;
672 * Request to datastore for migration (or NULL).
674 static struct GNUNET_DATASTORE_QueueEntry *mig_qe;
677 * ID of task that collects blocks for migration.
679 static GNUNET_SCHEDULER_TaskIdentifier mig_task;
682 * What is the maximum frequency at which we are allowed to
683 * poll the datastore for migration content?
685 static struct GNUNET_TIME_Relative min_migration_delay;
688 * Size of the doubly-linked list of migration blocks.
690 static unsigned int mig_size;
693 * Are we allowed to migrate content to this peer.
695 static int active_migration;
699 * Transmit messages by copying it to the target buffer
700 * "buf". "buf" will be NULL and "size" zero if the socket was closed
701 * for writing in the meantime. In that case, do nothing
702 * (the disconnect or shutdown handler will take care of the rest).
703 * If we were able to transmit messages and there are still more
704 * pending, ask core again for further calls to this function.
706 * @param cls closure, pointer to the 'struct ConnectedPeer*'
707 * @param size number of bytes available in buf
708 * @param buf where the callee should write the message
709 * @return number of bytes written to buf
712 transmit_to_peer (void *cls,
713 size_t size, void *buf);
716 /* ******************* clean up functions ************************ */
720 * Delete the given migration block.
722 * @param mb block to delete
725 delete_migration_block (struct MigrationReadyBlock *mb)
727 GNUNET_CONTAINER_DLL_remove (mig_head,
730 GNUNET_PEER_decrement_rcs (mb->target_list,
731 MIGRATION_LIST_SIZE);
738 * Compare the distance of two peers to a key.
741 * @param p1 first peer
742 * @param p2 second peer
743 * @return GNUNET_YES if P1 is closer to key than P2
746 is_closer (const GNUNET_HashCode *key,
747 const struct GNUNET_PeerIdentity *p1,
748 const struct GNUNET_PeerIdentity *p2)
750 return GNUNET_CRYPTO_hash_xorcmp (&p1->hashPubKey,
757 * Consider migrating content to a given peer.
759 * @param cls 'struct MigrationReadyBlock*' to select
760 * targets for (or NULL for none)
761 * @param key ID of the peer
762 * @param value 'struct ConnectedPeer' of the peer
763 * @return GNUNET_YES (always continue iteration)2
766 consider_migration (void *cls,
767 const GNUNET_HashCode *key,
770 struct MigrationReadyBlock *mb = cls;
771 struct ConnectedPeer *cp = value;
772 struct MigrationReadyBlock *pos;
773 struct GNUNET_PeerIdentity cppid;
774 struct GNUNET_PeerIdentity otherpid;
775 struct GNUNET_PeerIdentity worstpid;
780 /* consider 'cp' as a migration target for mb */
783 GNUNET_PEER_resolve (cp->pid,
785 repl = MIGRATION_LIST_SIZE;
786 for (i=0;i<MIGRATION_LIST_SIZE;i++)
788 if (mb->target_list[i] == 0)
790 mb->target_list[i] = cp->pid;
791 GNUNET_PEER_change_rc (mb->target_list[i], 1);
792 repl = MIGRATION_LIST_SIZE;
795 GNUNET_PEER_resolve (mb->target_list[i],
797 if ( (repl == MIGRATION_LIST_SIZE) &&
798 is_closer (&mb->query,
805 else if ( (repl != MIGRATION_LIST_SIZE) &&
806 (is_closer (&mb->query,
814 if (repl != MIGRATION_LIST_SIZE)
816 GNUNET_PEER_change_rc (mb->target_list[repl], -1);
817 mb->target_list[repl] = cp->pid;
818 GNUNET_PEER_change_rc (mb->target_list[repl], 1);
822 /* consider scheduling transmission to cp for content migration */
829 for (i=0;i<MIGRATION_LIST_SIZE;i++)
831 if (cp->pid == pos->target_list[i])
836 msize = GNUNET_MIN (msize,
844 return GNUNET_YES; /* no content available */
846 = GNUNET_CORE_notify_transmit_ready (core,
847 0, GNUNET_TIME_UNIT_FOREVER_REL,
848 (const struct GNUNET_PeerIdentity*) key,
849 msize + sizeof (struct PutMessage),
857 * Task that is run periodically to obtain blocks for content
861 * @param tc scheduler context (also unused)
864 gather_migration_blocks (void *cls,
865 const struct GNUNET_SCHEDULER_TaskContext *tc);
869 * If the migration task is not currently running, consider
870 * (re)scheduling it with the appropriate delay.
873 consider_migration_gathering ()
875 struct GNUNET_TIME_Relative delay;
879 if (mig_task != GNUNET_SCHEDULER_NO_TASK)
881 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
883 delay = GNUNET_TIME_relative_divide (GNUNET_TIME_UNIT_SECONDS,
884 MAX_MIGRATION_QUEUE);
885 delay = GNUNET_TIME_relative_max (delay,
886 min_migration_delay);
887 mig_task = GNUNET_SCHEDULER_add_delayed (sched,
889 &gather_migration_blocks,
895 * Process content offered for migration.
898 * @param key key for the content
899 * @param size number of bytes in data
900 * @param data content stored
901 * @param type type of the content
902 * @param priority priority of the content
903 * @param anonymity anonymity-level for the content
904 * @param expiration expiration time for the content
905 * @param uid unique identifier for the datum;
906 * maybe 0 if no unique identifier is available
909 process_migration_content (void *cls,
910 const GNUNET_HashCode * key,
913 enum GNUNET_BLOCK_Type type,
916 struct GNUNET_TIME_Absolute
917 expiration, uint64_t uid)
919 struct MigrationReadyBlock *mb;
924 if (mig_size < MAX_MIGRATION_QUEUE)
925 consider_migration_gathering ();
928 if (type == GNUNET_BLOCK_TYPE_ONDEMAND)
931 GNUNET_FS_handle_on_demand_block (key, size, data,
932 type, priority, anonymity,
934 &process_migration_content,
936 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
939 mb = GNUNET_malloc (sizeof (struct MigrationReadyBlock) + size);
941 mb->expiration = expiration;
944 memcpy (&mb[1], data, size);
945 GNUNET_CONTAINER_DLL_insert_after (mig_head,
950 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
953 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
958 * Task that is run periodically to obtain blocks for content
962 * @param tc scheduler context (also unused)
965 gather_migration_blocks (void *cls,
966 const struct GNUNET_SCHEDULER_TaskContext *tc)
968 mig_task = GNUNET_SCHEDULER_NO_TASK;
969 mig_qe = GNUNET_DATASTORE_get_random (dsh, 0, -1,
970 GNUNET_TIME_UNIT_FOREVER_REL,
971 &process_migration_content, NULL);
972 GNUNET_assert (mig_qe != NULL);
977 * We're done with a particular message list entry.
978 * Free all associated resources.
980 * @param pml entry to destroy
983 destroy_pending_message_list_entry (struct PendingMessageList *pml)
985 GNUNET_CONTAINER_DLL_remove (pml->req->pending_head,
986 pml->req->pending_tail,
988 GNUNET_CONTAINER_DLL_remove (pml->target->pending_messages_head,
989 pml->target->pending_messages_tail,
991 pml->target->pending_requests--;
992 GNUNET_free (pml->pm);
998 * Destroy the given pending message (and call the respective
1001 * @param pm message to destroy
1002 * @param tpid id of peer that the message was delivered to, or 0 for none
1005 destroy_pending_message (struct PendingMessage *pm,
1006 GNUNET_PEER_Id tpid)
1008 struct PendingMessageList *pml = pm->pml;
1009 TransmissionContinuation cont;
1012 GNUNET_assert (pml->pm == pm);
1013 GNUNET_assert ( (tpid == 0) || (tpid == pml->target->pid) );
1015 cont_cls = pm->cont_cls;
1016 destroy_pending_message_list_entry (pml);
1017 cont (cont_cls, tpid);
1022 * We're done processing a particular request.
1023 * Free all associated resources.
1025 * @param pr request to destroy
1028 destroy_pending_request (struct PendingRequest *pr)
1030 struct GNUNET_PeerIdentity pid;
1032 if (pr->hnode != NULL)
1034 GNUNET_CONTAINER_heap_remove_node (requests_by_expiration_heap,
1038 if (NULL == pr->client_request_list)
1040 GNUNET_STATISTICS_update (stats,
1041 gettext_noop ("# P2P searches active"),
1047 GNUNET_STATISTICS_update (stats,
1048 gettext_noop ("# client searches active"),
1052 /* might have already been removed from map in 'process_reply' (if
1053 there was a unique reply) or never inserted if it was a
1054 duplicate; hence ignore the return value here */
1055 (void) GNUNET_CONTAINER_multihashmap_remove (query_request_map,
1060 GNUNET_DATASTORE_cancel (pr->qe);
1063 if (pr->client_request_list != NULL)
1065 GNUNET_CONTAINER_DLL_remove (pr->client_request_list->client_list->rl_head,
1066 pr->client_request_list->client_list->rl_tail,
1067 pr->client_request_list);
1068 GNUNET_free (pr->client_request_list);
1069 pr->client_request_list = NULL;
1073 GNUNET_PEER_resolve (pr->cp->pid,
1075 (void) GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
1082 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
1085 if (pr->irc != NULL)
1087 GNUNET_CORE_peer_change_preference_cancel (pr->irc);
1090 if (pr->replies_seen != NULL)
1092 GNUNET_free (pr->replies_seen);
1093 pr->replies_seen = NULL;
1095 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
1097 GNUNET_SCHEDULER_cancel (sched,
1099 pr->task = GNUNET_SCHEDULER_NO_TASK;
1101 while (NULL != pr->pending_head)
1102 destroy_pending_message_list_entry (pr->pending_head);
1103 GNUNET_PEER_change_rc (pr->target_pid, -1);
1104 if (pr->used_pids != NULL)
1106 GNUNET_PEER_decrement_rcs (pr->used_pids, pr->used_pids_off);
1107 GNUNET_free (pr->used_pids);
1108 pr->used_pids_off = 0;
1109 pr->used_pids_size = 0;
1110 pr->used_pids = NULL;
1117 * Method called whenever a given peer connects.
1119 * @param cls closure, not used
1120 * @param peer peer identity this notification is about
1121 * @param latency reported latency of the connection with 'other'
1122 * @param distance reported distance (DV) to 'other'
1125 peer_connect_handler (void *cls,
1127 GNUNET_PeerIdentity * peer,
1128 struct GNUNET_TIME_Relative latency,
1131 struct ConnectedPeer *cp;
1132 struct MigrationReadyBlock *pos;
1134 cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
1135 cp->pid = GNUNET_PEER_intern (peer);
1136 GNUNET_break (GNUNET_OK ==
1137 GNUNET_CONTAINER_multihashmap_put (connected_peers,
1140 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1145 (void) consider_migration (pos, &peer->hashPubKey, cp);
1153 * Free (each) request made by the peer.
1155 * @param cls closure, points to peer that the request belongs to
1156 * @param key current key code
1157 * @param value value in the hash map
1158 * @return GNUNET_YES (we should continue to iterate)
1161 destroy_request (void *cls,
1162 const GNUNET_HashCode * key,
1165 const struct GNUNET_PeerIdentity * peer = cls;
1166 struct PendingRequest *pr = value;
1168 GNUNET_break (GNUNET_YES ==
1169 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
1172 destroy_pending_request (pr);
1178 * Method called whenever a peer disconnects.
1180 * @param cls closure, not used
1181 * @param peer peer identity this notification is about
1184 peer_disconnect_handler (void *cls,
1186 GNUNET_PeerIdentity * peer)
1188 struct ConnectedPeer *cp;
1189 struct PendingMessage *pm;
1191 struct MigrationReadyBlock *pos;
1192 struct MigrationReadyBlock *next;
1194 GNUNET_CONTAINER_multihashmap_get_multiple (peer_request_map,
1198 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1202 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1204 if (NULL != cp->last_client_replies[i])
1206 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1207 cp->last_client_replies[i] = NULL;
1210 GNUNET_break (GNUNET_YES ==
1211 GNUNET_CONTAINER_multihashmap_remove (connected_peers,
1214 /* remove this peer from migration considerations; schedule
1217 while (NULL != (pos = next))
1220 for (i=0;i<MIGRATION_LIST_SIZE;i++)
1222 if (pos->target_list[i] == cp->pid)
1224 GNUNET_PEER_change_rc (pos->target_list[i], -1);
1225 pos->target_list[i] = 0;
1226 if (pos->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers))
1228 delete_migration_block (pos);
1229 consider_migration_gathering ();
1232 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1233 &consider_migration,
1240 GNUNET_PEER_change_rc (cp->pid, -1);
1241 GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
1242 if (NULL != cp->cth)
1243 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
1244 while (NULL != (pm = cp->pending_messages_head))
1245 destroy_pending_message (pm, 0 /* delivery failed */);
1246 GNUNET_break (0 == cp->pending_requests);
1252 * Iterator over hash map entries that removes all occurences
1253 * of the given 'client' from the 'last_client_replies' of the
1254 * given connected peer.
1256 * @param cls closure, the 'struct GNUNET_SERVER_Client*' to remove
1257 * @param key current key code (unused)
1258 * @param value value in the hash map (the 'struct ConnectedPeer*' to change)
1259 * @return GNUNET_YES (we should continue to iterate)
1262 remove_client_from_last_client_replies (void *cls,
1263 const GNUNET_HashCode * key,
1266 struct GNUNET_SERVER_Client *client = cls;
1267 struct ConnectedPeer *cp = value;
1270 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1272 if (cp->last_client_replies[i] == client)
1274 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1275 cp->last_client_replies[i] = NULL;
1283 * A client disconnected. Remove all of its pending queries.
1285 * @param cls closure, NULL
1286 * @param client identification of the client
1289 handle_client_disconnect (void *cls,
1290 struct GNUNET_SERVER_Client
1293 struct ClientList *pos;
1294 struct ClientList *prev;
1295 struct ClientRequestList *rcl;
1296 struct ClientResponseMessage *creply;
1302 while ( (NULL != pos) &&
1303 (pos->client != client) )
1309 return; /* no requests pending for this client */
1310 while (NULL != (rcl = pos->rl_head))
1312 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1313 "Destroying pending request `%s' on disconnect\n",
1314 GNUNET_h2s (&rcl->req->query));
1315 destroy_pending_request (rcl->req);
1318 client_list = pos->next;
1320 prev->next = pos->next;
1321 if (pos->th != NULL)
1323 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
1326 while (NULL != (creply = pos->res_head))
1328 GNUNET_CONTAINER_DLL_remove (pos->res_head,
1331 GNUNET_free (creply);
1333 GNUNET_SERVER_client_drop (pos->client);
1335 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1336 &remove_client_from_last_client_replies,
1342 * Iterator to free peer entries.
1344 * @param cls closure, unused
1345 * @param key current key code
1346 * @param value value in the hash map (peer entry)
1347 * @return GNUNET_YES (we should continue to iterate)
1350 clean_peer (void *cls,
1351 const GNUNET_HashCode * key,
1354 peer_disconnect_handler (NULL, (const struct GNUNET_PeerIdentity*) key);
1360 * Task run during shutdown.
1366 shutdown_task (void *cls,
1367 const struct GNUNET_SCHEDULER_TaskContext *tc)
1371 GNUNET_DATASTORE_cancel (mig_qe);
1374 if (GNUNET_SCHEDULER_NO_TASK != mig_task)
1376 GNUNET_SCHEDULER_cancel (sched, mig_task);
1377 mig_task = GNUNET_SCHEDULER_NO_TASK;
1379 while (client_list != NULL)
1380 handle_client_disconnect (NULL,
1381 client_list->client);
1382 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1385 GNUNET_break (0 == GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap));
1386 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
1387 requests_by_expiration_heap = 0;
1388 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
1389 connected_peers = NULL;
1390 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (query_request_map));
1391 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
1392 query_request_map = NULL;
1393 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (peer_request_map));
1394 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
1395 peer_request_map = NULL;
1396 GNUNET_assert (NULL != core);
1397 GNUNET_CORE_disconnect (core);
1401 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1404 GNUNET_DATASTORE_disconnect (dsh,
1406 while (mig_head != NULL)
1407 delete_migration_block (mig_head);
1408 GNUNET_assert (0 == mig_size);
1415 /* ******************* Utility functions ******************** */
1419 * Transmit messages by copying it to the target buffer
1420 * "buf". "buf" will be NULL and "size" zero if the socket was closed
1421 * for writing in the meantime. In that case, do nothing
1422 * (the disconnect or shutdown handler will take care of the rest).
1423 * If we were able to transmit messages and there are still more
1424 * pending, ask core again for further calls to this function.
1426 * @param cls closure, pointer to the 'struct ConnectedPeer*'
1427 * @param size number of bytes available in buf
1428 * @param buf where the callee should write the message
1429 * @return number of bytes written to buf
1432 transmit_to_peer (void *cls,
1433 size_t size, void *buf)
1435 struct ConnectedPeer *cp = cls;
1437 struct GNUNET_PeerIdentity pid;
1438 struct PendingMessage *pm;
1439 struct MigrationReadyBlock *mb;
1440 struct MigrationReadyBlock *next;
1441 struct PutMessage migm;
1449 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1450 "Dropping message, core too busy.\n");
1455 while ( (NULL != (pm = cp->pending_messages_head) ) &&
1456 (pm->msize <= size) )
1458 memcpy (&cbuf[msize], &pm[1], pm->msize);
1461 destroy_pending_message (pm, cp->pid);
1465 GNUNET_PEER_resolve (cp->pid,
1467 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1469 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1478 while (NULL != (mb = next))
1481 for (i=0;i<MIGRATION_LIST_SIZE;i++)
1483 if ( (cp->pid == mb->target_list[i]) &&
1484 (mb->size + sizeof (migm) <= size) )
1486 GNUNET_PEER_change_rc (mb->target_list[i], -1);
1487 mb->target_list[i] = 0;
1489 migm.header.size = htons (sizeof (migm) + mb->size);
1490 migm.header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
1491 migm.type = htonl (mb->type);
1492 migm.expiration = GNUNET_TIME_absolute_hton (mb->expiration);
1493 memcpy (&cbuf[msize], &migm, sizeof (migm));
1494 msize += sizeof (migm);
1495 size -= sizeof (migm);
1496 memcpy (&cbuf[msize], &mb[1], mb->size);
1502 if ( (mb->used_targets >= MIGRATION_TARGET_COUNT) ||
1503 (mb->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers)) )
1505 delete_migration_block (mb);
1506 consider_migration_gathering ();
1509 consider_migration (NULL,
1514 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1515 "Transmitting %u bytes to peer %u\n",
1524 * Add a message to the set of pending messages for the given peer.
1526 * @param cp peer to send message to
1527 * @param pm message to queue
1528 * @param pr request on which behalf this message is being queued
1531 add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
1532 struct PendingMessage *pm,
1533 struct PendingRequest *pr)
1535 struct PendingMessage *pos;
1536 struct PendingMessageList *pml;
1537 struct GNUNET_PeerIdentity pid;
1539 GNUNET_assert (pm->next == NULL);
1540 GNUNET_assert (pm->pml == NULL);
1541 pml = GNUNET_malloc (sizeof (struct PendingMessageList));
1546 GNUNET_CONTAINER_DLL_insert (pr->pending_head,
1549 pos = cp->pending_messages_head;
1550 while ( (pos != NULL) &&
1551 (pm->priority < pos->priority) )
1553 GNUNET_CONTAINER_DLL_insert_after (cp->pending_messages_head,
1554 cp->pending_messages_tail,
1557 cp->pending_requests++;
1558 if (cp->pending_requests > MAX_QUEUE_PER_PEER)
1559 destroy_pending_message (cp->pending_messages_tail, 0);
1560 GNUNET_PEER_resolve (cp->pid, &pid);
1561 if (NULL != cp->cth)
1562 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
1563 /* need to schedule transmission */
1564 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1565 cp->pending_messages_head->priority,
1568 cp->pending_messages_head->msize,
1571 if (cp->cth == NULL)
1574 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1575 "Failed to schedule transmission with core!\n");
1577 /* FIXME: call stats (rare, bad case) */
1583 * Mingle hash with the mingle_number to produce different bits.
1586 mingle_hash (const GNUNET_HashCode * in,
1587 int32_t mingle_number,
1588 GNUNET_HashCode * hc)
1592 GNUNET_CRYPTO_hash (&mingle_number,
1595 GNUNET_CRYPTO_hash_xor (&m, in, hc);
1600 * Test if the load on this peer is too high
1601 * to even consider processing the query at
1604 * @return GNUNET_YES if the load is too high, GNUNET_NO otherwise
1607 test_load_too_high ()
1609 return GNUNET_NO; // FIXME
1613 /* ******************* Pending Request Refresh Task ******************** */
1618 * We use a random delay to make the timing of requests less
1619 * predictable. This function returns such a random delay. We add a base
1620 * delay of MAX_CORK_DELAY (1s).
1622 * FIXME: make schedule dependent on the specifics of the request?
1623 * Or bandwidth and number of connected peers and load?
1625 * @return random delay to use for some request, between 1s and 1000+TTL_DECREMENT ms
1627 static struct GNUNET_TIME_Relative
1628 get_processing_delay ()
1631 GNUNET_TIME_relative_add (GNUNET_CONSTANTS_MAX_CORK_DELAY,
1632 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1633 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1639 * We're processing a GET request from another peer and have decided
1640 * to forward it to other peers. This function is called periodically
1641 * and should forward the request to other peers until we have all
1642 * possible replies. If we have transmitted the *only* reply to
1643 * the initiator we should destroy the pending request. If we have
1644 * many replies in the queue to the initiator, we should delay sending
1645 * out more queries until the reply queue has shrunk some.
1647 * @param cls our "struct ProcessGetContext *"
1651 forward_request_task (void *cls,
1652 const struct GNUNET_SCHEDULER_TaskContext *tc);
1656 * Function called after we either failed or succeeded
1657 * at transmitting a query to a peer.
1659 * @param cls the requests "struct PendingRequest*"
1660 * @param tpid ID of receiving peer, 0 on transmission error
1663 transmit_query_continuation (void *cls,
1664 GNUNET_PEER_Id tpid)
1666 struct PendingRequest *pr = cls;
1668 GNUNET_STATISTICS_update (stats,
1669 gettext_noop ("# queries scheduled for forwarding"),
1675 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1676 "Transmission of request failed, will try again later.\n");
1678 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1679 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1680 get_processing_delay (),
1681 &forward_request_task,
1685 GNUNET_STATISTICS_update (stats,
1686 gettext_noop ("# queries forwarded"),
1689 GNUNET_PEER_change_rc (tpid, 1);
1690 if (pr->used_pids_off == pr->used_pids_size)
1691 GNUNET_array_grow (pr->used_pids,
1693 pr->used_pids_size * 2 + 2);
1694 pr->used_pids[pr->used_pids_off++] = tpid;
1695 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1696 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1697 get_processing_delay (),
1698 &forward_request_task,
1704 * How many bytes should a bloomfilter be if we have already seen
1705 * entry_count responses? Note that BLOOMFILTER_K gives us the number
1706 * of bits set per entry. Furthermore, we should not re-size the
1707 * filter too often (to keep it cheap).
1709 * Since other peers will also add entries but not resize the filter,
1710 * we should generally pick a slightly larger size than what the
1711 * strict math would suggest.
1713 * @return must be a power of two and smaller or equal to 2^15.
1716 compute_bloomfilter_size (unsigned int entry_count)
1719 unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
1720 uint16_t max = 1 << 15;
1722 if (entry_count > max)
1725 while ((size < max) && (size < ideal))
1734 * Recalculate our bloom filter for filtering replies. This function
1735 * will create a new bloom filter from scratch, so it should only be
1736 * called if we have no bloomfilter at all (and hence can create a
1737 * fresh one of minimal size without problems) OR if our peer is the
1738 * initiator (in which case we may resize to larger than mimimum size).
1740 * @param pr request for which the BF is to be recomputed
1743 refresh_bloomfilter (struct PendingRequest *pr)
1747 GNUNET_HashCode mhash;
1749 nsize = compute_bloomfilter_size (pr->replies_seen_off);
1750 if (nsize == pr->bf_size)
1751 return; /* size not changed */
1753 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
1754 pr->bf_size = nsize;
1755 pr->mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
1756 pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1759 for (i=0;i<pr->replies_seen_off;i++)
1761 mingle_hash (&pr->replies_seen[i], pr->mingle, &mhash);
1762 GNUNET_CONTAINER_bloomfilter_add (pr->bf, &mhash);
1768 * Function called after we've tried to reserve a certain amount of
1769 * bandwidth for a reply. Check if we succeeded and if so send our
1772 * @param cls the requests "struct PendingRequest*"
1773 * @param peer identifies the peer
1774 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1775 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1776 * @param amount set to the amount that was actually reserved or unreserved
1777 * @param preference current traffic preference for the given peer
1780 target_reservation_cb (void *cls,
1782 GNUNET_PeerIdentity * peer,
1783 struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
1784 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1786 uint64_t preference)
1788 struct PendingRequest *pr = cls;
1789 struct ConnectedPeer *cp;
1790 struct PendingMessage *pm;
1791 struct GetMessage *gm;
1792 GNUNET_HashCode *ext;
1802 /* error in communication with core, try again later */
1803 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1804 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1805 get_processing_delay (),
1806 &forward_request_task,
1810 // (3) transmit, update ttl/priority
1811 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1815 /* Peer must have just left */
1817 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1818 "Selected peer disconnected!\n");
1820 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1821 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1822 get_processing_delay (),
1823 &forward_request_task,
1827 no_route = GNUNET_NO;
1828 /* FIXME: check against DBLOCK_SIZE and possibly return
1829 amount to reserve; however, this also needs to work
1830 with testcases which currently start out with a far
1831 too low per-peer bw limit, so they would never send
1832 anything. Big issue. */
1838 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1839 "Failed to reserve bandwidth for reply (got %d/%u bytes only)!\n",
1843 GNUNET_STATISTICS_update (stats,
1844 gettext_noop ("# reply bandwidth reservation requests failed"),
1847 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1848 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1849 get_processing_delay (),
1850 &forward_request_task,
1852 return; /* this target round failed */
1854 /* FIXME: if we are "quite" busy, we may still want to skip
1855 this round; need more load detection code! */
1856 no_route = GNUNET_YES;
1859 GNUNET_STATISTICS_update (stats,
1860 gettext_noop ("# queries scheduled for forwarding"),
1863 /* build message and insert message into priority queue */
1865 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1866 "Forwarding request `%s' to `%4s'!\n",
1867 GNUNET_h2s (&pr->query),
1872 if (GNUNET_YES == no_route)
1874 bm |= GET_MESSAGE_BIT_RETURN_TO;
1877 if (pr->namespace != NULL)
1879 bm |= GET_MESSAGE_BIT_SKS_NAMESPACE;
1882 if (pr->target_pid != 0)
1884 bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
1887 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
1888 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1889 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1891 gm = (struct GetMessage*) &pm[1];
1892 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
1893 gm->header.size = htons (msize);
1894 gm->type = htonl (pr->type);
1895 pr->remaining_priority /= 2;
1896 gm->priority = htonl (pr->remaining_priority);
1897 gm->ttl = htonl (pr->ttl);
1898 gm->filter_mutator = htonl(pr->mingle);
1899 gm->hash_bitmap = htonl (bm);
1900 gm->query = pr->query;
1901 ext = (GNUNET_HashCode*) &gm[1];
1903 if (GNUNET_YES == no_route)
1904 GNUNET_PEER_resolve (pr->cp->pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1905 if (pr->namespace != NULL)
1906 memcpy (&ext[k++], pr->namespace, sizeof (GNUNET_HashCode));
1907 if (pr->target_pid != 0)
1908 GNUNET_PEER_resolve (pr->target_pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1909 bfdata = (char *) &ext[k];
1911 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
1914 pm->cont = &transmit_query_continuation;
1916 add_to_pending_messages_for_peer (cp, pm, pr);
1921 * Closure used for "target_peer_select_cb".
1923 struct PeerSelectionContext
1926 * The request for which we are selecting
1929 struct PendingRequest *pr;
1932 * Current "prime" target.
1934 struct GNUNET_PeerIdentity target;
1937 * How much do we like this target?
1939 double target_score;
1945 * Function called for each connected peer to determine
1946 * which one(s) would make good targets for forwarding.
1948 * @param cls closure (struct PeerSelectionContext)
1949 * @param key current key code (peer identity)
1950 * @param value value in the hash map (struct ConnectedPeer)
1951 * @return GNUNET_YES if we should continue to
1956 target_peer_select_cb (void *cls,
1957 const GNUNET_HashCode * key,
1960 struct PeerSelectionContext *psc = cls;
1961 struct ConnectedPeer *cp = value;
1962 struct PendingRequest *pr = psc->pr;
1967 /* 1) check that this peer is not the initiator */
1969 return GNUNET_YES; /* skip */
1971 /* 2) check if we have already (recently) forwarded to this peer */
1973 for (i=0;i<pr->used_pids_off;i++)
1974 if (pr->used_pids[i] == cp->pid)
1977 if (0 != GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1978 RETRY_PROBABILITY_INV))
1981 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1982 "NOT re-trying query that was previously transmitted %u times\n",
1983 (unsigned int) pr->used_pids_off);
1985 return GNUNET_YES; /* skip */
1990 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1991 "Re-trying query that was previously transmitted %u times to this peer\n",
1994 // 3) calculate how much we'd like to forward to this peer
1995 score = 42; // FIXME!
1996 // FIXME: also need API to gather data on responsiveness
1997 // of this peer (we have fields for that in 'cp', but
1998 // they are never set!)
2000 /* store best-fit in closure */
2001 if (score > psc->target_score)
2003 psc->target_score = score;
2004 psc->target.hashPubKey = *key;
2011 * The priority level imposes a bound on the maximum
2012 * value for the ttl that can be requested.
2014 * @param ttl_in requested ttl
2015 * @param prio given priority
2016 * @return ttl_in if ttl_in is below the limit,
2017 * otherwise the ttl-limit for the given priority
2020 bound_ttl (int32_t ttl_in, uint32_t prio)
2022 unsigned long long allowed;
2026 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
2027 if (ttl_in > allowed)
2029 if (allowed >= (1 << 30))
2038 * We're processing a GET request from another peer and have decided
2039 * to forward it to other peers. This function is called periodically
2040 * and should forward the request to other peers until we have all
2041 * possible replies. If we have transmitted the *only* reply to
2042 * the initiator we should destroy the pending request. If we have
2043 * many replies in the queue to the initiator, we should delay sending
2044 * out more queries until the reply queue has shrunk some.
2046 * @param cls our "struct ProcessGetContext *"
2050 forward_request_task (void *cls,
2051 const struct GNUNET_SCHEDULER_TaskContext *tc)
2053 struct PendingRequest *pr = cls;
2054 struct PeerSelectionContext psc;
2055 struct ConnectedPeer *cp;
2056 struct GNUNET_TIME_Relative delay;
2058 pr->task = GNUNET_SCHEDULER_NO_TASK;
2059 if (pr->irc != NULL)
2062 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2063 "Forwarding of query `%s' not attempted due to pending local lookup!\n",
2064 GNUNET_h2s (&pr->query));
2066 return; /* already pending */
2068 if (GNUNET_YES == pr->local_only)
2069 return; /* configured to not do P2P search */
2070 /* (1) select target */
2072 psc.target_score = DBL_MIN;
2073 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
2074 &target_peer_select_cb,
2076 if (psc.target_score == DBL_MIN)
2078 delay = get_processing_delay ();
2080 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2081 "No peer selected for forwarding of query `%s', will try again in %llu ms!\n",
2082 GNUNET_h2s (&pr->query),
2085 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
2087 &forward_request_task,
2089 return; /* nobody selected */
2091 /* (3) update TTL/priority */
2093 if (pr->client_request_list != NULL)
2095 /* FIXME: use better algorithm!? */
2096 if (0 == GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2099 /* FIXME: bound priority by "customary" priority used by other peers
2101 pr->ttl = bound_ttl (pr->ttl + TTL_DECREMENT * 2,
2104 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2105 "Trying query `%s' with priority %u and TTL %d.\n",
2106 GNUNET_h2s (&pr->query),
2113 /* FIXME: should we do something here as well!? */
2116 /* (3) reserve reply bandwidth */
2117 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2118 &psc.target.hashPubKey);
2119 GNUNET_assert (NULL != cp);
2120 pr->irc = GNUNET_CORE_peer_change_preference (sched, cfg,
2122 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
2123 GNUNET_BANDWIDTH_value_init ((uint32_t) -1 /* no limit */),
2125 (uint64_t) cp->inc_preference,
2126 &target_reservation_cb,
2128 cp->inc_preference = 0.0;
2132 /* **************************** P2P PUT Handling ************************ */
2136 * Function called after we either failed or succeeded
2137 * at transmitting a reply to a peer.
2139 * @param cls the requests "struct PendingRequest*"
2140 * @param tpid ID of receiving peer, 0 on transmission error
2143 transmit_reply_continuation (void *cls,
2144 GNUNET_PEER_Id tpid)
2146 struct PendingRequest *pr = cls;
2150 case GNUNET_BLOCK_TYPE_DBLOCK:
2151 case GNUNET_BLOCK_TYPE_IBLOCK:
2152 /* only one reply expected, done with the request! */
2153 destroy_pending_request (pr);
2155 case GNUNET_BLOCK_TYPE_ANY:
2156 case GNUNET_BLOCK_TYPE_KBLOCK:
2157 case GNUNET_BLOCK_TYPE_SBLOCK:
2167 * Transmit the given message by copying it to the target buffer
2168 * "buf". "buf" will be NULL and "size" zero if the socket was closed
2169 * for writing in the meantime. In that case, do nothing
2170 * (the disconnect or shutdown handler will take care of the rest).
2171 * If we were able to transmit messages and there are still more
2172 * pending, ask core again for further calls to this function.
2174 * @param cls closure, pointer to the 'struct ClientList*'
2175 * @param size number of bytes available in buf
2176 * @param buf where the callee should write the message
2177 * @return number of bytes written to buf
2180 transmit_to_client (void *cls,
2181 size_t size, void *buf)
2183 struct ClientList *cl = cls;
2185 struct ClientResponseMessage *creply;
2192 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2193 "Not sending reply, client communication problem.\n");
2198 while ( (NULL != (creply = cl->res_head) ) &&
2199 (creply->msize <= size) )
2201 memcpy (&cbuf[msize], &creply[1], creply->msize);
2202 msize += creply->msize;
2203 size -= creply->msize;
2204 GNUNET_CONTAINER_DLL_remove (cl->res_head,
2207 GNUNET_free (creply);
2210 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
2212 GNUNET_TIME_UNIT_FOREVER_REL,
2213 &transmit_to_client,
2216 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2217 "Transmitted %u bytes to client\n",
2218 (unsigned int) msize);
2225 * Closure for "process_reply" function.
2227 struct ProcessReplyClosure
2230 * The data for the reply.
2235 * Who gave us this reply? NULL for local host.
2237 struct ConnectedPeer *sender;
2240 * When the reply expires.
2242 struct GNUNET_TIME_Absolute expiration;
2250 * Namespace that this reply belongs to
2251 * (if it is of type SBLOCK).
2253 GNUNET_HashCode namespace;
2256 * Type of the block.
2258 enum GNUNET_BLOCK_Type type;
2261 * How much was this reply worth to us?
2268 * We have received a reply; handle it!
2270 * @param cls response (struct ProcessReplyClosure)
2271 * @param key our query
2272 * @param value value in the hash map (info about the query)
2273 * @return GNUNET_YES (we should continue to iterate)
2276 process_reply (void *cls,
2277 const GNUNET_HashCode * key,
2280 struct ProcessReplyClosure *prq = cls;
2281 struct PendingRequest *pr = value;
2282 struct PendingMessage *reply;
2283 struct ClientResponseMessage *creply;
2284 struct ClientList *cl;
2285 struct PutMessage *pm;
2286 struct ConnectedPeer *cp;
2287 struct GNUNET_TIME_Relative cur_delay;
2288 GNUNET_HashCode chash;
2289 GNUNET_HashCode mhash;
2293 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2294 "Matched result (type %u) for query `%s' with pending request\n",
2295 (unsigned int) prq->type,
2298 GNUNET_STATISTICS_update (stats,
2299 gettext_noop ("# replies received and matched"),
2302 if (prq->sender != NULL)
2304 /* FIXME: should we be more precise here and not use
2305 "start_time" but a peer-specific time stamp? */
2306 cur_delay = GNUNET_TIME_absolute_get_duration (pr->start_time);
2307 prq->sender->avg_delay.value
2308 = (prq->sender->avg_delay.value *
2309 (RUNAVG_DELAY_N - 1) + cur_delay.value) / RUNAVG_DELAY_N;
2310 prq->sender->avg_priority
2311 = (prq->sender->avg_priority *
2312 (RUNAVG_DELAY_N - 1) + pr->priority) / (double) RUNAVG_DELAY_N;
2315 GNUNET_PEER_change_rc (prq->sender->last_p2p_replies
2316 [prq->sender->last_p2p_replies_woff % P2P_SUCCESS_LIST_SIZE], -1);
2317 GNUNET_PEER_change_rc (pr->cp->pid, 1);
2318 prq->sender->last_p2p_replies
2319 [(prq->sender->last_p2p_replies_woff++) % P2P_SUCCESS_LIST_SIZE]
2324 if (NULL != prq->sender->last_client_replies
2325 [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE])
2326 GNUNET_SERVER_client_drop (prq->sender->last_client_replies
2327 [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE]);
2328 prq->sender->last_client_replies
2329 [(prq->sender->last_client_replies_woff++) % CS2P_SUCCESS_LIST_SIZE]
2330 = pr->client_request_list->client_list->client;
2331 GNUNET_SERVER_client_keep (pr->client_request_list->client_list->client);
2334 GNUNET_CRYPTO_hash (prq->data,
2339 case GNUNET_BLOCK_TYPE_DBLOCK:
2340 case GNUNET_BLOCK_TYPE_IBLOCK:
2341 /* only possible reply, stop requesting! */
2342 while (NULL != pr->pending_head)
2343 destroy_pending_message_list_entry (pr->pending_head);
2346 if (pr->client_request_list != NULL)
2347 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
2349 GNUNET_DATASTORE_cancel (pr->qe);
2352 pr->do_remove = GNUNET_YES;
2353 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
2355 GNUNET_SCHEDULER_cancel (sched,
2357 pr->task = GNUNET_SCHEDULER_NO_TASK;
2359 GNUNET_break (GNUNET_YES ==
2360 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
2364 case GNUNET_BLOCK_TYPE_SBLOCK:
2365 if (pr->namespace == NULL)
2370 if (0 != memcmp (pr->namespace,
2372 sizeof (GNUNET_HashCode)))
2374 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2375 _("Reply mismatched in terms of namespace. Discarded.\n"));
2376 return GNUNET_YES; /* wrong namespace */
2378 /* then: fall-through! */
2379 case GNUNET_BLOCK_TYPE_KBLOCK:
2380 case GNUNET_BLOCK_TYPE_NBLOCK:
2383 mingle_hash (&chash, pr->mingle, &mhash);
2384 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
2387 GNUNET_STATISTICS_update (stats,
2388 gettext_noop ("# duplicate replies discarded (bloomfilter)"),
2392 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2393 "Duplicate response `%s', discarding.\n",
2394 GNUNET_h2s (&mhash));
2396 return GNUNET_YES; /* duplicate */
2399 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2400 "New response `%s', adding to filter.\n",
2401 GNUNET_h2s (&mhash));
2404 if (pr->client_request_list != NULL)
2406 if (pr->replies_seen_size == pr->replies_seen_off)
2407 GNUNET_array_grow (pr->replies_seen,
2408 pr->replies_seen_size,
2409 pr->replies_seen_size * 2 + 4);
2410 pr->replies_seen[pr->replies_seen_off++] = chash;
2412 if ( (pr->bf == NULL) ||
2413 (pr->client_request_list != NULL) )
2414 refresh_bloomfilter (pr);
2415 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
2422 prq->priority += pr->remaining_priority;
2423 pr->remaining_priority = 0;
2424 if (pr->client_request_list != NULL)
2426 GNUNET_STATISTICS_update (stats,
2427 gettext_noop ("# replies received for local clients"),
2430 cl = pr->client_request_list->client_list;
2431 msize = sizeof (struct PutMessage) + prq->size;
2432 creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
2433 creply->msize = msize;
2434 creply->client_list = cl;
2435 GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
2439 pm = (struct PutMessage*) &creply[1];
2440 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2441 pm->header.size = htons (msize);
2442 pm->type = htonl (prq->type);
2443 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
2444 memcpy (&pm[1], prq->data, prq->size);
2448 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2449 "Transmitting result for query `%s' to client\n",
2452 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
2454 GNUNET_TIME_UNIT_FOREVER_REL,
2455 &transmit_to_client,
2458 GNUNET_break (cl->th != NULL);
2460 destroy_pending_request (pr);
2466 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2467 "Transmitting result for query `%s' to other peer (PID=%u)\n",
2469 (unsigned int) cp->pid);
2471 GNUNET_STATISTICS_update (stats,
2472 gettext_noop ("# replies received for other peers"),
2475 msize = sizeof (struct PutMessage) + prq->size;
2476 reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
2477 reply->cont = &transmit_reply_continuation;
2478 reply->cont_cls = pr;
2479 reply->msize = msize;
2480 reply->priority = (uint32_t) -1; /* send replies first! */
2481 pm = (struct PutMessage*) &reply[1];
2482 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2483 pm->header.size = htons (msize);
2484 pm->type = htonl (prq->type);
2485 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
2486 memcpy (&pm[1], prq->data, prq->size);
2487 add_to_pending_messages_for_peer (cp, reply, pr);
2494 * Continuation called to notify client about result of the
2497 * @param cls closure
2498 * @param success GNUNET_SYSERR on failure
2499 * @param msg NULL on success, otherwise an error message
2502 put_migration_continuation (void *cls,
2511 * Handle P2P "PUT" message.
2513 * @param cls closure, always NULL
2514 * @param other the other peer involved (sender or receiver, NULL
2515 * for loopback messages where we are both sender and receiver)
2516 * @param message the actual message
2517 * @param latency reported latency of the connection with 'other'
2518 * @param distance reported distance (DV) to 'other'
2519 * @return GNUNET_OK to keep the connection open,
2520 * GNUNET_SYSERR to close it (signal serious error)
2523 handle_p2p_put (void *cls,
2524 const struct GNUNET_PeerIdentity *other,
2525 const struct GNUNET_MessageHeader *message,
2526 struct GNUNET_TIME_Relative latency,
2529 const struct PutMessage *put;
2532 enum GNUNET_BLOCK_Type type;
2533 struct GNUNET_TIME_Absolute expiration;
2534 GNUNET_HashCode query;
2535 struct ProcessReplyClosure prq;
2536 const struct SBlock *sb;
2538 msize = ntohs (message->size);
2539 if (msize < sizeof (struct PutMessage))
2542 return GNUNET_SYSERR;
2544 put = (const struct PutMessage*) message;
2545 dsize = msize - sizeof (struct PutMessage);
2546 type = ntohl (put->type);
2547 expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
2550 GNUNET_BLOCK_check_block (type,
2555 GNUNET_break_op (0);
2556 return GNUNET_SYSERR;
2558 if (type == GNUNET_BLOCK_TYPE_ONDEMAND)
2559 return GNUNET_SYSERR;
2560 if (GNUNET_BLOCK_TYPE_SBLOCK == type)
2562 sb = (const struct SBlock*) &put[1];
2563 GNUNET_CRYPTO_hash (&sb->subspace,
2564 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2569 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2570 "Received result for query `%s' from peer `%4s'\n",
2571 GNUNET_h2s (&query),
2572 GNUNET_i2s (other));
2574 GNUNET_STATISTICS_update (stats,
2575 gettext_noop ("# replies received (overall)"),
2578 /* now, lookup 'query' */
2579 prq.data = (const void*) &put[1];
2581 prq.sender = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2582 &other->hashPubKey);
2585 prq.expiration = expiration;
2587 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2591 if (GNUNET_YES == active_migration)
2593 GNUNET_DATASTORE_put (dsh,
2594 0, &query, dsize, &put[1],
2595 type, prq.priority, 1 /* anonymity */,
2597 1 + prq.priority, MAX_DATASTORE_QUEUE,
2598 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
2599 &put_migration_continuation,
2606 /* **************************** P2P GET Handling ************************ */
2610 * Closure for 'check_duplicate_request_{peer,client}'.
2612 struct CheckDuplicateRequestClosure
2615 * The new request we should check if it already exists.
2617 const struct PendingRequest *pr;
2620 * Existing request found by the checker, NULL if none.
2622 struct PendingRequest *have;
2627 * Iterator over entries in the 'query_request_map' that
2628 * tries to see if we have the same request pending from
2629 * the same client already.
2631 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
2632 * @param key current key code (query, ignored, must match)
2633 * @param value value in the hash map (a 'struct PendingRequest'
2634 * that already exists)
2635 * @return GNUNET_YES if we should continue to
2636 * iterate (no match yet)
2637 * GNUNET_NO if not (match found).
2640 check_duplicate_request_client (void *cls,
2641 const GNUNET_HashCode * key,
2644 struct CheckDuplicateRequestClosure *cdc = cls;
2645 struct PendingRequest *have = value;
2647 if (have->client_request_list == NULL)
2649 if ( (cdc->pr->client_request_list->client_list->client == have->client_request_list->client_list->client) &&
2660 * We're processing (local) results for a search request
2661 * from another peer. Pass applicable results to the
2662 * peer and if we are done either clean up (operation
2663 * complete) or forward to other peers (more results possible).
2665 * @param cls our closure (struct LocalGetContext)
2666 * @param key key for the content
2667 * @param size number of bytes in data
2668 * @param data content stored
2669 * @param type type of the content
2670 * @param priority priority of the content
2671 * @param anonymity anonymity-level for the content
2672 * @param expiration expiration time for the content
2673 * @param uid unique identifier for the datum;
2674 * maybe 0 if no unique identifier is available
2677 process_local_reply (void *cls,
2678 const GNUNET_HashCode * key,
2681 enum GNUNET_BLOCK_Type type,
2684 struct GNUNET_TIME_Absolute
2688 struct PendingRequest *pr = cls;
2689 struct ProcessReplyClosure prq;
2690 struct CheckDuplicateRequestClosure cdrc;
2691 const struct SBlock *sb;
2692 GNUNET_HashCode dhash;
2693 GNUNET_HashCode mhash;
2694 GNUNET_HashCode query;
2699 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2700 "Done processing local replies, forwarding request to other peers.\n");
2703 if (pr->client_request_list != NULL)
2705 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
2707 /* Figure out if this is a duplicate request and possibly
2708 merge 'struct PendingRequest' entries */
2711 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2713 &check_duplicate_request_client,
2715 if (cdrc.have != NULL)
2718 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2719 "Received request for block `%s' twice from client, will only request once.\n",
2720 GNUNET_h2s (&pr->query));
2723 destroy_pending_request (pr);
2728 /* no more results */
2729 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2730 pr->task = GNUNET_SCHEDULER_add_now (sched,
2731 &forward_request_task,
2736 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2737 "New local response to `%s' of type %u.\n",
2741 if (type == GNUNET_BLOCK_TYPE_ONDEMAND)
2744 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2745 "Found ONDEMAND block, performing on-demand encoding\n");
2747 GNUNET_STATISTICS_update (stats,
2748 gettext_noop ("# on-demand blocks matched requests"),
2752 GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
2753 anonymity, expiration, uid,
2754 &process_local_reply,
2757 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2760 /* check for duplicates */
2761 GNUNET_CRYPTO_hash (data, size, &dhash);
2762 mingle_hash (&dhash,
2765 if ( (pr->bf != NULL) &&
2767 GNUNET_CONTAINER_bloomfilter_test (pr->bf,
2771 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2772 "Result from datastore filtered by bloomfilter (duplicate).\n");
2774 GNUNET_STATISTICS_update (stats,
2775 gettext_noop ("# results filtered by query bloomfilter"),
2779 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2783 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2784 "Found result for query `%s' in local datastore\n",
2787 GNUNET_STATISTICS_update (stats,
2788 gettext_noop ("# results found locally"),
2791 pr->results_found++;
2792 memset (&prq, 0, sizeof (prq));
2794 prq.expiration = expiration;
2796 if (GNUNET_BLOCK_TYPE_SBLOCK == type)
2798 sb = (const struct SBlock*) data;
2799 GNUNET_CRYPTO_hash (&sb->subspace,
2800 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2803 if (GNUNET_OK != GNUNET_BLOCK_check_block (type,
2809 GNUNET_DATASTORE_remove (dsh,
2813 GNUNET_TIME_UNIT_FOREVER_REL,
2815 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2818 if ( (type == GNUNET_BLOCK_TYPE_DBLOCK) ||
2819 (type == GNUNET_BLOCK_TYPE_IBLOCK) )
2822 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
2824 else if ( (pr->client_request_list == NULL) &&
2825 ( (GNUNET_YES == test_load_too_high()) ||
2826 (pr->results_found > 5 + 2 * pr->priority) ) )
2829 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2830 "Load too high, done with request\n");
2832 GNUNET_STATISTICS_update (stats,
2833 gettext_noop ("# processing result set cut short due to load"),
2837 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
2839 else if (pr->qe != NULL)
2840 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2842 prq.priority = priority;
2843 process_reply (&prq, key, pr);
2848 * We've received a request with the specified priority. Bound it
2849 * according to how much we trust the given peer.
2851 * @param prio_in requested priority
2852 * @param cp the peer making the request
2853 * @return effective priority
2856 bound_priority (uint32_t prio_in,
2857 struct ConnectedPeer *cp)
2864 * Iterator over entries in the 'query_request_map' that
2865 * tries to see if we have the same request pending from
2866 * the same peer already.
2868 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
2869 * @param key current key code (query, ignored, must match)
2870 * @param value value in the hash map (a 'struct PendingRequest'
2871 * that already exists)
2872 * @return GNUNET_YES if we should continue to
2873 * iterate (no match yet)
2874 * GNUNET_NO if not (match found).
2877 check_duplicate_request_peer (void *cls,
2878 const GNUNET_HashCode * key,
2881 struct CheckDuplicateRequestClosure *cdc = cls;
2882 struct PendingRequest *have = value;
2884 if (cdc->pr->target_pid == have->target_pid)
2894 * Handle P2P "GET" request.
2896 * @param cls closure, always NULL
2897 * @param other the other peer involved (sender or receiver, NULL
2898 * for loopback messages where we are both sender and receiver)
2899 * @param message the actual message
2900 * @param latency reported latency of the connection with 'other'
2901 * @param distance reported distance (DV) to 'other'
2902 * @return GNUNET_OK to keep the connection open,
2903 * GNUNET_SYSERR to close it (signal serious error)
2906 handle_p2p_get (void *cls,
2907 const struct GNUNET_PeerIdentity *other,
2908 const struct GNUNET_MessageHeader *message,
2909 struct GNUNET_TIME_Relative latency,
2912 struct PendingRequest *pr;
2913 struct ConnectedPeer *cp;
2914 struct ConnectedPeer *cps;
2915 struct CheckDuplicateRequestClosure cdc;
2916 struct GNUNET_TIME_Relative timeout;
2918 const struct GetMessage *gm;
2920 const GNUNET_HashCode *opt;
2923 uint32_t ttl_decrement;
2924 enum GNUNET_BLOCK_Type type;
2928 msize = ntohs(message->size);
2929 if (msize < sizeof (struct GetMessage))
2931 GNUNET_break_op (0);
2932 return GNUNET_SYSERR;
2934 gm = (const struct GetMessage*) message;
2935 type = ntohl (gm->type);
2938 case GNUNET_BLOCK_TYPE_ANY:
2939 case GNUNET_BLOCK_TYPE_DBLOCK:
2940 case GNUNET_BLOCK_TYPE_IBLOCK:
2941 case GNUNET_BLOCK_TYPE_KBLOCK:
2942 case GNUNET_BLOCK_TYPE_SBLOCK:
2945 GNUNET_break_op (0);
2946 return GNUNET_SYSERR;
2948 bm = ntohl (gm->hash_bitmap);
2956 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
2958 GNUNET_break_op (0);
2959 return GNUNET_SYSERR;
2961 opt = (const GNUNET_HashCode*) &gm[1];
2962 bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
2963 bm = ntohl (gm->hash_bitmap);
2964 if ( (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)) &&
2965 (type != GNUNET_BLOCK_TYPE_SBLOCK) )
2967 GNUNET_break_op (0);
2968 return GNUNET_SYSERR;
2971 cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2972 &other->hashPubKey);
2975 /* peer must have just disconnected */
2976 GNUNET_STATISTICS_update (stats,
2977 gettext_noop ("# requests dropped due to initiator not being connected"),
2980 return GNUNET_SYSERR;
2982 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
2983 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2990 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
2991 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2992 "Failed to find RETURN-TO peer `%4s' in connection set. Dropping query.\n",
2993 GNUNET_i2s ((const struct GNUNET_PeerIdentity*) &opt[bits-1]));
2996 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2997 "Failed to find peer `%4s' in connection set. Dropping query.\n",
2998 GNUNET_i2s (other));
3000 GNUNET_STATISTICS_update (stats,
3001 gettext_noop ("# requests dropped due to missing reverse route"),
3004 /* FIXME: try connect? */
3007 /* note that we can really only check load here since otherwise
3008 peers could find out that we are overloaded by not being
3009 disconnected after sending us a malformed query... */
3010 if (GNUNET_YES == test_load_too_high ())
3013 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3014 "Dropping query from `%s', this peer is too busy.\n",
3015 GNUNET_i2s (other));
3017 GNUNET_STATISTICS_update (stats,
3018 gettext_noop ("# requests dropped due to high load"),
3025 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3026 "Received request for `%s' of type %u from peer `%4s' with flags %u\n",
3027 GNUNET_h2s (&gm->query),
3028 (unsigned int) type,
3032 have_ns = (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE));
3033 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
3034 (have_ns ? sizeof(GNUNET_HashCode) : 0));
3036 pr->namespace = (GNUNET_HashCode*) &pr[1];
3038 pr->mingle = ntohl (gm->filter_mutator);
3039 if (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
3040 memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
3041 if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
3042 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
3044 pr->anonymity_level = 1;
3045 pr->priority = bound_priority (ntohl (gm->priority), cps);
3046 pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
3047 pr->query = gm->query;
3048 /* decrement ttl (always) */
3049 ttl_decrement = 2 * TTL_DECREMENT +
3050 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3052 if ( (pr->ttl < 0) &&
3053 (((int32_t)(pr->ttl - ttl_decrement)) > 0) )
3056 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3057 "Dropping query from `%s' due to TTL underflow (%d - %u).\n",
3062 GNUNET_STATISTICS_update (stats,
3063 gettext_noop ("# requests dropped due TTL underflow"),
3066 /* integer underflow => drop (should be very rare)! */
3070 pr->ttl -= ttl_decrement;
3071 pr->start_time = GNUNET_TIME_absolute_get ();
3073 /* get bloom filter */
3076 pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
3079 pr->bf_size = bfsize;
3084 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
3086 &check_duplicate_request_peer,
3088 if (cdc.have != NULL)
3090 if (cdc.have->start_time.value + cdc.have->ttl >=
3091 pr->start_time.value + pr->ttl)
3093 /* existing request has higher TTL, drop new one! */
3094 cdc.have->priority += pr->priority;
3095 destroy_pending_request (pr);
3097 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3098 "Have existing request with higher TTL, dropping new request.\n",
3099 GNUNET_i2s (other));
3101 GNUNET_STATISTICS_update (stats,
3102 gettext_noop ("# requests dropped due to higher-TTL request"),
3109 /* existing request has lower TTL, drop old one! */
3110 pr->priority += cdc.have->priority;
3111 /* Possible optimization: if we have applicable pending
3112 replies in 'cdc.have', we might want to move those over
3113 (this is a really rare special-case, so it is not clear
3114 that this would be worth it) */
3115 destroy_pending_request (cdc.have);
3116 /* keep processing 'pr'! */
3121 GNUNET_break (GNUNET_OK ==
3122 GNUNET_CONTAINER_multihashmap_put (query_request_map,
3125 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
3126 GNUNET_break (GNUNET_OK ==
3127 GNUNET_CONTAINER_multihashmap_put (peer_request_map,
3130 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
3132 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
3134 pr->start_time.value + pr->ttl);
3136 GNUNET_STATISTICS_update (stats,
3137 gettext_noop ("# P2P searches received"),
3140 GNUNET_STATISTICS_update (stats,
3141 gettext_noop ("# P2P searches active"),
3145 /* calculate change in traffic preference */
3146 preference = (double) pr->priority;
3147 if (preference < QUERY_BANDWIDTH_VALUE)
3148 preference = QUERY_BANDWIDTH_VALUE;
3149 cps->inc_preference += preference;
3151 /* process locally */
3152 if (type == GNUNET_BLOCK_TYPE_DBLOCK)
3153 type = GNUNET_BLOCK_TYPE_ANY; /* to get on-demand as well */
3154 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
3155 (pr->priority + 1));
3156 pr->qe = GNUNET_DATASTORE_get (dsh,
3160 MAX_DATASTORE_QUEUE,
3162 &process_local_reply,
3165 /* Are multiple results possible? If so, start processing remotely now! */
3168 case GNUNET_BLOCK_TYPE_DBLOCK:
3169 case GNUNET_BLOCK_TYPE_IBLOCK:
3170 /* only one result, wait for datastore */
3173 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
3174 pr->task = GNUNET_SCHEDULER_add_now (sched,
3175 &forward_request_task,
3179 /* make sure we don't track too many requests */
3180 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
3182 pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
3183 destroy_pending_request (pr);
3189 /* **************************** CS GET Handling ************************ */
3193 * Handle START_SEARCH-message (search request from client).
3195 * @param cls closure
3196 * @param client identification of the client
3197 * @param message the actual message
3200 handle_start_search (void *cls,
3201 struct GNUNET_SERVER_Client *client,
3202 const struct GNUNET_MessageHeader *message)
3204 static GNUNET_HashCode all_zeros;
3205 const struct SearchMessage *sm;
3206 struct ClientList *cl;
3207 struct ClientRequestList *crl;
3208 struct PendingRequest *pr;
3211 enum GNUNET_BLOCK_Type type;
3213 msize = ntohs (message->size);
3214 if ( (msize < sizeof (struct SearchMessage)) ||
3215 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
3218 GNUNET_SERVER_receive_done (client,
3222 GNUNET_STATISTICS_update (stats,
3223 gettext_noop ("# client searches received"),
3226 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
3227 sm = (const struct SearchMessage*) message;
3228 type = ntohl (sm->type);
3230 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3231 "Received request for `%s' of type %u from local client\n",
3232 GNUNET_h2s (&sm->query),
3233 (unsigned int) type);
3237 case GNUNET_BLOCK_TYPE_ANY:
3238 case GNUNET_BLOCK_TYPE_DBLOCK:
3239 case GNUNET_BLOCK_TYPE_IBLOCK:
3240 case GNUNET_BLOCK_TYPE_KBLOCK:
3241 case GNUNET_BLOCK_TYPE_SBLOCK:
3242 case GNUNET_BLOCK_TYPE_NBLOCK:
3246 GNUNET_SERVER_receive_done (client,
3252 while ( (cl != NULL) &&
3253 (cl->client != client) )
3257 cl = GNUNET_malloc (sizeof (struct ClientList));
3258 cl->client = client;
3259 GNUNET_SERVER_client_keep (client);
3260 cl->next = client_list;
3263 /* detect duplicate KBLOCK requests */
3264 if ( (type == GNUNET_BLOCK_TYPE_KBLOCK) ||
3265 (type == GNUNET_BLOCK_TYPE_NBLOCK) ||
3266 (type == GNUNET_BLOCK_TYPE_ANY) )
3269 while ( (crl != NULL) &&
3270 ( (0 != memcmp (&crl->req->query,
3272 sizeof (GNUNET_HashCode))) ||
3273 (crl->req->type != type) ) )
3278 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3279 "Have existing request, merging content-seen lists.\n");
3282 /* Duplicate request (used to send long list of
3283 known/blocked results); merge 'pr->replies_seen'
3284 and update bloom filter */
3285 GNUNET_array_grow (pr->replies_seen,
3286 pr->replies_seen_size,
3287 pr->replies_seen_off + sc);
3288 memcpy (&pr->replies_seen[pr->replies_seen_off],
3290 sc * sizeof (GNUNET_HashCode));
3291 pr->replies_seen_off += sc;
3292 refresh_bloomfilter (pr);
3293 GNUNET_STATISTICS_update (stats,
3294 gettext_noop ("# client searches updated (merged content seen list)"),
3297 GNUNET_SERVER_receive_done (client,
3302 GNUNET_STATISTICS_update (stats,
3303 gettext_noop ("# client searches active"),
3306 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
3307 ((type == GNUNET_BLOCK_TYPE_SBLOCK) ? sizeof(GNUNET_HashCode) : 0));
3308 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
3309 memset (crl, 0, sizeof (struct ClientRequestList));
3310 crl->client_list = cl;
3311 GNUNET_CONTAINER_DLL_insert (cl->rl_head,
3316 pr->client_request_list = crl;
3317 GNUNET_array_grow (pr->replies_seen,
3318 pr->replies_seen_size,
3320 memcpy (pr->replies_seen,
3322 sc * sizeof (GNUNET_HashCode));
3323 pr->replies_seen_off = sc;
3324 pr->anonymity_level = ntohl (sm->anonymity_level);
3325 refresh_bloomfilter (pr);
3326 pr->query = sm->query;
3327 if (0 == (1 & ntohl (sm->options)))
3328 pr->local_only = GNUNET_NO;
3330 pr->local_only = GNUNET_YES;
3333 case GNUNET_BLOCK_TYPE_DBLOCK:
3334 case GNUNET_BLOCK_TYPE_IBLOCK:
3335 if (0 != memcmp (&sm->target,
3337 sizeof (GNUNET_HashCode)))
3338 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
3340 case GNUNET_BLOCK_TYPE_SBLOCK:
3341 pr->namespace = (GNUNET_HashCode*) &pr[1];
3342 memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
3347 GNUNET_break (GNUNET_OK ==
3348 GNUNET_CONTAINER_multihashmap_put (query_request_map,
3351 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
3352 if (type == GNUNET_BLOCK_TYPE_DBLOCK)
3353 type = GNUNET_BLOCK_TYPE_ANY; /* get on-demand blocks too! */
3354 pr->qe = GNUNET_DATASTORE_get (dsh,
3358 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
3359 &process_local_reply,
3364 /* **************************** Startup ************************ */
3368 * List of handlers for P2P messages
3369 * that we care about.
3371 static struct GNUNET_CORE_MessageHandler p2p_handlers[] =
3374 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
3376 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
3382 * List of handlers for the messages understood by this
3385 static struct GNUNET_SERVER_MessageHandler handlers[] = {
3386 {&GNUNET_FS_handle_index_start, NULL,
3387 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
3388 {&GNUNET_FS_handle_index_list_get, NULL,
3389 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
3390 {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
3391 sizeof (struct UnindexMessage) },
3392 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
3399 * Process fs requests.
3401 * @param s scheduler to use
3402 * @param server the initialized server
3403 * @param c configuration to use
3406 main_init (struct GNUNET_SCHEDULER_Handle *s,
3407 struct GNUNET_SERVER_Handle *server,
3408 const struct GNUNET_CONFIGURATION_Handle *c)
3412 stats = GNUNET_STATISTICS_create (sched, "fs", cfg);
3413 min_migration_delay = GNUNET_TIME_UNIT_SECONDS; // FIXME: get from config
3414 connected_peers = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3415 query_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3416 peer_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3417 requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
3418 core = GNUNET_CORE_connect (sched,
3420 GNUNET_TIME_UNIT_FOREVER_REL,
3423 &peer_connect_handler,
3424 &peer_disconnect_handler,
3430 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3431 _("Failed to connect to `%s' service.\n"),
3433 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
3434 connected_peers = NULL;
3435 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
3436 query_request_map = NULL;
3437 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
3438 requests_by_expiration_heap = NULL;
3439 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
3440 peer_request_map = NULL;
3443 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
3446 return GNUNET_SYSERR;
3448 /* FIXME: distinguish between sending and storing in options? */
3449 if (active_migration)
3450 consider_migration_gathering ();
3451 GNUNET_SERVER_disconnect_notify (server,
3452 &handle_client_disconnect,
3454 GNUNET_SERVER_add_handlers (server, handlers);
3455 GNUNET_SCHEDULER_add_delayed (sched,
3456 GNUNET_TIME_UNIT_FOREVER_REL,
3464 * Process fs requests.
3466 * @param cls closure
3467 * @param sched scheduler to use
3468 * @param server the initialized server
3469 * @param cfg configuration to use
3473 struct GNUNET_SCHEDULER_Handle *sched,
3474 struct GNUNET_SERVER_Handle *server,
3475 const struct GNUNET_CONFIGURATION_Handle *cfg)
3477 active_migration = GNUNET_CONFIGURATION_get_value_yesno (cfg,
3480 dsh = GNUNET_DATASTORE_connect (cfg,
3484 GNUNET_SCHEDULER_shutdown (sched);
3487 if ( (GNUNET_OK != GNUNET_FS_indexing_init (sched, cfg, dsh)) ||
3488 (GNUNET_OK != main_init (sched, server, cfg)) )
3490 GNUNET_SCHEDULER_shutdown (sched);
3491 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
3499 * The main function for the fs service.
3501 * @param argc number of arguments from the command line
3502 * @param argv command line arguments
3503 * @return 0 ok, 1 on error
3506 main (int argc, char *const *argv)
3508 return (GNUNET_OK ==
3509 GNUNET_SERVICE_run (argc,
3512 GNUNET_SERVICE_OPTION_NONE,
3513 &run, NULL)) ? 0 : 1;
3516 /* end of gnunet-service-fs.c */