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;
1228 if (pos->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers))
1230 delete_migration_block (pos);
1231 consider_migration_gathering ();
1234 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1235 &consider_migration,
1239 GNUNET_PEER_change_rc (cp->pid, -1);
1240 GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
1241 if (NULL != cp->cth)
1242 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
1243 while (NULL != (pm = cp->pending_messages_head))
1244 destroy_pending_message (pm, 0 /* delivery failed */);
1245 GNUNET_break (0 == cp->pending_requests);
1251 * Iterator over hash map entries that removes all occurences
1252 * of the given 'client' from the 'last_client_replies' of the
1253 * given connected peer.
1255 * @param cls closure, the 'struct GNUNET_SERVER_Client*' to remove
1256 * @param key current key code (unused)
1257 * @param value value in the hash map (the 'struct ConnectedPeer*' to change)
1258 * @return GNUNET_YES (we should continue to iterate)
1261 remove_client_from_last_client_replies (void *cls,
1262 const GNUNET_HashCode * key,
1265 struct GNUNET_SERVER_Client *client = cls;
1266 struct ConnectedPeer *cp = value;
1269 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1271 if (cp->last_client_replies[i] == client)
1273 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1274 cp->last_client_replies[i] = NULL;
1282 * A client disconnected. Remove all of its pending queries.
1284 * @param cls closure, NULL
1285 * @param client identification of the client
1288 handle_client_disconnect (void *cls,
1289 struct GNUNET_SERVER_Client
1292 struct ClientList *pos;
1293 struct ClientList *prev;
1294 struct ClientRequestList *rcl;
1295 struct ClientResponseMessage *creply;
1301 while ( (NULL != pos) &&
1302 (pos->client != client) )
1308 return; /* no requests pending for this client */
1309 while (NULL != (rcl = pos->rl_head))
1311 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1312 "Destroying pending request `%s' on disconnect\n",
1313 GNUNET_h2s (&rcl->req->query));
1314 destroy_pending_request (rcl->req);
1317 client_list = pos->next;
1319 prev->next = pos->next;
1320 if (pos->th != NULL)
1322 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
1325 while (NULL != (creply = pos->res_head))
1327 GNUNET_CONTAINER_DLL_remove (pos->res_head,
1330 GNUNET_free (creply);
1332 GNUNET_SERVER_client_drop (pos->client);
1334 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1335 &remove_client_from_last_client_replies,
1341 * Iterator to free peer entries.
1343 * @param cls closure, unused
1344 * @param key current key code
1345 * @param value value in the hash map (peer entry)
1346 * @return GNUNET_YES (we should continue to iterate)
1349 clean_peer (void *cls,
1350 const GNUNET_HashCode * key,
1353 peer_disconnect_handler (NULL, (const struct GNUNET_PeerIdentity*) key);
1359 * Task run during shutdown.
1365 shutdown_task (void *cls,
1366 const struct GNUNET_SCHEDULER_TaskContext *tc)
1370 GNUNET_DATASTORE_cancel (mig_qe);
1373 if (GNUNET_SCHEDULER_NO_TASK != mig_task)
1375 GNUNET_SCHEDULER_cancel (sched, mig_task);
1376 mig_task = GNUNET_SCHEDULER_NO_TASK;
1378 while (client_list != NULL)
1379 handle_client_disconnect (NULL,
1380 client_list->client);
1381 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1384 GNUNET_break (0 == GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap));
1385 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
1386 requests_by_expiration_heap = 0;
1387 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
1388 connected_peers = NULL;
1389 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (query_request_map));
1390 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
1391 query_request_map = NULL;
1392 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (peer_request_map));
1393 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
1394 peer_request_map = NULL;
1395 GNUNET_assert (NULL != core);
1396 GNUNET_CORE_disconnect (core);
1400 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1403 GNUNET_DATASTORE_disconnect (dsh,
1405 while (mig_head != NULL)
1406 delete_migration_block (mig_head);
1407 GNUNET_assert (0 == mig_size);
1414 /* ******************* Utility functions ******************** */
1418 * Transmit messages by copying it to the target buffer
1419 * "buf". "buf" will be NULL and "size" zero if the socket was closed
1420 * for writing in the meantime. In that case, do nothing
1421 * (the disconnect or shutdown handler will take care of the rest).
1422 * If we were able to transmit messages and there are still more
1423 * pending, ask core again for further calls to this function.
1425 * @param cls closure, pointer to the 'struct ConnectedPeer*'
1426 * @param size number of bytes available in buf
1427 * @param buf where the callee should write the message
1428 * @return number of bytes written to buf
1431 transmit_to_peer (void *cls,
1432 size_t size, void *buf)
1434 struct ConnectedPeer *cp = cls;
1436 struct GNUNET_PeerIdentity pid;
1437 struct PendingMessage *pm;
1438 struct MigrationReadyBlock *mb;
1439 struct MigrationReadyBlock *next;
1440 struct PutMessage migm;
1448 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1449 "Dropping message, core too busy.\n");
1454 while ( (NULL != (pm = cp->pending_messages_head) ) &&
1455 (pm->msize <= size) )
1457 memcpy (&cbuf[msize], &pm[1], pm->msize);
1460 destroy_pending_message (pm, cp->pid);
1464 GNUNET_PEER_resolve (cp->pid,
1466 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1468 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1477 while (NULL != (mb = next))
1480 for (i=0;i<MIGRATION_LIST_SIZE;i++)
1482 if ( (cp->pid == mb->target_list[i]) &&
1483 (mb->size + sizeof (migm) <= size) )
1485 GNUNET_PEER_change_rc (mb->target_list[i], -1);
1486 mb->target_list[i] = 0;
1488 migm.header.size = htons (sizeof (migm) + mb->size);
1489 migm.header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
1490 migm.type = htonl (mb->type);
1491 migm.expiration = GNUNET_TIME_absolute_hton (mb->expiration);
1492 memcpy (&cbuf[msize], &migm, sizeof (migm));
1493 msize += sizeof (migm);
1494 size -= sizeof (migm);
1495 memcpy (&cbuf[msize], &mb[1], mb->size);
1501 if ( (mb->used_targets >= MIGRATION_TARGET_COUNT) ||
1502 (mb->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers)) )
1504 delete_migration_block (mb);
1505 consider_migration_gathering ();
1508 consider_migration (NULL,
1513 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1514 "Transmitting %u bytes to peer %u\n",
1523 * Add a message to the set of pending messages for the given peer.
1525 * @param cp peer to send message to
1526 * @param pm message to queue
1527 * @param pr request on which behalf this message is being queued
1530 add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
1531 struct PendingMessage *pm,
1532 struct PendingRequest *pr)
1534 struct PendingMessage *pos;
1535 struct PendingMessageList *pml;
1536 struct GNUNET_PeerIdentity pid;
1538 GNUNET_assert (pm->next == NULL);
1539 GNUNET_assert (pm->pml == NULL);
1540 pml = GNUNET_malloc (sizeof (struct PendingMessageList));
1545 GNUNET_CONTAINER_DLL_insert (pr->pending_head,
1548 pos = cp->pending_messages_head;
1549 while ( (pos != NULL) &&
1550 (pm->priority < pos->priority) )
1552 GNUNET_CONTAINER_DLL_insert_after (cp->pending_messages_head,
1553 cp->pending_messages_tail,
1556 cp->pending_requests++;
1557 if (cp->pending_requests > MAX_QUEUE_PER_PEER)
1558 destroy_pending_message (cp->pending_messages_tail, 0);
1559 GNUNET_PEER_resolve (cp->pid, &pid);
1560 if (NULL != cp->cth)
1561 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
1562 /* need to schedule transmission */
1563 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1564 cp->pending_messages_head->priority,
1567 cp->pending_messages_head->msize,
1570 if (cp->cth == NULL)
1573 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1574 "Failed to schedule transmission with core!\n");
1576 /* FIXME: call stats (rare, bad case) */
1582 * Mingle hash with the mingle_number to produce different bits.
1585 mingle_hash (const GNUNET_HashCode * in,
1586 int32_t mingle_number,
1587 GNUNET_HashCode * hc)
1591 GNUNET_CRYPTO_hash (&mingle_number,
1594 GNUNET_CRYPTO_hash_xor (&m, in, hc);
1599 * Test if the load on this peer is too high
1600 * to even consider processing the query at
1603 * @return GNUNET_YES if the load is too high, GNUNET_NO otherwise
1606 test_load_too_high ()
1608 return GNUNET_NO; // FIXME
1612 /* ******************* Pending Request Refresh Task ******************** */
1617 * We use a random delay to make the timing of requests less
1618 * predictable. This function returns such a random delay. We add a base
1619 * delay of MAX_CORK_DELAY (1s).
1621 * FIXME: make schedule dependent on the specifics of the request?
1622 * Or bandwidth and number of connected peers and load?
1624 * @return random delay to use for some request, between 1s and 1000+TTL_DECREMENT ms
1626 static struct GNUNET_TIME_Relative
1627 get_processing_delay ()
1630 GNUNET_TIME_relative_add (GNUNET_CONSTANTS_MAX_CORK_DELAY,
1631 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1632 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1638 * We're processing a GET request from another peer and have decided
1639 * to forward it to other peers. This function is called periodically
1640 * and should forward the request to other peers until we have all
1641 * possible replies. If we have transmitted the *only* reply to
1642 * the initiator we should destroy the pending request. If we have
1643 * many replies in the queue to the initiator, we should delay sending
1644 * out more queries until the reply queue has shrunk some.
1646 * @param cls our "struct ProcessGetContext *"
1650 forward_request_task (void *cls,
1651 const struct GNUNET_SCHEDULER_TaskContext *tc);
1655 * Function called after we either failed or succeeded
1656 * at transmitting a query to a peer.
1658 * @param cls the requests "struct PendingRequest*"
1659 * @param tpid ID of receiving peer, 0 on transmission error
1662 transmit_query_continuation (void *cls,
1663 GNUNET_PEER_Id tpid)
1665 struct PendingRequest *pr = cls;
1667 GNUNET_STATISTICS_update (stats,
1668 gettext_noop ("# queries scheduled for forwarding"),
1674 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1675 "Transmission of request failed, will try again later.\n");
1677 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1678 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1679 get_processing_delay (),
1680 &forward_request_task,
1684 GNUNET_STATISTICS_update (stats,
1685 gettext_noop ("# queries forwarded"),
1688 GNUNET_PEER_change_rc (tpid, 1);
1689 if (pr->used_pids_off == pr->used_pids_size)
1690 GNUNET_array_grow (pr->used_pids,
1692 pr->used_pids_size * 2 + 2);
1693 pr->used_pids[pr->used_pids_off++] = tpid;
1694 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1695 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1696 get_processing_delay (),
1697 &forward_request_task,
1703 * How many bytes should a bloomfilter be if we have already seen
1704 * entry_count responses? Note that BLOOMFILTER_K gives us the number
1705 * of bits set per entry. Furthermore, we should not re-size the
1706 * filter too often (to keep it cheap).
1708 * Since other peers will also add entries but not resize the filter,
1709 * we should generally pick a slightly larger size than what the
1710 * strict math would suggest.
1712 * @return must be a power of two and smaller or equal to 2^15.
1715 compute_bloomfilter_size (unsigned int entry_count)
1718 unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
1719 uint16_t max = 1 << 15;
1721 if (entry_count > max)
1724 while ((size < max) && (size < ideal))
1733 * Recalculate our bloom filter for filtering replies. This function
1734 * will create a new bloom filter from scratch, so it should only be
1735 * called if we have no bloomfilter at all (and hence can create a
1736 * fresh one of minimal size without problems) OR if our peer is the
1737 * initiator (in which case we may resize to larger than mimimum size).
1739 * @param pr request for which the BF is to be recomputed
1742 refresh_bloomfilter (struct PendingRequest *pr)
1746 GNUNET_HashCode mhash;
1748 nsize = compute_bloomfilter_size (pr->replies_seen_off);
1749 if (nsize == pr->bf_size)
1750 return; /* size not changed */
1752 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
1753 pr->bf_size = nsize;
1754 pr->mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
1755 pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1758 for (i=0;i<pr->replies_seen_off;i++)
1760 mingle_hash (&pr->replies_seen[i], pr->mingle, &mhash);
1761 GNUNET_CONTAINER_bloomfilter_add (pr->bf, &mhash);
1767 * Function called after we've tried to reserve a certain amount of
1768 * bandwidth for a reply. Check if we succeeded and if so send our
1771 * @param cls the requests "struct PendingRequest*"
1772 * @param peer identifies the peer
1773 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1774 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1775 * @param amount set to the amount that was actually reserved or unreserved
1776 * @param preference current traffic preference for the given peer
1779 target_reservation_cb (void *cls,
1781 GNUNET_PeerIdentity * peer,
1782 struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
1783 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1785 uint64_t preference)
1787 struct PendingRequest *pr = cls;
1788 struct ConnectedPeer *cp;
1789 struct PendingMessage *pm;
1790 struct GetMessage *gm;
1791 GNUNET_HashCode *ext;
1801 /* error in communication with core, try again later */
1802 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1803 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1804 get_processing_delay (),
1805 &forward_request_task,
1809 // (3) transmit, update ttl/priority
1810 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1814 /* Peer must have just left */
1816 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1817 "Selected peer disconnected!\n");
1819 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1820 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1821 get_processing_delay (),
1822 &forward_request_task,
1826 no_route = GNUNET_NO;
1827 /* FIXME: check against DBLOCK_SIZE and possibly return
1828 amount to reserve; however, this also needs to work
1829 with testcases which currently start out with a far
1830 too low per-peer bw limit, so they would never send
1831 anything. Big issue. */
1837 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1838 "Failed to reserve bandwidth for reply (got %d/%u bytes only)!\n",
1842 GNUNET_STATISTICS_update (stats,
1843 gettext_noop ("# reply bandwidth reservation requests failed"),
1846 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1847 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1848 get_processing_delay (),
1849 &forward_request_task,
1851 return; /* this target round failed */
1853 /* FIXME: if we are "quite" busy, we may still want to skip
1854 this round; need more load detection code! */
1855 no_route = GNUNET_YES;
1858 GNUNET_STATISTICS_update (stats,
1859 gettext_noop ("# queries scheduled for forwarding"),
1862 /* build message and insert message into priority queue */
1864 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1865 "Forwarding request `%s' to `%4s'!\n",
1866 GNUNET_h2s (&pr->query),
1871 if (GNUNET_YES == no_route)
1873 bm |= GET_MESSAGE_BIT_RETURN_TO;
1876 if (pr->namespace != NULL)
1878 bm |= GET_MESSAGE_BIT_SKS_NAMESPACE;
1881 if (pr->target_pid != 0)
1883 bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
1886 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
1887 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1888 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1890 gm = (struct GetMessage*) &pm[1];
1891 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
1892 gm->header.size = htons (msize);
1893 gm->type = htonl (pr->type);
1894 pr->remaining_priority /= 2;
1895 gm->priority = htonl (pr->remaining_priority);
1896 gm->ttl = htonl (pr->ttl);
1897 gm->filter_mutator = htonl(pr->mingle);
1898 gm->hash_bitmap = htonl (bm);
1899 gm->query = pr->query;
1900 ext = (GNUNET_HashCode*) &gm[1];
1902 if (GNUNET_YES == no_route)
1903 GNUNET_PEER_resolve (pr->cp->pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1904 if (pr->namespace != NULL)
1905 memcpy (&ext[k++], pr->namespace, sizeof (GNUNET_HashCode));
1906 if (pr->target_pid != 0)
1907 GNUNET_PEER_resolve (pr->target_pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1908 bfdata = (char *) &ext[k];
1910 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
1913 pm->cont = &transmit_query_continuation;
1915 add_to_pending_messages_for_peer (cp, pm, pr);
1920 * Closure used for "target_peer_select_cb".
1922 struct PeerSelectionContext
1925 * The request for which we are selecting
1928 struct PendingRequest *pr;
1931 * Current "prime" target.
1933 struct GNUNET_PeerIdentity target;
1936 * How much do we like this target?
1938 double target_score;
1944 * Function called for each connected peer to determine
1945 * which one(s) would make good targets for forwarding.
1947 * @param cls closure (struct PeerSelectionContext)
1948 * @param key current key code (peer identity)
1949 * @param value value in the hash map (struct ConnectedPeer)
1950 * @return GNUNET_YES if we should continue to
1955 target_peer_select_cb (void *cls,
1956 const GNUNET_HashCode * key,
1959 struct PeerSelectionContext *psc = cls;
1960 struct ConnectedPeer *cp = value;
1961 struct PendingRequest *pr = psc->pr;
1966 /* 1) check that this peer is not the initiator */
1968 return GNUNET_YES; /* skip */
1970 /* 2) check if we have already (recently) forwarded to this peer */
1972 for (i=0;i<pr->used_pids_off;i++)
1973 if (pr->used_pids[i] == cp->pid)
1976 if (0 != GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1977 RETRY_PROBABILITY_INV))
1980 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1981 "NOT re-trying query that was previously transmitted %u times\n",
1982 (unsigned int) pr->used_pids_off);
1984 return GNUNET_YES; /* skip */
1989 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1990 "Re-trying query that was previously transmitted %u times to this peer\n",
1993 // 3) calculate how much we'd like to forward to this peer
1994 score = 42; // FIXME!
1995 // FIXME: also need API to gather data on responsiveness
1996 // of this peer (we have fields for that in 'cp', but
1997 // they are never set!)
1999 /* store best-fit in closure */
2000 if (score > psc->target_score)
2002 psc->target_score = score;
2003 psc->target.hashPubKey = *key;
2010 * The priority level imposes a bound on the maximum
2011 * value for the ttl that can be requested.
2013 * @param ttl_in requested ttl
2014 * @param prio given priority
2015 * @return ttl_in if ttl_in is below the limit,
2016 * otherwise the ttl-limit for the given priority
2019 bound_ttl (int32_t ttl_in, uint32_t prio)
2021 unsigned long long allowed;
2025 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
2026 if (ttl_in > allowed)
2028 if (allowed >= (1 << 30))
2037 * We're processing a GET request from another peer and have decided
2038 * to forward it to other peers. This function is called periodically
2039 * and should forward the request to other peers until we have all
2040 * possible replies. If we have transmitted the *only* reply to
2041 * the initiator we should destroy the pending request. If we have
2042 * many replies in the queue to the initiator, we should delay sending
2043 * out more queries until the reply queue has shrunk some.
2045 * @param cls our "struct ProcessGetContext *"
2049 forward_request_task (void *cls,
2050 const struct GNUNET_SCHEDULER_TaskContext *tc)
2052 struct PendingRequest *pr = cls;
2053 struct PeerSelectionContext psc;
2054 struct ConnectedPeer *cp;
2055 struct GNUNET_TIME_Relative delay;
2057 pr->task = GNUNET_SCHEDULER_NO_TASK;
2058 if (pr->irc != NULL)
2061 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2062 "Forwarding of query `%s' not attempted due to pending local lookup!\n",
2063 GNUNET_h2s (&pr->query));
2065 return; /* already pending */
2067 if (GNUNET_YES == pr->local_only)
2068 return; /* configured to not do P2P search */
2069 /* (1) select target */
2071 psc.target_score = DBL_MIN;
2072 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
2073 &target_peer_select_cb,
2075 if (psc.target_score == DBL_MIN)
2077 delay = get_processing_delay ();
2079 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2080 "No peer selected for forwarding of query `%s', will try again in %llu ms!\n",
2081 GNUNET_h2s (&pr->query),
2084 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
2086 &forward_request_task,
2088 return; /* nobody selected */
2090 /* (3) update TTL/priority */
2092 if (pr->client_request_list != NULL)
2094 /* FIXME: use better algorithm!? */
2095 if (0 == GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2098 /* FIXME: bound priority by "customary" priority used by other peers
2100 pr->ttl = bound_ttl (pr->ttl + TTL_DECREMENT * 2,
2103 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2104 "Trying query `%s' with priority %u and TTL %d.\n",
2105 GNUNET_h2s (&pr->query),
2112 /* FIXME: should we do something here as well!? */
2115 /* (3) reserve reply bandwidth */
2116 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2117 &psc.target.hashPubKey);
2118 GNUNET_assert (NULL != cp);
2119 pr->irc = GNUNET_CORE_peer_change_preference (sched, cfg,
2121 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
2122 GNUNET_BANDWIDTH_value_init ((uint32_t) -1 /* no limit */),
2124 (uint64_t) cp->inc_preference,
2125 &target_reservation_cb,
2127 cp->inc_preference = 0.0;
2131 /* **************************** P2P PUT Handling ************************ */
2135 * Function called after we either failed or succeeded
2136 * at transmitting a reply to a peer.
2138 * @param cls the requests "struct PendingRequest*"
2139 * @param tpid ID of receiving peer, 0 on transmission error
2142 transmit_reply_continuation (void *cls,
2143 GNUNET_PEER_Id tpid)
2145 struct PendingRequest *pr = cls;
2149 case GNUNET_BLOCK_TYPE_DBLOCK:
2150 case GNUNET_BLOCK_TYPE_IBLOCK:
2151 /* only one reply expected, done with the request! */
2152 destroy_pending_request (pr);
2154 case GNUNET_BLOCK_TYPE_ANY:
2155 case GNUNET_BLOCK_TYPE_KBLOCK:
2156 case GNUNET_BLOCK_TYPE_SBLOCK:
2166 * Transmit the given message by copying it to the target buffer
2167 * "buf". "buf" will be NULL and "size" zero if the socket was closed
2168 * for writing in the meantime. In that case, do nothing
2169 * (the disconnect or shutdown handler will take care of the rest).
2170 * If we were able to transmit messages and there are still more
2171 * pending, ask core again for further calls to this function.
2173 * @param cls closure, pointer to the 'struct ClientList*'
2174 * @param size number of bytes available in buf
2175 * @param buf where the callee should write the message
2176 * @return number of bytes written to buf
2179 transmit_to_client (void *cls,
2180 size_t size, void *buf)
2182 struct ClientList *cl = cls;
2184 struct ClientResponseMessage *creply;
2191 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2192 "Not sending reply, client communication problem.\n");
2197 while ( (NULL != (creply = cl->res_head) ) &&
2198 (creply->msize <= size) )
2200 memcpy (&cbuf[msize], &creply[1], creply->msize);
2201 msize += creply->msize;
2202 size -= creply->msize;
2203 GNUNET_CONTAINER_DLL_remove (cl->res_head,
2206 GNUNET_free (creply);
2209 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
2211 GNUNET_TIME_UNIT_FOREVER_REL,
2212 &transmit_to_client,
2215 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2216 "Transmitted %u bytes to client\n",
2217 (unsigned int) msize);
2224 * Closure for "process_reply" function.
2226 struct ProcessReplyClosure
2229 * The data for the reply.
2234 * Who gave us this reply? NULL for local host.
2236 struct ConnectedPeer *sender;
2239 * When the reply expires.
2241 struct GNUNET_TIME_Absolute expiration;
2249 * Namespace that this reply belongs to
2250 * (if it is of type SBLOCK).
2252 GNUNET_HashCode namespace;
2255 * Type of the block.
2257 enum GNUNET_BLOCK_Type type;
2260 * How much was this reply worth to us?
2267 * We have received a reply; handle it!
2269 * @param cls response (struct ProcessReplyClosure)
2270 * @param key our query
2271 * @param value value in the hash map (info about the query)
2272 * @return GNUNET_YES (we should continue to iterate)
2275 process_reply (void *cls,
2276 const GNUNET_HashCode * key,
2279 struct ProcessReplyClosure *prq = cls;
2280 struct PendingRequest *pr = value;
2281 struct PendingMessage *reply;
2282 struct ClientResponseMessage *creply;
2283 struct ClientList *cl;
2284 struct PutMessage *pm;
2285 struct ConnectedPeer *cp;
2286 struct GNUNET_TIME_Relative cur_delay;
2287 GNUNET_HashCode chash;
2288 GNUNET_HashCode mhash;
2292 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2293 "Matched result (type %u) for query `%s' with pending request\n",
2294 (unsigned int) prq->type,
2297 GNUNET_STATISTICS_update (stats,
2298 gettext_noop ("# replies received and matched"),
2301 if (prq->sender != NULL)
2303 /* FIXME: should we be more precise here and not use
2304 "start_time" but a peer-specific time stamp? */
2305 cur_delay = GNUNET_TIME_absolute_get_duration (pr->start_time);
2306 prq->sender->avg_delay.value
2307 = (prq->sender->avg_delay.value *
2308 (RUNAVG_DELAY_N - 1) + cur_delay.value) / RUNAVG_DELAY_N;
2309 prq->sender->avg_priority
2310 = (prq->sender->avg_priority *
2311 (RUNAVG_DELAY_N - 1) + pr->priority) / (double) RUNAVG_DELAY_N;
2314 GNUNET_PEER_change_rc (prq->sender->last_p2p_replies
2315 [prq->sender->last_p2p_replies_woff % P2P_SUCCESS_LIST_SIZE], -1);
2316 GNUNET_PEER_change_rc (pr->cp->pid, 1);
2317 prq->sender->last_p2p_replies
2318 [(prq->sender->last_p2p_replies_woff++) % P2P_SUCCESS_LIST_SIZE]
2323 if (NULL != prq->sender->last_client_replies
2324 [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE])
2325 GNUNET_SERVER_client_drop (prq->sender->last_client_replies
2326 [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE]);
2327 prq->sender->last_client_replies
2328 [(prq->sender->last_client_replies_woff++) % CS2P_SUCCESS_LIST_SIZE]
2329 = pr->client_request_list->client_list->client;
2330 GNUNET_SERVER_client_keep (pr->client_request_list->client_list->client);
2333 GNUNET_CRYPTO_hash (prq->data,
2338 case GNUNET_BLOCK_TYPE_DBLOCK:
2339 case GNUNET_BLOCK_TYPE_IBLOCK:
2340 /* only possible reply, stop requesting! */
2341 while (NULL != pr->pending_head)
2342 destroy_pending_message_list_entry (pr->pending_head);
2345 if (pr->client_request_list != NULL)
2346 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
2348 GNUNET_DATASTORE_cancel (pr->qe);
2351 pr->do_remove = GNUNET_YES;
2352 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
2354 GNUNET_SCHEDULER_cancel (sched,
2356 pr->task = GNUNET_SCHEDULER_NO_TASK;
2358 GNUNET_break (GNUNET_YES ==
2359 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
2363 case GNUNET_BLOCK_TYPE_SBLOCK:
2364 if (pr->namespace == NULL)
2369 if (0 != memcmp (pr->namespace,
2371 sizeof (GNUNET_HashCode)))
2373 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2374 _("Reply mismatched in terms of namespace. Discarded.\n"));
2375 return GNUNET_YES; /* wrong namespace */
2377 /* then: fall-through! */
2378 case GNUNET_BLOCK_TYPE_KBLOCK:
2379 case GNUNET_BLOCK_TYPE_NBLOCK:
2382 mingle_hash (&chash, pr->mingle, &mhash);
2383 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
2386 GNUNET_STATISTICS_update (stats,
2387 gettext_noop ("# duplicate replies discarded (bloomfilter)"),
2391 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2392 "Duplicate response `%s', discarding.\n",
2393 GNUNET_h2s (&mhash));
2395 return GNUNET_YES; /* duplicate */
2398 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2399 "New response `%s', adding to filter.\n",
2400 GNUNET_h2s (&mhash));
2403 if (pr->client_request_list != NULL)
2405 if (pr->replies_seen_size == pr->replies_seen_off)
2406 GNUNET_array_grow (pr->replies_seen,
2407 pr->replies_seen_size,
2408 pr->replies_seen_size * 2 + 4);
2409 pr->replies_seen[pr->replies_seen_off++] = chash;
2411 if ( (pr->bf == NULL) ||
2412 (pr->client_request_list != NULL) )
2413 refresh_bloomfilter (pr);
2414 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
2421 prq->priority += pr->remaining_priority;
2422 pr->remaining_priority = 0;
2423 if (pr->client_request_list != NULL)
2425 GNUNET_STATISTICS_update (stats,
2426 gettext_noop ("# replies received for local clients"),
2429 cl = pr->client_request_list->client_list;
2430 msize = sizeof (struct PutMessage) + prq->size;
2431 creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
2432 creply->msize = msize;
2433 creply->client_list = cl;
2434 GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
2438 pm = (struct PutMessage*) &creply[1];
2439 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2440 pm->header.size = htons (msize);
2441 pm->type = htonl (prq->type);
2442 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
2443 memcpy (&pm[1], prq->data, prq->size);
2447 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2448 "Transmitting result for query `%s' to client\n",
2451 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
2453 GNUNET_TIME_UNIT_FOREVER_REL,
2454 &transmit_to_client,
2457 GNUNET_break (cl->th != NULL);
2459 destroy_pending_request (pr);
2465 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2466 "Transmitting result for query `%s' to other peer (PID=%u)\n",
2468 (unsigned int) cp->pid);
2470 GNUNET_STATISTICS_update (stats,
2471 gettext_noop ("# replies received for other peers"),
2474 msize = sizeof (struct PutMessage) + prq->size;
2475 reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
2476 reply->cont = &transmit_reply_continuation;
2477 reply->cont_cls = pr;
2478 reply->msize = msize;
2479 reply->priority = (uint32_t) -1; /* send replies first! */
2480 pm = (struct PutMessage*) &reply[1];
2481 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2482 pm->header.size = htons (msize);
2483 pm->type = htonl (prq->type);
2484 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
2485 memcpy (&pm[1], prq->data, prq->size);
2486 add_to_pending_messages_for_peer (cp, reply, pr);
2493 * Continuation called to notify client about result of the
2496 * @param cls closure
2497 * @param success GNUNET_SYSERR on failure
2498 * @param msg NULL on success, otherwise an error message
2501 put_migration_continuation (void *cls,
2510 * Handle P2P "PUT" message.
2512 * @param cls closure, always NULL
2513 * @param other the other peer involved (sender or receiver, NULL
2514 * for loopback messages where we are both sender and receiver)
2515 * @param message the actual message
2516 * @param latency reported latency of the connection with 'other'
2517 * @param distance reported distance (DV) to 'other'
2518 * @return GNUNET_OK to keep the connection open,
2519 * GNUNET_SYSERR to close it (signal serious error)
2522 handle_p2p_put (void *cls,
2523 const struct GNUNET_PeerIdentity *other,
2524 const struct GNUNET_MessageHeader *message,
2525 struct GNUNET_TIME_Relative latency,
2528 const struct PutMessage *put;
2531 enum GNUNET_BLOCK_Type type;
2532 struct GNUNET_TIME_Absolute expiration;
2533 GNUNET_HashCode query;
2534 struct ProcessReplyClosure prq;
2535 const struct SBlock *sb;
2537 msize = ntohs (message->size);
2538 if (msize < sizeof (struct PutMessage))
2541 return GNUNET_SYSERR;
2543 put = (const struct PutMessage*) message;
2544 dsize = msize - sizeof (struct PutMessage);
2545 type = ntohl (put->type);
2546 expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
2549 GNUNET_BLOCK_check_block (type,
2554 GNUNET_break_op (0);
2555 return GNUNET_SYSERR;
2557 if (type == GNUNET_BLOCK_TYPE_ONDEMAND)
2558 return GNUNET_SYSERR;
2559 if (GNUNET_BLOCK_TYPE_SBLOCK == type)
2561 sb = (const struct SBlock*) &put[1];
2562 GNUNET_CRYPTO_hash (&sb->subspace,
2563 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2568 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2569 "Received result for query `%s' from peer `%4s'\n",
2570 GNUNET_h2s (&query),
2571 GNUNET_i2s (other));
2573 GNUNET_STATISTICS_update (stats,
2574 gettext_noop ("# replies received (overall)"),
2577 /* now, lookup 'query' */
2578 prq.data = (const void*) &put[1];
2580 prq.sender = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2581 &other->hashPubKey);
2584 prq.expiration = expiration;
2586 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2590 if (GNUNET_YES == active_migration)
2592 GNUNET_DATASTORE_put (dsh,
2593 0, &query, dsize, &put[1],
2594 type, prq.priority, 1 /* anonymity */,
2596 1 + prq.priority, MAX_DATASTORE_QUEUE,
2597 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
2598 &put_migration_continuation,
2605 /* **************************** P2P GET Handling ************************ */
2609 * Closure for 'check_duplicate_request_{peer,client}'.
2611 struct CheckDuplicateRequestClosure
2614 * The new request we should check if it already exists.
2616 const struct PendingRequest *pr;
2619 * Existing request found by the checker, NULL if none.
2621 struct PendingRequest *have;
2626 * Iterator over entries in the 'query_request_map' that
2627 * tries to see if we have the same request pending from
2628 * the same client already.
2630 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
2631 * @param key current key code (query, ignored, must match)
2632 * @param value value in the hash map (a 'struct PendingRequest'
2633 * that already exists)
2634 * @return GNUNET_YES if we should continue to
2635 * iterate (no match yet)
2636 * GNUNET_NO if not (match found).
2639 check_duplicate_request_client (void *cls,
2640 const GNUNET_HashCode * key,
2643 struct CheckDuplicateRequestClosure *cdc = cls;
2644 struct PendingRequest *have = value;
2646 if (have->client_request_list == NULL)
2648 if ( (cdc->pr->client_request_list->client_list->client == have->client_request_list->client_list->client) &&
2659 * We're processing (local) results for a search request
2660 * from another peer. Pass applicable results to the
2661 * peer and if we are done either clean up (operation
2662 * complete) or forward to other peers (more results possible).
2664 * @param cls our closure (struct LocalGetContext)
2665 * @param key key for the content
2666 * @param size number of bytes in data
2667 * @param data content stored
2668 * @param type type of the content
2669 * @param priority priority of the content
2670 * @param anonymity anonymity-level for the content
2671 * @param expiration expiration time for the content
2672 * @param uid unique identifier for the datum;
2673 * maybe 0 if no unique identifier is available
2676 process_local_reply (void *cls,
2677 const GNUNET_HashCode * key,
2680 enum GNUNET_BLOCK_Type type,
2683 struct GNUNET_TIME_Absolute
2687 struct PendingRequest *pr = cls;
2688 struct ProcessReplyClosure prq;
2689 struct CheckDuplicateRequestClosure cdrc;
2690 const struct SBlock *sb;
2691 GNUNET_HashCode dhash;
2692 GNUNET_HashCode mhash;
2693 GNUNET_HashCode query;
2698 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2699 "Done processing local replies, forwarding request to other peers.\n");
2702 if (pr->client_request_list != NULL)
2704 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
2706 /* Figure out if this is a duplicate request and possibly
2707 merge 'struct PendingRequest' entries */
2710 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2712 &check_duplicate_request_client,
2714 if (cdrc.have != NULL)
2717 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2718 "Received request for block `%s' twice from client, will only request once.\n",
2719 GNUNET_h2s (&pr->query));
2722 destroy_pending_request (pr);
2727 /* no more results */
2728 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2729 pr->task = GNUNET_SCHEDULER_add_now (sched,
2730 &forward_request_task,
2735 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2736 "New local response to `%s' of type %u.\n",
2740 if (type == GNUNET_BLOCK_TYPE_ONDEMAND)
2743 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2744 "Found ONDEMAND block, performing on-demand encoding\n");
2746 GNUNET_STATISTICS_update (stats,
2747 gettext_noop ("# on-demand blocks matched requests"),
2751 GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
2752 anonymity, expiration, uid,
2753 &process_local_reply,
2756 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2759 /* check for duplicates */
2760 GNUNET_CRYPTO_hash (data, size, &dhash);
2761 mingle_hash (&dhash,
2764 if ( (pr->bf != NULL) &&
2766 GNUNET_CONTAINER_bloomfilter_test (pr->bf,
2770 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2771 "Result from datastore filtered by bloomfilter (duplicate).\n");
2773 GNUNET_STATISTICS_update (stats,
2774 gettext_noop ("# results filtered by query bloomfilter"),
2778 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2782 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2783 "Found result for query `%s' in local datastore\n",
2786 GNUNET_STATISTICS_update (stats,
2787 gettext_noop ("# results found locally"),
2790 pr->results_found++;
2791 memset (&prq, 0, sizeof (prq));
2793 prq.expiration = expiration;
2795 if (GNUNET_BLOCK_TYPE_SBLOCK == type)
2797 sb = (const struct SBlock*) data;
2798 GNUNET_CRYPTO_hash (&sb->subspace,
2799 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2802 if (GNUNET_OK != GNUNET_BLOCK_check_block (type,
2808 GNUNET_DATASTORE_remove (dsh,
2812 GNUNET_TIME_UNIT_FOREVER_REL,
2814 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2817 if ( (type == GNUNET_BLOCK_TYPE_DBLOCK) ||
2818 (type == GNUNET_BLOCK_TYPE_IBLOCK) )
2821 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
2823 else if ( (pr->client_request_list == NULL) &&
2824 ( (GNUNET_YES == test_load_too_high()) ||
2825 (pr->results_found > 5 + 2 * pr->priority) ) )
2828 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2829 "Load too high, done with request\n");
2831 GNUNET_STATISTICS_update (stats,
2832 gettext_noop ("# processing result set cut short due to load"),
2836 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
2838 else if (pr->qe != NULL)
2839 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2841 prq.priority = priority;
2842 process_reply (&prq, key, pr);
2847 * We've received a request with the specified priority. Bound it
2848 * according to how much we trust the given peer.
2850 * @param prio_in requested priority
2851 * @param cp the peer making the request
2852 * @return effective priority
2855 bound_priority (uint32_t prio_in,
2856 struct ConnectedPeer *cp)
2863 * Iterator over entries in the 'query_request_map' that
2864 * tries to see if we have the same request pending from
2865 * the same peer already.
2867 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
2868 * @param key current key code (query, ignored, must match)
2869 * @param value value in the hash map (a 'struct PendingRequest'
2870 * that already exists)
2871 * @return GNUNET_YES if we should continue to
2872 * iterate (no match yet)
2873 * GNUNET_NO if not (match found).
2876 check_duplicate_request_peer (void *cls,
2877 const GNUNET_HashCode * key,
2880 struct CheckDuplicateRequestClosure *cdc = cls;
2881 struct PendingRequest *have = value;
2883 if (cdc->pr->target_pid == have->target_pid)
2893 * Handle P2P "GET" request.
2895 * @param cls closure, always NULL
2896 * @param other the other peer involved (sender or receiver, NULL
2897 * for loopback messages where we are both sender and receiver)
2898 * @param message the actual message
2899 * @param latency reported latency of the connection with 'other'
2900 * @param distance reported distance (DV) to 'other'
2901 * @return GNUNET_OK to keep the connection open,
2902 * GNUNET_SYSERR to close it (signal serious error)
2905 handle_p2p_get (void *cls,
2906 const struct GNUNET_PeerIdentity *other,
2907 const struct GNUNET_MessageHeader *message,
2908 struct GNUNET_TIME_Relative latency,
2911 struct PendingRequest *pr;
2912 struct ConnectedPeer *cp;
2913 struct ConnectedPeer *cps;
2914 struct CheckDuplicateRequestClosure cdc;
2915 struct GNUNET_TIME_Relative timeout;
2917 const struct GetMessage *gm;
2919 const GNUNET_HashCode *opt;
2922 uint32_t ttl_decrement;
2923 enum GNUNET_BLOCK_Type type;
2927 msize = ntohs(message->size);
2928 if (msize < sizeof (struct GetMessage))
2930 GNUNET_break_op (0);
2931 return GNUNET_SYSERR;
2933 gm = (const struct GetMessage*) message;
2934 type = ntohl (gm->type);
2937 case GNUNET_BLOCK_TYPE_ANY:
2938 case GNUNET_BLOCK_TYPE_DBLOCK:
2939 case GNUNET_BLOCK_TYPE_IBLOCK:
2940 case GNUNET_BLOCK_TYPE_KBLOCK:
2941 case GNUNET_BLOCK_TYPE_SBLOCK:
2944 GNUNET_break_op (0);
2945 return GNUNET_SYSERR;
2947 bm = ntohl (gm->hash_bitmap);
2955 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
2957 GNUNET_break_op (0);
2958 return GNUNET_SYSERR;
2960 opt = (const GNUNET_HashCode*) &gm[1];
2961 bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
2962 bm = ntohl (gm->hash_bitmap);
2963 if ( (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)) &&
2964 (type != GNUNET_BLOCK_TYPE_SBLOCK) )
2966 GNUNET_break_op (0);
2967 return GNUNET_SYSERR;
2970 cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2971 &other->hashPubKey);
2974 /* peer must have just disconnected */
2975 GNUNET_STATISTICS_update (stats,
2976 gettext_noop ("# requests dropped due to initiator not being connected"),
2979 return GNUNET_SYSERR;
2981 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
2982 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2989 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
2990 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2991 "Failed to find RETURN-TO peer `%4s' in connection set. Dropping query.\n",
2992 GNUNET_i2s ((const struct GNUNET_PeerIdentity*) &opt[bits-1]));
2995 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2996 "Failed to find peer `%4s' in connection set. Dropping query.\n",
2997 GNUNET_i2s (other));
2999 GNUNET_STATISTICS_update (stats,
3000 gettext_noop ("# requests dropped due to missing reverse route"),
3003 /* FIXME: try connect? */
3006 /* note that we can really only check load here since otherwise
3007 peers could find out that we are overloaded by not being
3008 disconnected after sending us a malformed query... */
3009 if (GNUNET_YES == test_load_too_high ())
3012 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3013 "Dropping query from `%s', this peer is too busy.\n",
3014 GNUNET_i2s (other));
3016 GNUNET_STATISTICS_update (stats,
3017 gettext_noop ("# requests dropped due to high load"),
3024 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3025 "Received request for `%s' of type %u from peer `%4s' with flags %u\n",
3026 GNUNET_h2s (&gm->query),
3027 (unsigned int) type,
3031 have_ns = (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE));
3032 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
3033 (have_ns ? sizeof(GNUNET_HashCode) : 0));
3035 pr->namespace = (GNUNET_HashCode*) &pr[1];
3037 pr->mingle = ntohl (gm->filter_mutator);
3038 if (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
3039 memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
3040 if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
3041 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
3043 pr->anonymity_level = 1;
3044 pr->priority = bound_priority (ntohl (gm->priority), cps);
3045 pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
3046 pr->query = gm->query;
3047 /* decrement ttl (always) */
3048 ttl_decrement = 2 * TTL_DECREMENT +
3049 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3051 if ( (pr->ttl < 0) &&
3052 (((int32_t)(pr->ttl - ttl_decrement)) > 0) )
3055 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3056 "Dropping query from `%s' due to TTL underflow (%d - %u).\n",
3061 GNUNET_STATISTICS_update (stats,
3062 gettext_noop ("# requests dropped due TTL underflow"),
3065 /* integer underflow => drop (should be very rare)! */
3069 pr->ttl -= ttl_decrement;
3070 pr->start_time = GNUNET_TIME_absolute_get ();
3072 /* get bloom filter */
3075 pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
3078 pr->bf_size = bfsize;
3083 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
3085 &check_duplicate_request_peer,
3087 if (cdc.have != NULL)
3089 if (cdc.have->start_time.value + cdc.have->ttl >=
3090 pr->start_time.value + pr->ttl)
3092 /* existing request has higher TTL, drop new one! */
3093 cdc.have->priority += pr->priority;
3094 destroy_pending_request (pr);
3096 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3097 "Have existing request with higher TTL, dropping new request.\n",
3098 GNUNET_i2s (other));
3100 GNUNET_STATISTICS_update (stats,
3101 gettext_noop ("# requests dropped due to higher-TTL request"),
3108 /* existing request has lower TTL, drop old one! */
3109 pr->priority += cdc.have->priority;
3110 /* Possible optimization: if we have applicable pending
3111 replies in 'cdc.have', we might want to move those over
3112 (this is a really rare special-case, so it is not clear
3113 that this would be worth it) */
3114 destroy_pending_request (cdc.have);
3115 /* keep processing 'pr'! */
3120 GNUNET_break (GNUNET_OK ==
3121 GNUNET_CONTAINER_multihashmap_put (query_request_map,
3124 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
3125 GNUNET_break (GNUNET_OK ==
3126 GNUNET_CONTAINER_multihashmap_put (peer_request_map,
3129 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
3131 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
3133 pr->start_time.value + pr->ttl);
3135 GNUNET_STATISTICS_update (stats,
3136 gettext_noop ("# P2P searches received"),
3139 GNUNET_STATISTICS_update (stats,
3140 gettext_noop ("# P2P searches active"),
3144 /* calculate change in traffic preference */
3145 preference = (double) pr->priority;
3146 if (preference < QUERY_BANDWIDTH_VALUE)
3147 preference = QUERY_BANDWIDTH_VALUE;
3148 cps->inc_preference += preference;
3150 /* process locally */
3151 if (type == GNUNET_BLOCK_TYPE_DBLOCK)
3152 type = GNUNET_BLOCK_TYPE_ANY; /* to get on-demand as well */
3153 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
3154 (pr->priority + 1));
3155 pr->qe = GNUNET_DATASTORE_get (dsh,
3159 MAX_DATASTORE_QUEUE,
3161 &process_local_reply,
3164 /* Are multiple results possible? If so, start processing remotely now! */
3167 case GNUNET_BLOCK_TYPE_DBLOCK:
3168 case GNUNET_BLOCK_TYPE_IBLOCK:
3169 /* only one result, wait for datastore */
3172 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
3173 pr->task = GNUNET_SCHEDULER_add_now (sched,
3174 &forward_request_task,
3178 /* make sure we don't track too many requests */
3179 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
3181 pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
3182 destroy_pending_request (pr);
3188 /* **************************** CS GET Handling ************************ */
3192 * Handle START_SEARCH-message (search request from client).
3194 * @param cls closure
3195 * @param client identification of the client
3196 * @param message the actual message
3199 handle_start_search (void *cls,
3200 struct GNUNET_SERVER_Client *client,
3201 const struct GNUNET_MessageHeader *message)
3203 static GNUNET_HashCode all_zeros;
3204 const struct SearchMessage *sm;
3205 struct ClientList *cl;
3206 struct ClientRequestList *crl;
3207 struct PendingRequest *pr;
3210 enum GNUNET_BLOCK_Type type;
3212 msize = ntohs (message->size);
3213 if ( (msize < sizeof (struct SearchMessage)) ||
3214 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
3217 GNUNET_SERVER_receive_done (client,
3221 GNUNET_STATISTICS_update (stats,
3222 gettext_noop ("# client searches received"),
3225 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
3226 sm = (const struct SearchMessage*) message;
3227 type = ntohl (sm->type);
3229 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3230 "Received request for `%s' of type %u from local client\n",
3231 GNUNET_h2s (&sm->query),
3232 (unsigned int) type);
3236 case GNUNET_BLOCK_TYPE_ANY:
3237 case GNUNET_BLOCK_TYPE_DBLOCK:
3238 case GNUNET_BLOCK_TYPE_IBLOCK:
3239 case GNUNET_BLOCK_TYPE_KBLOCK:
3240 case GNUNET_BLOCK_TYPE_SBLOCK:
3241 case GNUNET_BLOCK_TYPE_NBLOCK:
3245 GNUNET_SERVER_receive_done (client,
3251 while ( (cl != NULL) &&
3252 (cl->client != client) )
3256 cl = GNUNET_malloc (sizeof (struct ClientList));
3257 cl->client = client;
3258 GNUNET_SERVER_client_keep (client);
3259 cl->next = client_list;
3262 /* detect duplicate KBLOCK requests */
3263 if ( (type == GNUNET_BLOCK_TYPE_KBLOCK) ||
3264 (type == GNUNET_BLOCK_TYPE_NBLOCK) ||
3265 (type == GNUNET_BLOCK_TYPE_ANY) )
3268 while ( (crl != NULL) &&
3269 ( (0 != memcmp (&crl->req->query,
3271 sizeof (GNUNET_HashCode))) ||
3272 (crl->req->type != type) ) )
3277 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3278 "Have existing request, merging content-seen lists.\n");
3281 /* Duplicate request (used to send long list of
3282 known/blocked results); merge 'pr->replies_seen'
3283 and update bloom filter */
3284 GNUNET_array_grow (pr->replies_seen,
3285 pr->replies_seen_size,
3286 pr->replies_seen_off + sc);
3287 memcpy (&pr->replies_seen[pr->replies_seen_off],
3289 sc * sizeof (GNUNET_HashCode));
3290 pr->replies_seen_off += sc;
3291 refresh_bloomfilter (pr);
3292 GNUNET_STATISTICS_update (stats,
3293 gettext_noop ("# client searches updated (merged content seen list)"),
3296 GNUNET_SERVER_receive_done (client,
3301 GNUNET_STATISTICS_update (stats,
3302 gettext_noop ("# client searches active"),
3305 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
3306 ((type == GNUNET_BLOCK_TYPE_SBLOCK) ? sizeof(GNUNET_HashCode) : 0));
3307 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
3308 memset (crl, 0, sizeof (struct ClientRequestList));
3309 crl->client_list = cl;
3310 GNUNET_CONTAINER_DLL_insert (cl->rl_head,
3315 pr->client_request_list = crl;
3316 GNUNET_array_grow (pr->replies_seen,
3317 pr->replies_seen_size,
3319 memcpy (pr->replies_seen,
3321 sc * sizeof (GNUNET_HashCode));
3322 pr->replies_seen_off = sc;
3323 pr->anonymity_level = ntohl (sm->anonymity_level);
3324 refresh_bloomfilter (pr);
3325 pr->query = sm->query;
3326 if (0 == (1 & ntohl (sm->options)))
3327 pr->local_only = GNUNET_NO;
3329 pr->local_only = GNUNET_YES;
3332 case GNUNET_BLOCK_TYPE_DBLOCK:
3333 case GNUNET_BLOCK_TYPE_IBLOCK:
3334 if (0 != memcmp (&sm->target,
3336 sizeof (GNUNET_HashCode)))
3337 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
3339 case GNUNET_BLOCK_TYPE_SBLOCK:
3340 pr->namespace = (GNUNET_HashCode*) &pr[1];
3341 memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
3346 GNUNET_break (GNUNET_OK ==
3347 GNUNET_CONTAINER_multihashmap_put (query_request_map,
3350 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
3351 if (type == GNUNET_BLOCK_TYPE_DBLOCK)
3352 type = GNUNET_BLOCK_TYPE_ANY; /* get on-demand blocks too! */
3353 pr->qe = GNUNET_DATASTORE_get (dsh,
3357 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
3358 &process_local_reply,
3363 /* **************************** Startup ************************ */
3367 * List of handlers for P2P messages
3368 * that we care about.
3370 static struct GNUNET_CORE_MessageHandler p2p_handlers[] =
3373 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
3375 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
3381 * List of handlers for the messages understood by this
3384 static struct GNUNET_SERVER_MessageHandler handlers[] = {
3385 {&GNUNET_FS_handle_index_start, NULL,
3386 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
3387 {&GNUNET_FS_handle_index_list_get, NULL,
3388 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
3389 {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
3390 sizeof (struct UnindexMessage) },
3391 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
3398 * Process fs requests.
3400 * @param s scheduler to use
3401 * @param server the initialized server
3402 * @param c configuration to use
3405 main_init (struct GNUNET_SCHEDULER_Handle *s,
3406 struct GNUNET_SERVER_Handle *server,
3407 const struct GNUNET_CONFIGURATION_Handle *c)
3411 stats = GNUNET_STATISTICS_create (sched, "fs", cfg);
3412 min_migration_delay = GNUNET_TIME_UNIT_SECONDS; // FIXME: get from config
3413 connected_peers = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3414 query_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3415 peer_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3416 requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
3417 core = GNUNET_CORE_connect (sched,
3419 GNUNET_TIME_UNIT_FOREVER_REL,
3422 &peer_connect_handler,
3423 &peer_disconnect_handler,
3429 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3430 _("Failed to connect to `%s' service.\n"),
3432 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
3433 connected_peers = NULL;
3434 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
3435 query_request_map = NULL;
3436 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
3437 requests_by_expiration_heap = NULL;
3438 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
3439 peer_request_map = NULL;
3442 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
3445 return GNUNET_SYSERR;
3447 /* FIXME: distinguish between sending and storing in options? */
3448 if (active_migration)
3449 consider_migration_gathering ();
3450 GNUNET_SERVER_disconnect_notify (server,
3451 &handle_client_disconnect,
3453 GNUNET_SERVER_add_handlers (server, handlers);
3454 GNUNET_SCHEDULER_add_delayed (sched,
3455 GNUNET_TIME_UNIT_FOREVER_REL,
3463 * Process fs requests.
3465 * @param cls closure
3466 * @param sched scheduler to use
3467 * @param server the initialized server
3468 * @param cfg configuration to use
3472 struct GNUNET_SCHEDULER_Handle *sched,
3473 struct GNUNET_SERVER_Handle *server,
3474 const struct GNUNET_CONFIGURATION_Handle *cfg)
3476 active_migration = GNUNET_CONFIGURATION_get_value_yesno (cfg,
3479 dsh = GNUNET_DATASTORE_connect (cfg,
3483 GNUNET_SCHEDULER_shutdown (sched);
3486 if ( (GNUNET_OK != GNUNET_FS_indexing_init (sched, cfg, dsh)) ||
3487 (GNUNET_OK != main_init (sched, server, cfg)) )
3489 GNUNET_SCHEDULER_shutdown (sched);
3490 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
3498 * The main function for the fs service.
3500 * @param argc number of arguments from the command line
3501 * @param argv command line arguments
3502 * @return 0 ok, 1 on error
3505 main (int argc, char *const *argv)
3507 return (GNUNET_OK ==
3508 GNUNET_SERVICE_run (argc,
3511 GNUNET_SERVICE_OPTION_NONE,
3512 &run, NULL)) ? 0 : 1;
3515 /* end of gnunet-service-fs.c */