2 This file is part of GNUnet.
3 (C) 2009, 2010 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file fs/gnunet-service-fs.c
23 * @brief gnunet anonymity protocol implementation
24 * @author Christian Grothoff
27 * - implement test_load_too_high, make decision priority-based, implement forwarding, etc.
28 * - consider more precise latency estimation (per-peer & request)
29 * - introduce random latency in processing
30 * - tell other peers to stop migration if our PUTs fail (or if
31 * we don't support migration per configuration?)
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.
52 #define MAX_QUEUE_PER_PEER 16
55 * How often do we flush trust values to disk?
57 #define TRUST_FLUSH_FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
61 * Inverse of the probability that we will submit the same query
62 * to the same peer again. If the same peer already got the query
63 * repeatedly recently, the probability is multiplied by the inverse
64 * of this number each time. Note that we only try about every TTL_DECREMENT/2
65 * plus MAX_CORK_DELAY (so roughly every 3.5s).
67 #define RETRY_PROBABILITY_INV 3
70 * What is the maximum delay for a P2P FS message (in our interaction
71 * with core)? FS-internal delays are another story. The value is
72 * chosen based on the 32k block size. Given that peers typcially
73 * have at least 1 kb/s bandwidth, 45s waits give us a chance to
74 * transmit one message even to the lowest-bandwidth peers.
76 #define MAX_TRANSMIT_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 45)
81 * Maximum number of requests (from other peers) that we're
82 * willing to have pending at any given point in time.
83 * FIXME: set from configuration.
85 static uint64_t max_pending_requests = (32 * 1024);
89 * Information we keep for each pending reply. The
90 * actual message follows at the end of this struct.
92 struct PendingMessage;
95 * Function called upon completion of a transmission.
98 * @param pid ID of receiving peer, 0 on transmission error
100 typedef void (*TransmissionContinuation)(void * cls,
101 GNUNET_PEER_Id tpid);
105 * Information we keep for each pending message (GET/PUT). The
106 * actual message follows at the end of this struct.
108 struct PendingMessage
111 * This is a doubly-linked list of messages to the same peer.
113 struct PendingMessage *next;
116 * This is a doubly-linked list of messages to the same peer.
118 struct PendingMessage *prev;
121 * Entry in pending message list for this pending message.
123 struct PendingMessageList *pml;
126 * Function to call immediately once we have transmitted this
129 TransmissionContinuation cont;
137 * Size of the reply; actual reply message follows
138 * at the end of this struct.
143 * How important is this message for us?
151 * Information about a peer that we are connected to.
152 * We track data that is useful for determining which
153 * peers should receive our requests. We also keep
154 * a list of messages to transmit to this peer.
160 * List of the last clients for which this peer successfully
163 struct GNUNET_SERVER_Client *last_client_replies[CS2P_SUCCESS_LIST_SIZE];
166 * List of the last PIDs for which
167 * this peer successfully answered a query;
168 * We use 0 to indicate no successful reply.
170 GNUNET_PEER_Id last_p2p_replies[P2P_SUCCESS_LIST_SIZE];
173 * Average delay between sending the peer a request and
174 * getting a reply (only calculated over the requests for
175 * which we actually got a reply). Calculated
176 * as a moving average: new_delay = ((n-1)*last_delay+curr_delay) / n
178 struct GNUNET_TIME_Relative avg_delay;
181 * Handle for an active request for transmission to this
184 struct GNUNET_CORE_TransmitHandle *cth;
187 * Messages (replies, queries, content migration) we would like to
188 * send to this peer in the near future. Sorted by priority, head.
190 struct PendingMessage *pending_messages_head;
193 * Messages (replies, queries, content migration) we would like to
194 * send to this peer in the near future. Sorted by priority, tail.
196 struct PendingMessage *pending_messages_tail;
199 * Average priority of successful replies. Calculated
200 * as a moving average: new_avg = ((n-1)*last_avg+curr_prio) / n
205 * Increase in traffic preference still to be submitted
206 * to the core service for this peer.
208 uint64_t inc_preference;
211 * Trust rating for this peer
216 * Trust rating for this peer on disk.
221 * The peer's identity.
226 * Size of the linked list of 'pending_messages'.
228 unsigned int pending_requests;
231 * Which offset in "last_p2p_replies" will be updated next?
232 * (we go round-robin).
234 unsigned int last_p2p_replies_woff;
237 * Which offset in "last_client_replies" will be updated next?
238 * (we go round-robin).
240 unsigned int last_client_replies_woff;
246 * Information we keep for each pending request. We should try to
247 * keep this struct as small as possible since its memory consumption
248 * is key to how many requests we can have pending at once.
250 struct PendingRequest;
254 * Doubly-linked list of requests we are performing
255 * on behalf of the same client.
257 struct ClientRequestList
261 * This is a doubly-linked list.
263 struct ClientRequestList *next;
266 * This is a doubly-linked list.
268 struct ClientRequestList *prev;
271 * Request this entry represents.
273 struct PendingRequest *req;
276 * Client list this request belongs to.
278 struct ClientList *client_list;
284 * Replies to be transmitted to the client. The actual
285 * response message is allocated after this struct.
287 struct ClientResponseMessage
290 * This is a doubly-linked list.
292 struct ClientResponseMessage *next;
295 * This is a doubly-linked list.
297 struct ClientResponseMessage *prev;
300 * Client list entry this response belongs to.
302 struct ClientList *client_list;
305 * Number of bytes in the response.
312 * Linked list of clients we are performing requests
318 * This is a linked list.
320 struct ClientList *next;
323 * ID of a client making a request, NULL if this entry is for a
326 struct GNUNET_SERVER_Client *client;
329 * Head of list of requests performed on behalf
330 * of this client right now.
332 struct ClientRequestList *rl_head;
335 * Tail of list of requests performed on behalf
336 * of this client right now.
338 struct ClientRequestList *rl_tail;
341 * Head of linked list of responses.
343 struct ClientResponseMessage *res_head;
346 * Tail of linked list of responses.
348 struct ClientResponseMessage *res_tail;
351 * Context for sending replies.
353 struct GNUNET_CONNECTION_TransmitHandle *th;
359 * Doubly-linked list of messages we are performing
360 * due to a pending request.
362 struct PendingMessageList
366 * This is a doubly-linked list of messages on behalf of the same request.
368 struct PendingMessageList *next;
371 * This is a doubly-linked list of messages on behalf of the same request.
373 struct PendingMessageList *prev;
376 * Message this entry represents.
378 struct PendingMessage *pm;
381 * Request this entry belongs to.
383 struct PendingRequest *req;
386 * Peer this message is targeted for.
388 struct ConnectedPeer *target;
394 * Information we keep for each pending request. We should try to
395 * keep this struct as small as possible since its memory consumption
396 * is key to how many requests we can have pending at once.
398 struct PendingRequest
402 * If this request was made by a client, this is our entry in the
403 * client request list; otherwise NULL.
405 struct ClientRequestList *client_request_list;
408 * Entry of peer responsible for this entry (if this request
409 * was made by a peer).
411 struct ConnectedPeer *cp;
414 * If this is a namespace query, pointer to the hash of the public
415 * key of the namespace; otherwise NULL. Pointer will be to the
416 * end of this struct (so no need to free it).
418 const GNUNET_HashCode *namespace;
421 * Bloomfilter we use to filter out replies that we don't care about
422 * (anymore). NULL as long as we are interested in all replies.
424 struct GNUNET_CONTAINER_BloomFilter *bf;
427 * Context of our GNUNET_CORE_peer_change_preference call.
429 struct GNUNET_CORE_InformationRequestContext *irc;
432 * Hash code of all replies that we have seen so far (only valid
433 * if client is not NULL since we only track replies like this for
436 GNUNET_HashCode *replies_seen;
439 * Node in the heap representing this entry; NULL
440 * if we have no heap node.
442 struct GNUNET_CONTAINER_HeapNode *hnode;
445 * Head of list of messages being performed on behalf of this
448 struct PendingMessageList *pending_head;
451 * Tail of list of messages being performed on behalf of this
454 struct PendingMessageList *pending_tail;
457 * When did we first see this request (form this peer), or, if our
458 * client is initiating, when did we last initiate a search?
460 struct GNUNET_TIME_Absolute start_time;
463 * The query that this request is for.
465 GNUNET_HashCode query;
468 * The task responsible for transmitting queries
471 GNUNET_SCHEDULER_TaskIdentifier task;
474 * (Interned) Peer identifier that identifies a preferred target
477 GNUNET_PEER_Id target_pid;
480 * (Interned) Peer identifiers of peers that have already
481 * received our query for this content.
483 GNUNET_PEER_Id *used_pids;
486 * Our entry in the queue (non-NULL while we wait for our
487 * turn to interact with the local database).
489 struct GNUNET_DATASTORE_QueueEntry *qe;
492 * Size of the 'bf' (in bytes).
497 * Desired anonymity level; only valid for requests from a local client.
499 uint32_t anonymity_level;
502 * How many entries in "used_pids" are actually valid?
504 unsigned int used_pids_off;
507 * How long is the "used_pids" array?
509 unsigned int used_pids_size;
512 * Number of results found for this request.
514 unsigned int results_found;
517 * How many entries in "replies_seen" are actually valid?
519 unsigned int replies_seen_off;
522 * How long is the "replies_seen" array?
524 unsigned int replies_seen_size;
527 * Priority with which this request was made. If one of our clients
528 * made the request, then this is the current priority that we are
529 * using when initiating the request. This value is used when
530 * we decide to reward other peers with trust for providing a reply.
535 * Priority points left for us to spend when forwarding this request
538 uint32_t remaining_priority;
541 * Number to mingle hashes for bloom-filter tests with.
546 * TTL with which we saw this request (or, if we initiated, TTL that
547 * we used for the request).
552 * Type of the content that this request is for.
554 enum GNUNET_BLOCK_Type type;
557 * Remove this request after transmission of the current response.
562 * GNUNET_YES if we should not forward this request to other peers.
570 * Block that is ready for migration to other peers. Actual data is at the end of the block.
572 struct MigrationReadyBlock
576 * This is a doubly-linked list.
578 struct MigrationReadyBlock *next;
581 * This is a doubly-linked list.
583 struct MigrationReadyBlock *prev;
586 * Query for the block.
588 GNUNET_HashCode query;
591 * When does this block expire?
593 struct GNUNET_TIME_Absolute expiration;
596 * Peers we would consider forwarding this
597 * block to. Zero for empty entries.
599 GNUNET_PEER_Id target_list[MIGRATION_LIST_SIZE];
607 * Number of targets already used.
609 unsigned int used_targets;
614 enum GNUNET_BLOCK_Type type;
619 * Our connection to the datastore.
621 static struct GNUNET_DATASTORE_Handle *dsh;
627 static struct GNUNET_SCHEDULER_Handle *sched;
632 static const struct GNUNET_CONFIGURATION_Handle *cfg;
635 * Map of peer identifiers to "struct ConnectedPeer" (for that peer).
637 static struct GNUNET_CONTAINER_MultiHashMap *connected_peers;
640 * Map of peer identifiers to "struct PendingRequest" (for that peer).
642 static struct GNUNET_CONTAINER_MultiHashMap *peer_request_map;
645 * Map of query identifiers to "struct PendingRequest" (for that query).
647 static struct GNUNET_CONTAINER_MultiHashMap *query_request_map;
650 * Heap with the request that will expire next at the top. Contains
651 * pointers of type "struct PendingRequest*"; these will *also* be
652 * aliased from the "requests_by_peer" data structures and the
653 * "requests_by_query" table. Note that requests from our clients
654 * don't expire and are thus NOT in the "requests_by_expiration"
655 * (or the "requests_by_peer" tables).
657 static struct GNUNET_CONTAINER_Heap *requests_by_expiration_heap;
660 * Handle for reporting statistics.
662 static struct GNUNET_STATISTICS_Handle *stats;
665 * Linked list of clients we are currently processing requests for.
667 static struct ClientList *client_list;
670 * Pointer to handle to the core service (points to NULL until we've
673 static struct GNUNET_CORE_Handle *core;
676 * Head of linked list of blocks that can be migrated.
678 static struct MigrationReadyBlock *mig_head;
681 * Tail of linked list of blocks that can be migrated.
683 static struct MigrationReadyBlock *mig_tail;
686 * Request to datastore for migration (or NULL).
688 static struct GNUNET_DATASTORE_QueueEntry *mig_qe;
691 * Where do we store trust information?
693 static char *trustDirectory;
696 * ID of task that collects blocks for migration.
698 static GNUNET_SCHEDULER_TaskIdentifier mig_task;
701 * What is the maximum frequency at which we are allowed to
702 * poll the datastore for migration content?
704 static struct GNUNET_TIME_Relative min_migration_delay;
707 * Size of the doubly-linked list of migration blocks.
709 static unsigned int mig_size;
712 * Are we allowed to migrate content to this peer.
714 static int active_migration;
717 * Typical priorities we're seeing from other peers right now. Since
718 * most priorities will be zero, this value is the weighted average of
719 * non-zero priorities seen "recently". In order to ensure that new
720 * values do not dramatically change the ratio, values are first
721 * "capped" to a reasonable range (+N of the current value) and then
722 * averaged into the existing value by a ratio of 1:N. Hence
723 * receiving the largest possible priority can still only raise our
724 * "current_priorities" by at most 1.
726 static double current_priorities;
729 * Get the filename under which we would store the GNUNET_HELLO_Message
730 * for the given host and protocol.
731 * @return filename of the form DIRECTORY/HOSTID
734 get_trust_filename (const struct GNUNET_PeerIdentity *id)
736 struct GNUNET_CRYPTO_HashAsciiEncoded fil;
739 GNUNET_CRYPTO_hash_to_enc (&id->hashPubKey, &fil);
740 GNUNET_asprintf (&fn, "%s%s%s", trustDirectory, DIR_SEPARATOR_STR, &fil);
747 * Transmit messages by copying it to the target buffer
748 * "buf". "buf" will be NULL and "size" zero if the socket was closed
749 * for writing in the meantime. In that case, do nothing
750 * (the disconnect or shutdown handler will take care of the rest).
751 * If we were able to transmit messages and there are still more
752 * pending, ask core again for further calls to this function.
754 * @param cls closure, pointer to the 'struct ConnectedPeer*'
755 * @param size number of bytes available in buf
756 * @param buf where the callee should write the message
757 * @return number of bytes written to buf
760 transmit_to_peer (void *cls,
761 size_t size, void *buf);
764 /* ******************* clean up functions ************************ */
768 * Delete the given migration block.
770 * @param mb block to delete
773 delete_migration_block (struct MigrationReadyBlock *mb)
775 GNUNET_CONTAINER_DLL_remove (mig_head,
778 GNUNET_PEER_decrement_rcs (mb->target_list,
779 MIGRATION_LIST_SIZE);
786 * Compare the distance of two peers to a key.
789 * @param p1 first peer
790 * @param p2 second peer
791 * @return GNUNET_YES if P1 is closer to key than P2
794 is_closer (const GNUNET_HashCode *key,
795 const struct GNUNET_PeerIdentity *p1,
796 const struct GNUNET_PeerIdentity *p2)
798 return GNUNET_CRYPTO_hash_xorcmp (&p1->hashPubKey,
805 * Consider migrating content to a given peer.
807 * @param cls 'struct MigrationReadyBlock*' to select
808 * targets for (or NULL for none)
809 * @param key ID of the peer
810 * @param value 'struct ConnectedPeer' of the peer
811 * @return GNUNET_YES (always continue iteration)
814 consider_migration (void *cls,
815 const GNUNET_HashCode *key,
818 struct MigrationReadyBlock *mb = cls;
819 struct ConnectedPeer *cp = value;
820 struct MigrationReadyBlock *pos;
821 struct GNUNET_PeerIdentity cppid;
822 struct GNUNET_PeerIdentity otherpid;
823 struct GNUNET_PeerIdentity worstpid;
828 /* consider 'cp' as a migration target for mb */
831 GNUNET_PEER_resolve (cp->pid,
833 repl = MIGRATION_LIST_SIZE;
834 for (i=0;i<MIGRATION_LIST_SIZE;i++)
836 if (mb->target_list[i] == 0)
838 mb->target_list[i] = cp->pid;
839 GNUNET_PEER_change_rc (mb->target_list[i], 1);
840 repl = MIGRATION_LIST_SIZE;
843 GNUNET_PEER_resolve (mb->target_list[i],
845 if ( (repl == MIGRATION_LIST_SIZE) &&
846 is_closer (&mb->query,
853 else if ( (repl != MIGRATION_LIST_SIZE) &&
854 (is_closer (&mb->query,
862 if (repl != MIGRATION_LIST_SIZE)
864 GNUNET_PEER_change_rc (mb->target_list[repl], -1);
865 mb->target_list[repl] = cp->pid;
866 GNUNET_PEER_change_rc (mb->target_list[repl], 1);
870 /* consider scheduling transmission to cp for content migration */
877 for (i=0;i<MIGRATION_LIST_SIZE;i++)
879 if (cp->pid == pos->target_list[i])
884 msize = GNUNET_MIN (msize,
892 return GNUNET_YES; /* no content available */
894 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
895 "Trying to migrate at least %u bytes to peer `%s'\n",
900 = GNUNET_CORE_notify_transmit_ready (core,
901 0, GNUNET_TIME_UNIT_FOREVER_REL,
902 (const struct GNUNET_PeerIdentity*) key,
903 msize + sizeof (struct PutMessage),
911 * Task that is run periodically to obtain blocks for content
915 * @param tc scheduler context (also unused)
918 gather_migration_blocks (void *cls,
919 const struct GNUNET_SCHEDULER_TaskContext *tc);
923 * If the migration task is not currently running, consider
924 * (re)scheduling it with the appropriate delay.
927 consider_migration_gathering ()
929 struct GNUNET_TIME_Relative delay;
933 if (mig_task != GNUNET_SCHEDULER_NO_TASK)
935 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
937 delay = GNUNET_TIME_relative_divide (delay,
938 MAX_MIGRATION_QUEUE);
939 delay = GNUNET_TIME_relative_max (delay,
940 min_migration_delay);
941 mig_task = GNUNET_SCHEDULER_add_delayed (sched,
943 &gather_migration_blocks,
949 * Process content offered for migration.
952 * @param key key for the content
953 * @param size number of bytes in data
954 * @param data content stored
955 * @param type type of the content
956 * @param priority priority of the content
957 * @param anonymity anonymity-level for the content
958 * @param expiration expiration time for the content
959 * @param uid unique identifier for the datum;
960 * maybe 0 if no unique identifier is available
963 process_migration_content (void *cls,
964 const GNUNET_HashCode * key,
967 enum GNUNET_BLOCK_Type type,
970 struct GNUNET_TIME_Absolute
971 expiration, uint64_t uid)
973 struct MigrationReadyBlock *mb;
978 if (mig_size < MAX_MIGRATION_QUEUE)
979 consider_migration_gathering ();
982 if (type == GNUNET_BLOCK_TYPE_ONDEMAND)
985 GNUNET_FS_handle_on_demand_block (key, size, data,
986 type, priority, anonymity,
988 &process_migration_content,
990 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
994 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
995 "Retrieved block `%s' of type %u for migration\n",
999 mb = GNUNET_malloc (sizeof (struct MigrationReadyBlock) + size);
1001 mb->expiration = expiration;
1004 memcpy (&mb[1], data, size);
1005 GNUNET_CONTAINER_DLL_insert_after (mig_head,
1010 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1011 &consider_migration,
1013 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1018 * Task that is run periodically to obtain blocks for content
1022 * @param tc scheduler context (also unused)
1025 gather_migration_blocks (void *cls,
1026 const struct GNUNET_SCHEDULER_TaskContext *tc)
1028 mig_task = GNUNET_SCHEDULER_NO_TASK;
1029 mig_qe = GNUNET_DATASTORE_get_random (dsh, 0, -1,
1030 GNUNET_TIME_UNIT_FOREVER_REL,
1031 &process_migration_content, NULL);
1032 GNUNET_assert (mig_qe != NULL);
1037 * We're done with a particular message list entry.
1038 * Free all associated resources.
1040 * @param pml entry to destroy
1043 destroy_pending_message_list_entry (struct PendingMessageList *pml)
1045 GNUNET_CONTAINER_DLL_remove (pml->req->pending_head,
1046 pml->req->pending_tail,
1048 GNUNET_CONTAINER_DLL_remove (pml->target->pending_messages_head,
1049 pml->target->pending_messages_tail,
1051 pml->target->pending_requests--;
1052 GNUNET_free (pml->pm);
1058 * Destroy the given pending message (and call the respective
1061 * @param pm message to destroy
1062 * @param tpid id of peer that the message was delivered to, or 0 for none
1065 destroy_pending_message (struct PendingMessage *pm,
1066 GNUNET_PEER_Id tpid)
1068 struct PendingMessageList *pml = pm->pml;
1069 TransmissionContinuation cont;
1072 GNUNET_assert (pml->pm == pm);
1073 GNUNET_assert ( (tpid == 0) || (tpid == pml->target->pid) );
1075 cont_cls = pm->cont_cls;
1076 destroy_pending_message_list_entry (pml);
1077 cont (cont_cls, tpid);
1082 * We're done processing a particular request.
1083 * Free all associated resources.
1085 * @param pr request to destroy
1088 destroy_pending_request (struct PendingRequest *pr)
1090 struct GNUNET_PeerIdentity pid;
1092 if (pr->hnode != NULL)
1094 GNUNET_CONTAINER_heap_remove_node (requests_by_expiration_heap,
1098 if (NULL == pr->client_request_list)
1100 GNUNET_STATISTICS_update (stats,
1101 gettext_noop ("# P2P searches active"),
1107 GNUNET_STATISTICS_update (stats,
1108 gettext_noop ("# client searches active"),
1112 /* might have already been removed from map in 'process_reply' (if
1113 there was a unique reply) or never inserted if it was a
1114 duplicate; hence ignore the return value here */
1115 (void) GNUNET_CONTAINER_multihashmap_remove (query_request_map,
1120 GNUNET_DATASTORE_cancel (pr->qe);
1123 if (pr->client_request_list != NULL)
1125 GNUNET_CONTAINER_DLL_remove (pr->client_request_list->client_list->rl_head,
1126 pr->client_request_list->client_list->rl_tail,
1127 pr->client_request_list);
1128 GNUNET_free (pr->client_request_list);
1129 pr->client_request_list = NULL;
1133 GNUNET_PEER_resolve (pr->cp->pid,
1135 (void) GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
1142 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
1145 if (pr->irc != NULL)
1147 GNUNET_CORE_peer_change_preference_cancel (pr->irc);
1150 if (pr->replies_seen != NULL)
1152 GNUNET_free (pr->replies_seen);
1153 pr->replies_seen = NULL;
1155 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
1157 GNUNET_SCHEDULER_cancel (sched,
1159 pr->task = GNUNET_SCHEDULER_NO_TASK;
1161 while (NULL != pr->pending_head)
1162 destroy_pending_message_list_entry (pr->pending_head);
1163 GNUNET_PEER_change_rc (pr->target_pid, -1);
1164 if (pr->used_pids != NULL)
1166 GNUNET_PEER_decrement_rcs (pr->used_pids, pr->used_pids_off);
1167 GNUNET_free (pr->used_pids);
1168 pr->used_pids_off = 0;
1169 pr->used_pids_size = 0;
1170 pr->used_pids = NULL;
1177 * Method called whenever a given peer connects.
1179 * @param cls closure, not used
1180 * @param peer peer identity this notification is about
1181 * @param latency reported latency of the connection with 'other'
1182 * @param distance reported distance (DV) to 'other'
1185 peer_connect_handler (void *cls,
1187 GNUNET_PeerIdentity * peer,
1188 struct GNUNET_TIME_Relative latency,
1191 struct ConnectedPeer *cp;
1192 struct MigrationReadyBlock *pos;
1196 cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
1197 cp->pid = GNUNET_PEER_intern (peer);
1199 fn = get_trust_filename (peer);
1200 if ((GNUNET_DISK_file_test (fn) == GNUNET_YES) &&
1201 (sizeof (trust) == GNUNET_DISK_fn_read (fn, &trust, sizeof (trust))))
1202 cp->disk_trust = cp->trust = ntohl (trust);
1205 GNUNET_break (GNUNET_OK ==
1206 GNUNET_CONTAINER_multihashmap_put (connected_peers,
1209 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1214 (void) consider_migration (pos, &peer->hashPubKey, cp);
1221 * Increase the host credit by a value.
1223 * @param host which peer to change the trust value on
1224 * @param value is the int value by which the
1225 * host credit is to be increased or decreased
1226 * @returns the actual change in trust (positive or negative)
1229 change_host_trust (struct ConnectedPeer *host, int value)
1231 unsigned int old_trust;
1235 GNUNET_assert (host != NULL);
1236 old_trust = host->trust;
1239 if (host->trust + value < host->trust)
1241 value = UINT32_MAX - host->trust;
1242 host->trust = UINT32_MAX;
1245 host->trust += value;
1249 if (host->trust < -value)
1251 value = -host->trust;
1255 host->trust += value;
1262 * Write host-trust information to a file - flush the buffer entry!
1265 flush_trust (void *cls,
1266 const GNUNET_HashCode *key,
1269 struct ConnectedPeer *host = value;
1272 struct GNUNET_PeerIdentity pid;
1274 if (host->trust == host->disk_trust)
1275 return GNUNET_OK; /* unchanged */
1276 GNUNET_PEER_resolve (host->pid,
1278 fn = get_trust_filename (&pid);
1279 if (host->trust == 0)
1281 if ((0 != UNLINK (fn)) && (errno != ENOENT))
1282 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
1283 GNUNET_ERROR_TYPE_BULK, "unlink", fn);
1287 trust = htonl (host->trust);
1288 if (sizeof(uint32_t) == GNUNET_DISK_fn_write (fn, &trust,
1290 GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE
1291 | GNUNET_DISK_PERM_GROUP_READ | GNUNET_DISK_PERM_OTHER_READ))
1292 host->disk_trust = host->trust;
1299 * Call this method periodically to scan data/hosts for new hosts.
1302 cron_flush_trust (void *cls,
1303 const struct GNUNET_SCHEDULER_TaskContext *tc)
1306 if (NULL == connected_peers)
1308 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1313 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1315 GNUNET_SCHEDULER_add_delayed (tc->sched,
1316 TRUST_FLUSH_FREQ, &cron_flush_trust, NULL);
1321 * Free (each) request made by the peer.
1323 * @param cls closure, points to peer that the request belongs to
1324 * @param key current key code
1325 * @param value value in the hash map
1326 * @return GNUNET_YES (we should continue to iterate)
1329 destroy_request (void *cls,
1330 const GNUNET_HashCode * key,
1333 const struct GNUNET_PeerIdentity * peer = cls;
1334 struct PendingRequest *pr = value;
1336 GNUNET_break (GNUNET_YES ==
1337 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
1340 destroy_pending_request (pr);
1346 * Method called whenever a peer disconnects.
1348 * @param cls closure, not used
1349 * @param peer peer identity this notification is about
1352 peer_disconnect_handler (void *cls,
1354 GNUNET_PeerIdentity * peer)
1356 struct ConnectedPeer *cp;
1357 struct PendingMessage *pm;
1359 struct MigrationReadyBlock *pos;
1360 struct MigrationReadyBlock *next;
1362 GNUNET_CONTAINER_multihashmap_get_multiple (peer_request_map,
1366 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1370 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1372 if (NULL != cp->last_client_replies[i])
1374 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1375 cp->last_client_replies[i] = NULL;
1378 GNUNET_break (GNUNET_YES ==
1379 GNUNET_CONTAINER_multihashmap_remove (connected_peers,
1382 /* remove this peer from migration considerations; schedule
1385 while (NULL != (pos = next))
1388 for (i=0;i<MIGRATION_LIST_SIZE;i++)
1390 if (pos->target_list[i] == cp->pid)
1392 GNUNET_PEER_change_rc (pos->target_list[i], -1);
1393 pos->target_list[i] = 0;
1396 if (pos->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers))
1398 delete_migration_block (pos);
1399 consider_migration_gathering ();
1402 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1403 &consider_migration,
1406 GNUNET_PEER_change_rc (cp->pid, -1);
1407 GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
1408 if (NULL != cp->cth)
1409 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
1410 while (NULL != (pm = cp->pending_messages_head))
1411 destroy_pending_message (pm, 0 /* delivery failed */);
1412 GNUNET_break (0 == cp->pending_requests);
1418 * Iterator over hash map entries that removes all occurences
1419 * of the given 'client' from the 'last_client_replies' of the
1420 * given connected peer.
1422 * @param cls closure, the 'struct GNUNET_SERVER_Client*' to remove
1423 * @param key current key code (unused)
1424 * @param value value in the hash map (the 'struct ConnectedPeer*' to change)
1425 * @return GNUNET_YES (we should continue to iterate)
1428 remove_client_from_last_client_replies (void *cls,
1429 const GNUNET_HashCode * key,
1432 struct GNUNET_SERVER_Client *client = cls;
1433 struct ConnectedPeer *cp = value;
1436 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1438 if (cp->last_client_replies[i] == client)
1440 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1441 cp->last_client_replies[i] = NULL;
1449 * A client disconnected. Remove all of its pending queries.
1451 * @param cls closure, NULL
1452 * @param client identification of the client
1455 handle_client_disconnect (void *cls,
1456 struct GNUNET_SERVER_Client
1459 struct ClientList *pos;
1460 struct ClientList *prev;
1461 struct ClientRequestList *rcl;
1462 struct ClientResponseMessage *creply;
1468 while ( (NULL != pos) &&
1469 (pos->client != client) )
1475 return; /* no requests pending for this client */
1476 while (NULL != (rcl = pos->rl_head))
1478 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1479 "Destroying pending request `%s' on disconnect\n",
1480 GNUNET_h2s (&rcl->req->query));
1481 destroy_pending_request (rcl->req);
1484 client_list = pos->next;
1486 prev->next = pos->next;
1487 if (pos->th != NULL)
1489 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
1492 while (NULL != (creply = pos->res_head))
1494 GNUNET_CONTAINER_DLL_remove (pos->res_head,
1497 GNUNET_free (creply);
1499 GNUNET_SERVER_client_drop (pos->client);
1501 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1502 &remove_client_from_last_client_replies,
1508 * Iterator to free peer entries.
1510 * @param cls closure, unused
1511 * @param key current key code
1512 * @param value value in the hash map (peer entry)
1513 * @return GNUNET_YES (we should continue to iterate)
1516 clean_peer (void *cls,
1517 const GNUNET_HashCode * key,
1520 peer_disconnect_handler (NULL, (const struct GNUNET_PeerIdentity*) key);
1526 * Task run during shutdown.
1532 shutdown_task (void *cls,
1533 const struct GNUNET_SCHEDULER_TaskContext *tc)
1537 GNUNET_DATASTORE_cancel (mig_qe);
1540 if (GNUNET_SCHEDULER_NO_TASK != mig_task)
1542 GNUNET_SCHEDULER_cancel (sched, mig_task);
1543 mig_task = GNUNET_SCHEDULER_NO_TASK;
1545 while (client_list != NULL)
1546 handle_client_disconnect (NULL,
1547 client_list->client);
1548 cron_flush_trust (NULL, NULL);
1549 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1552 GNUNET_break (0 == GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap));
1553 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
1554 requests_by_expiration_heap = 0;
1555 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
1556 connected_peers = NULL;
1557 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (query_request_map));
1558 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
1559 query_request_map = NULL;
1560 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (peer_request_map));
1561 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
1562 peer_request_map = NULL;
1563 GNUNET_assert (NULL != core);
1564 GNUNET_CORE_disconnect (core);
1568 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1571 GNUNET_DATASTORE_disconnect (dsh,
1573 while (mig_head != NULL)
1574 delete_migration_block (mig_head);
1575 GNUNET_assert (0 == mig_size);
1579 GNUNET_free_non_null (trustDirectory);
1580 trustDirectory = NULL;
1584 /* ******************* Utility functions ******************** */
1588 * Transmit messages by copying it to the target buffer
1589 * "buf". "buf" will be NULL and "size" zero if the socket was closed
1590 * for writing in the meantime. In that case, do nothing
1591 * (the disconnect or shutdown handler will take care of the rest).
1592 * If we were able to transmit messages and there are still more
1593 * pending, ask core again for further calls to this function.
1595 * @param cls closure, pointer to the 'struct ConnectedPeer*'
1596 * @param size number of bytes available in buf
1597 * @param buf where the callee should write the message
1598 * @return number of bytes written to buf
1601 transmit_to_peer (void *cls,
1602 size_t size, void *buf)
1604 struct ConnectedPeer *cp = cls;
1606 struct GNUNET_PeerIdentity pid;
1607 struct PendingMessage *pm;
1608 struct MigrationReadyBlock *mb;
1609 struct MigrationReadyBlock *next;
1610 struct PutMessage migm;
1618 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1619 "Dropping message, core too busy.\n");
1624 while ( (NULL != (pm = cp->pending_messages_head) ) &&
1625 (pm->msize <= size) )
1627 memcpy (&cbuf[msize], &pm[1], pm->msize);
1630 destroy_pending_message (pm, cp->pid);
1634 GNUNET_PEER_resolve (cp->pid,
1636 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1638 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1647 while (NULL != (mb = next))
1650 for (i=0;i<MIGRATION_LIST_SIZE;i++)
1652 if ( (cp->pid == mb->target_list[i]) &&
1653 (mb->size + sizeof (migm) <= size) )
1655 GNUNET_PEER_change_rc (mb->target_list[i], -1);
1656 mb->target_list[i] = 0;
1658 migm.header.size = htons (sizeof (migm) + mb->size);
1659 migm.header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
1660 migm.type = htonl (mb->type);
1661 migm.expiration = GNUNET_TIME_absolute_hton (mb->expiration);
1662 memcpy (&cbuf[msize], &migm, sizeof (migm));
1663 msize += sizeof (migm);
1664 size -= sizeof (migm);
1665 memcpy (&cbuf[msize], &mb[1], mb->size);
1669 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1670 "Pushing migration block `%s' (%u bytes) to `%s'\n",
1671 GNUNET_h2s (&mb->query),
1680 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1681 "Migration block `%s' (%u bytes) is not on migration list for peer `%s'\n",
1682 GNUNET_h2s (&mb->query),
1688 if ( (mb->used_targets >= MIGRATION_TARGET_COUNT) ||
1689 (mb->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers)) )
1691 delete_migration_block (mb);
1692 consider_migration_gathering ();
1695 consider_migration (NULL,
1700 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1701 "Transmitting %u bytes to peer %u\n",
1710 * Add a message to the set of pending messages for the given peer.
1712 * @param cp peer to send message to
1713 * @param pm message to queue
1714 * @param pr request on which behalf this message is being queued
1717 add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
1718 struct PendingMessage *pm,
1719 struct PendingRequest *pr)
1721 struct PendingMessage *pos;
1722 struct PendingMessageList *pml;
1723 struct GNUNET_PeerIdentity pid;
1725 GNUNET_assert (pm->next == NULL);
1726 GNUNET_assert (pm->pml == NULL);
1727 pml = GNUNET_malloc (sizeof (struct PendingMessageList));
1732 GNUNET_CONTAINER_DLL_insert (pr->pending_head,
1735 pos = cp->pending_messages_head;
1736 while ( (pos != NULL) &&
1737 (pm->priority < pos->priority) )
1739 GNUNET_CONTAINER_DLL_insert_after (cp->pending_messages_head,
1740 cp->pending_messages_tail,
1743 cp->pending_requests++;
1744 if (cp->pending_requests > MAX_QUEUE_PER_PEER)
1745 destroy_pending_message (cp->pending_messages_tail, 0);
1746 GNUNET_PEER_resolve (cp->pid, &pid);
1747 if (NULL != cp->cth)
1748 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
1749 /* need to schedule transmission */
1750 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1751 cp->pending_messages_head->priority,
1754 cp->pending_messages_head->msize,
1757 if (cp->cth == NULL)
1760 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1761 "Failed to schedule transmission with core!\n");
1763 GNUNET_STATISTICS_update (stats,
1764 gettext_noop ("# CORE transmission failures"),
1772 * Mingle hash with the mingle_number to produce different bits.
1775 mingle_hash (const GNUNET_HashCode * in,
1776 int32_t mingle_number,
1777 GNUNET_HashCode * hc)
1781 GNUNET_CRYPTO_hash (&mingle_number,
1784 GNUNET_CRYPTO_hash_xor (&m, in, hc);
1789 * Test if the load on this peer is too high
1790 * to even consider processing the query at
1793 * @return GNUNET_YES if the load is too high to do anything, GNUNET_NO to forward (load high, but not too high), GNUNET_SYSERR to indirect (load low)
1796 test_load_too_high ()
1798 return GNUNET_SYSERR; // FIXME
1802 /* ******************* Pending Request Refresh Task ******************** */
1807 * We use a random delay to make the timing of requests less
1808 * predictable. This function returns such a random delay. We add a base
1809 * delay of MAX_CORK_DELAY (1s).
1811 * FIXME: make schedule dependent on the specifics of the request?
1812 * Or bandwidth and number of connected peers and load?
1814 * @return random delay to use for some request, between 1s and 1000+TTL_DECREMENT ms
1816 static struct GNUNET_TIME_Relative
1817 get_processing_delay ()
1820 GNUNET_TIME_relative_add (GNUNET_CONSTANTS_MAX_CORK_DELAY,
1821 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1822 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1828 * We're processing a GET request from another peer and have decided
1829 * to forward it to other peers. This function is called periodically
1830 * and should forward the request to other peers until we have all
1831 * possible replies. If we have transmitted the *only* reply to
1832 * the initiator we should destroy the pending request. If we have
1833 * many replies in the queue to the initiator, we should delay sending
1834 * out more queries until the reply queue has shrunk some.
1836 * @param cls our "struct ProcessGetContext *"
1840 forward_request_task (void *cls,
1841 const struct GNUNET_SCHEDULER_TaskContext *tc);
1845 * Function called after we either failed or succeeded
1846 * at transmitting a query to a peer.
1848 * @param cls the requests "struct PendingRequest*"
1849 * @param tpid ID of receiving peer, 0 on transmission error
1852 transmit_query_continuation (void *cls,
1853 GNUNET_PEER_Id tpid)
1855 struct PendingRequest *pr = cls;
1857 GNUNET_STATISTICS_update (stats,
1858 gettext_noop ("# queries scheduled for forwarding"),
1864 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1865 "Transmission of request failed, will try again later.\n");
1867 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1868 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1869 get_processing_delay (),
1870 &forward_request_task,
1874 GNUNET_STATISTICS_update (stats,
1875 gettext_noop ("# queries forwarded"),
1878 GNUNET_PEER_change_rc (tpid, 1);
1879 if (pr->used_pids_off == pr->used_pids_size)
1880 GNUNET_array_grow (pr->used_pids,
1882 pr->used_pids_size * 2 + 2);
1883 pr->used_pids[pr->used_pids_off++] = tpid;
1884 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1885 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1886 get_processing_delay (),
1887 &forward_request_task,
1893 * How many bytes should a bloomfilter be if we have already seen
1894 * entry_count responses? Note that BLOOMFILTER_K gives us the number
1895 * of bits set per entry. Furthermore, we should not re-size the
1896 * filter too often (to keep it cheap).
1898 * Since other peers will also add entries but not resize the filter,
1899 * we should generally pick a slightly larger size than what the
1900 * strict math would suggest.
1902 * @return must be a power of two and smaller or equal to 2^15.
1905 compute_bloomfilter_size (unsigned int entry_count)
1908 unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
1909 uint16_t max = 1 << 15;
1911 if (entry_count > max)
1914 while ((size < max) && (size < ideal))
1923 * Recalculate our bloom filter for filtering replies. This function
1924 * will create a new bloom filter from scratch, so it should only be
1925 * called if we have no bloomfilter at all (and hence can create a
1926 * fresh one of minimal size without problems) OR if our peer is the
1927 * initiator (in which case we may resize to larger than mimimum size).
1929 * @param pr request for which the BF is to be recomputed
1932 refresh_bloomfilter (struct PendingRequest *pr)
1936 GNUNET_HashCode mhash;
1938 nsize = compute_bloomfilter_size (pr->replies_seen_off);
1939 if (nsize == pr->bf_size)
1940 return; /* size not changed */
1942 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
1943 pr->bf_size = nsize;
1944 pr->mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
1945 pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1948 for (i=0;i<pr->replies_seen_off;i++)
1950 mingle_hash (&pr->replies_seen[i], pr->mingle, &mhash);
1951 GNUNET_CONTAINER_bloomfilter_add (pr->bf, &mhash);
1957 * Function called after we've tried to reserve a certain amount of
1958 * bandwidth for a reply. Check if we succeeded and if so send our
1961 * @param cls the requests "struct PendingRequest*"
1962 * @param peer identifies the peer
1963 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1964 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1965 * @param amount set to the amount that was actually reserved or unreserved
1966 * @param preference current traffic preference for the given peer
1969 target_reservation_cb (void *cls,
1971 GNUNET_PeerIdentity * peer,
1972 struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
1973 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1975 uint64_t preference)
1977 struct PendingRequest *pr = cls;
1978 struct ConnectedPeer *cp;
1979 struct PendingMessage *pm;
1980 struct GetMessage *gm;
1981 GNUNET_HashCode *ext;
1991 /* error in communication with core, try again later */
1992 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1993 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1994 get_processing_delay (),
1995 &forward_request_task,
1999 // (3) transmit, update ttl/priority
2000 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2004 /* Peer must have just left */
2006 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2007 "Selected peer disconnected!\n");
2009 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2010 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
2011 get_processing_delay (),
2012 &forward_request_task,
2016 no_route = GNUNET_NO;
2022 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2023 "Failed to reserve bandwidth for reply (got %d/%u bytes only)!\n",
2027 GNUNET_STATISTICS_update (stats,
2028 gettext_noop ("# reply bandwidth reservation requests failed"),
2031 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2032 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
2033 get_processing_delay (),
2034 &forward_request_task,
2036 return; /* this target round failed */
2038 /* FIXME: if we are "quite" busy, we may still want to skip
2039 this round; need more load detection code! */
2040 no_route = GNUNET_YES;
2043 GNUNET_STATISTICS_update (stats,
2044 gettext_noop ("# queries scheduled for forwarding"),
2047 /* build message and insert message into priority queue */
2049 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2050 "Forwarding request `%s' to `%4s'!\n",
2051 GNUNET_h2s (&pr->query),
2056 if (GNUNET_YES == no_route)
2058 bm |= GET_MESSAGE_BIT_RETURN_TO;
2061 if (pr->namespace != NULL)
2063 bm |= GET_MESSAGE_BIT_SKS_NAMESPACE;
2066 if (pr->target_pid != 0)
2068 bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
2071 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
2072 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
2073 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
2075 gm = (struct GetMessage*) &pm[1];
2076 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
2077 gm->header.size = htons (msize);
2078 gm->type = htonl (pr->type);
2079 pr->remaining_priority /= 2;
2080 gm->priority = htonl (pr->remaining_priority);
2081 gm->ttl = htonl (pr->ttl);
2082 gm->filter_mutator = htonl(pr->mingle);
2083 gm->hash_bitmap = htonl (bm);
2084 gm->query = pr->query;
2085 ext = (GNUNET_HashCode*) &gm[1];
2087 if (GNUNET_YES == no_route)
2088 GNUNET_PEER_resolve (pr->cp->pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
2089 if (pr->namespace != NULL)
2090 memcpy (&ext[k++], pr->namespace, sizeof (GNUNET_HashCode));
2091 if (pr->target_pid != 0)
2092 GNUNET_PEER_resolve (pr->target_pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
2093 bfdata = (char *) &ext[k];
2095 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
2098 pm->cont = &transmit_query_continuation;
2100 add_to_pending_messages_for_peer (cp, pm, pr);
2105 * Closure used for "target_peer_select_cb".
2107 struct PeerSelectionContext
2110 * The request for which we are selecting
2113 struct PendingRequest *pr;
2116 * Current "prime" target.
2118 struct GNUNET_PeerIdentity target;
2121 * How much do we like this target?
2123 double target_score;
2129 * Function called for each connected peer to determine
2130 * which one(s) would make good targets for forwarding.
2132 * @param cls closure (struct PeerSelectionContext)
2133 * @param key current key code (peer identity)
2134 * @param value value in the hash map (struct ConnectedPeer)
2135 * @return GNUNET_YES if we should continue to
2140 target_peer_select_cb (void *cls,
2141 const GNUNET_HashCode * key,
2144 struct PeerSelectionContext *psc = cls;
2145 struct ConnectedPeer *cp = value;
2146 struct PendingRequest *pr = psc->pr;
2151 /* 1) check that this peer is not the initiator */
2155 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2156 "Skipping initiator in forwarding selection\n");
2158 return GNUNET_YES; /* skip */
2161 /* 2) check if we have already (recently) forwarded to this peer */
2163 for (i=0;i<pr->used_pids_off;i++)
2164 if (pr->used_pids[i] == cp->pid)
2167 if (0 != GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2168 RETRY_PROBABILITY_INV))
2171 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2172 "NOT re-trying query that was previously transmitted %u times\n",
2173 (unsigned int) pr->used_pids_off);
2175 return GNUNET_YES; /* skip */
2180 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2181 "Re-trying query that was previously transmitted %u times to this peer\n",
2184 /* 3) calculate how much we'd like to forward to this peer,
2185 starting with a random value that is strong enough
2186 to at least give any peer a chance sometimes
2187 (compared to the other factors that come later) */
2188 /* 3a) count successful (recent) routes from cp for same source */
2191 score = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2192 P2P_SUCCESS_LIST_SIZE);
2193 for (i=0;i<P2P_SUCCESS_LIST_SIZE;i++)
2194 if (cp->last_p2p_replies[i] == pr->cp->pid)
2195 score += 1; /* likely successful based on hot path */
2199 score = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2200 CS2P_SUCCESS_LIST_SIZE);
2201 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
2202 if (cp->last_client_replies[i] == pr->client_request_list->client_list->client)
2203 score += 1; /* likely successful based on hot path */
2205 /* 3b) include latency */
2206 if (cp->avg_delay.value < 4 * TTL_DECREMENT)
2207 score += 1; /* likely fast based on latency */
2208 /* 3c) include priorities */
2209 if (cp->avg_priority <= pr->remaining_priority / 2.0)
2210 score += 1; /* likely successful based on priorities */
2211 /* 3d) penalize for queue size */
2212 score -= (2.0 * cp->pending_requests / (double) MAX_QUEUE_PER_PEER);
2213 /* 3e) include peer proximity */
2214 score -= (2.0 * (GNUNET_CRYPTO_hash_distance_u32 (key,
2215 &pr->query)) / (double) UINT32_MAX);
2216 /* store best-fit in closure */
2218 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2219 "Peer `%s' gets score %f for forwarding query, max is %f\n",
2224 score++; /* avoid zero */
2225 if (score > psc->target_score)
2227 psc->target_score = score;
2228 psc->target.hashPubKey = *key;
2235 * The priority level imposes a bound on the maximum
2236 * value for the ttl that can be requested.
2238 * @param ttl_in requested ttl
2239 * @param prio given priority
2240 * @return ttl_in if ttl_in is below the limit,
2241 * otherwise the ttl-limit for the given priority
2244 bound_ttl (int32_t ttl_in, uint32_t prio)
2246 unsigned long long allowed;
2250 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
2251 if (ttl_in > allowed)
2253 if (allowed >= (1 << 30))
2262 * We're processing a GET request and have decided
2263 * to forward it to other peers. This function is called periodically
2264 * and should forward the request to other peers until we have all
2265 * possible replies. If we have transmitted the *only* reply to
2266 * the initiator we should destroy the pending request. If we have
2267 * many replies in the queue to the initiator, we should delay sending
2268 * out more queries until the reply queue has shrunk some.
2270 * @param cls our "struct ProcessGetContext *"
2274 forward_request_task (void *cls,
2275 const struct GNUNET_SCHEDULER_TaskContext *tc)
2277 struct PendingRequest *pr = cls;
2278 struct PeerSelectionContext psc;
2279 struct ConnectedPeer *cp;
2280 struct GNUNET_TIME_Relative delay;
2282 pr->task = GNUNET_SCHEDULER_NO_TASK;
2283 if (pr->irc != NULL)
2286 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2287 "Forwarding of query `%s' not attempted due to pending local lookup!\n",
2288 GNUNET_h2s (&pr->query));
2290 return; /* already pending */
2292 if (GNUNET_YES == pr->local_only)
2293 return; /* configured to not do P2P search */
2294 /* (1) select target */
2296 psc.target_score = -DBL_MAX;
2297 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
2298 &target_peer_select_cb,
2300 if (psc.target_score == -DBL_MAX)
2302 delay = get_processing_delay ();
2304 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2305 "No peer selected for forwarding of query `%s', will try again in %llu ms!\n",
2306 GNUNET_h2s (&pr->query),
2309 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
2311 &forward_request_task,
2313 return; /* nobody selected */
2315 /* (3) update TTL/priority */
2316 if (pr->client_request_list != NULL)
2318 /* FIXME: use better algorithm!? */
2319 if (0 == GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2322 /* bound priority we use by priorities we see from other peers
2323 rounded up (must round up so that we can see non-zero
2324 priorities, but round up as little as possible to make it
2325 plausible that we forwarded another peers request) */
2326 if (pr->priority > current_priorities + 1.0)
2327 pr->priority = (uint32_t) current_priorities + 1.0;
2328 pr->ttl = bound_ttl (pr->ttl + TTL_DECREMENT * 2,
2331 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2332 "Trying query `%s' with priority %u and TTL %d.\n",
2333 GNUNET_h2s (&pr->query),
2339 /* (3) reserve reply bandwidth */
2340 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2341 &psc.target.hashPubKey);
2342 GNUNET_assert (NULL != cp);
2343 pr->irc = GNUNET_CORE_peer_change_preference (sched, cfg,
2345 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
2346 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
2349 &target_reservation_cb,
2351 cp->inc_preference = 0;
2355 /* **************************** P2P PUT Handling ************************ */
2359 * Function called after we either failed or succeeded
2360 * at transmitting a reply to a peer.
2362 * @param cls the requests "struct PendingRequest*"
2363 * @param tpid ID of receiving peer, 0 on transmission error
2366 transmit_reply_continuation (void *cls,
2367 GNUNET_PEER_Id tpid)
2369 struct PendingRequest *pr = cls;
2373 case GNUNET_BLOCK_TYPE_DBLOCK:
2374 case GNUNET_BLOCK_TYPE_IBLOCK:
2375 /* only one reply expected, done with the request! */
2376 destroy_pending_request (pr);
2378 case GNUNET_BLOCK_TYPE_ANY:
2379 case GNUNET_BLOCK_TYPE_KBLOCK:
2380 case GNUNET_BLOCK_TYPE_SBLOCK:
2390 * Transmit the given message by copying it to the target buffer
2391 * "buf". "buf" will be NULL and "size" zero if the socket was closed
2392 * for writing in the meantime. In that case, do nothing
2393 * (the disconnect or shutdown handler will take care of the rest).
2394 * If we were able to transmit messages and there are still more
2395 * pending, ask core again for further calls to this function.
2397 * @param cls closure, pointer to the 'struct ClientList*'
2398 * @param size number of bytes available in buf
2399 * @param buf where the callee should write the message
2400 * @return number of bytes written to buf
2403 transmit_to_client (void *cls,
2404 size_t size, void *buf)
2406 struct ClientList *cl = cls;
2408 struct ClientResponseMessage *creply;
2415 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2416 "Not sending reply, client communication problem.\n");
2421 while ( (NULL != (creply = cl->res_head) ) &&
2422 (creply->msize <= size) )
2424 memcpy (&cbuf[msize], &creply[1], creply->msize);
2425 msize += creply->msize;
2426 size -= creply->msize;
2427 GNUNET_CONTAINER_DLL_remove (cl->res_head,
2430 GNUNET_free (creply);
2433 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
2435 GNUNET_TIME_UNIT_FOREVER_REL,
2436 &transmit_to_client,
2439 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2440 "Transmitted %u bytes to client\n",
2441 (unsigned int) msize);
2448 * Closure for "process_reply" function.
2450 struct ProcessReplyClosure
2453 * The data for the reply.
2458 * Who gave us this reply? NULL for local host.
2460 struct ConnectedPeer *sender;
2463 * When the reply expires.
2465 struct GNUNET_TIME_Absolute expiration;
2473 * Namespace that this reply belongs to
2474 * (if it is of type SBLOCK).
2476 GNUNET_HashCode namespace;
2479 * Type of the block.
2481 enum GNUNET_BLOCK_Type type;
2484 * How much was this reply worth to us?
2489 * Did we finish processing the associated request?
2496 * We have received a reply; handle it!
2498 * @param cls response (struct ProcessReplyClosure)
2499 * @param key our query
2500 * @param value value in the hash map (info about the query)
2501 * @return GNUNET_YES (we should continue to iterate)
2504 process_reply (void *cls,
2505 const GNUNET_HashCode * key,
2508 struct ProcessReplyClosure *prq = cls;
2509 struct PendingRequest *pr = value;
2510 struct PendingMessage *reply;
2511 struct ClientResponseMessage *creply;
2512 struct ClientList *cl;
2513 struct PutMessage *pm;
2514 struct ConnectedPeer *cp;
2515 struct GNUNET_TIME_Relative cur_delay;
2516 GNUNET_HashCode chash;
2517 GNUNET_HashCode mhash;
2521 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2522 "Matched result (type %u) for query `%s' with pending request\n",
2523 (unsigned int) prq->type,
2526 GNUNET_STATISTICS_update (stats,
2527 gettext_noop ("# replies received and matched"),
2530 if (prq->sender != NULL)
2532 /* FIXME: should we be more precise here and not use
2533 "start_time" but a peer-specific time stamp? */
2534 cur_delay = GNUNET_TIME_absolute_get_duration (pr->start_time);
2535 prq->sender->avg_delay.value
2536 = (prq->sender->avg_delay.value *
2537 (RUNAVG_DELAY_N - 1) + cur_delay.value) / RUNAVG_DELAY_N;
2538 prq->sender->avg_priority
2539 = (prq->sender->avg_priority *
2540 (RUNAVG_DELAY_N - 1) + pr->priority) / (double) RUNAVG_DELAY_N;
2543 GNUNET_PEER_change_rc (prq->sender->last_p2p_replies
2544 [prq->sender->last_p2p_replies_woff % P2P_SUCCESS_LIST_SIZE],
2546 GNUNET_PEER_change_rc (pr->cp->pid, 1);
2547 prq->sender->last_p2p_replies
2548 [(prq->sender->last_p2p_replies_woff++) % P2P_SUCCESS_LIST_SIZE]
2553 if (NULL != prq->sender->last_client_replies
2554 [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE])
2555 GNUNET_SERVER_client_drop (prq->sender->last_client_replies
2556 [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE]);
2557 prq->sender->last_client_replies
2558 [(prq->sender->last_client_replies_woff++) % CS2P_SUCCESS_LIST_SIZE]
2559 = pr->client_request_list->client_list->client;
2560 GNUNET_SERVER_client_keep (pr->client_request_list->client_list->client);
2563 GNUNET_CRYPTO_hash (prq->data,
2568 case GNUNET_BLOCK_TYPE_DBLOCK:
2569 case GNUNET_BLOCK_TYPE_IBLOCK:
2570 /* only possible reply, stop requesting! */
2571 while (NULL != pr->pending_head)
2572 destroy_pending_message_list_entry (pr->pending_head);
2575 if (pr->client_request_list != NULL)
2576 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
2578 GNUNET_DATASTORE_cancel (pr->qe);
2581 pr->do_remove = GNUNET_YES;
2582 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
2584 GNUNET_SCHEDULER_cancel (sched,
2586 pr->task = GNUNET_SCHEDULER_NO_TASK;
2588 GNUNET_break (GNUNET_YES ==
2589 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
2593 case GNUNET_BLOCK_TYPE_SBLOCK:
2594 if (pr->namespace == NULL)
2599 if (0 != memcmp (pr->namespace,
2601 sizeof (GNUNET_HashCode)))
2603 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2604 _("Reply mismatched in terms of namespace. Discarded.\n"));
2605 return GNUNET_YES; /* wrong namespace */
2607 /* then: fall-through! */
2608 case GNUNET_BLOCK_TYPE_KBLOCK:
2609 case GNUNET_BLOCK_TYPE_NBLOCK:
2612 mingle_hash (&chash, pr->mingle, &mhash);
2613 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
2616 GNUNET_STATISTICS_update (stats,
2617 gettext_noop ("# duplicate replies discarded (bloomfilter)"),
2621 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2622 "Duplicate response `%s', discarding.\n",
2623 GNUNET_h2s (&mhash));
2625 return GNUNET_YES; /* duplicate */
2628 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2629 "New response `%s', adding to filter.\n",
2630 GNUNET_h2s (&mhash));
2633 if (pr->client_request_list != NULL)
2635 if (pr->replies_seen_size == pr->replies_seen_off)
2636 GNUNET_array_grow (pr->replies_seen,
2637 pr->replies_seen_size,
2638 pr->replies_seen_size * 2 + 4);
2639 pr->replies_seen[pr->replies_seen_off++] = chash;
2641 if ( (pr->bf == NULL) ||
2642 (pr->client_request_list != NULL) )
2643 refresh_bloomfilter (pr);
2644 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
2651 prq->priority += pr->remaining_priority;
2652 pr->remaining_priority = 0;
2653 if (NULL != pr->client_request_list)
2655 GNUNET_STATISTICS_update (stats,
2656 gettext_noop ("# replies received for local clients"),
2659 cl = pr->client_request_list->client_list;
2660 msize = sizeof (struct PutMessage) + prq->size;
2661 creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
2662 creply->msize = msize;
2663 creply->client_list = cl;
2664 GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
2668 pm = (struct PutMessage*) &creply[1];
2669 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2670 pm->header.size = htons (msize);
2671 pm->type = htonl (prq->type);
2672 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
2673 memcpy (&pm[1], prq->data, prq->size);
2677 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2678 "Transmitting result for query `%s' to client\n",
2681 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
2683 GNUNET_TIME_UNIT_FOREVER_REL,
2684 &transmit_to_client,
2687 GNUNET_break (cl->th != NULL);
2690 prq->finished = GNUNET_YES;
2691 destroy_pending_request (pr);
2698 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2699 "Transmitting result for query `%s' to other peer (PID=%u)\n",
2701 (unsigned int) cp->pid);
2703 GNUNET_STATISTICS_update (stats,
2704 gettext_noop ("# replies received for other peers"),
2707 msize = sizeof (struct PutMessage) + prq->size;
2708 reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
2709 reply->cont = &transmit_reply_continuation;
2710 reply->cont_cls = pr;
2711 reply->msize = msize;
2712 reply->priority = UINT32_MAX; /* send replies first! */
2713 pm = (struct PutMessage*) &reply[1];
2714 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2715 pm->header.size = htons (msize);
2716 pm->type = htonl (prq->type);
2717 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
2718 memcpy (&pm[1], prq->data, prq->size);
2719 add_to_pending_messages_for_peer (cp, reply, pr);
2726 * Continuation called to notify client about result of the
2729 * @param cls closure
2730 * @param success GNUNET_SYSERR on failure
2731 * @param msg NULL on success, otherwise an error message
2734 put_migration_continuation (void *cls,
2743 * Handle P2P "PUT" message.
2745 * @param cls closure, always NULL
2746 * @param other the other peer involved (sender or receiver, NULL
2747 * for loopback messages where we are both sender and receiver)
2748 * @param message the actual message
2749 * @param latency reported latency of the connection with 'other'
2750 * @param distance reported distance (DV) to 'other'
2751 * @return GNUNET_OK to keep the connection open,
2752 * GNUNET_SYSERR to close it (signal serious error)
2755 handle_p2p_put (void *cls,
2756 const struct GNUNET_PeerIdentity *other,
2757 const struct GNUNET_MessageHeader *message,
2758 struct GNUNET_TIME_Relative latency,
2761 const struct PutMessage *put;
2764 enum GNUNET_BLOCK_Type type;
2765 struct GNUNET_TIME_Absolute expiration;
2766 GNUNET_HashCode query;
2767 struct ProcessReplyClosure prq;
2768 const struct SBlock *sb;
2770 msize = ntohs (message->size);
2771 if (msize < sizeof (struct PutMessage))
2774 return GNUNET_SYSERR;
2776 put = (const struct PutMessage*) message;
2777 dsize = msize - sizeof (struct PutMessage);
2778 type = ntohl (put->type);
2779 expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
2782 GNUNET_BLOCK_check_block (type,
2787 GNUNET_break_op (0);
2788 return GNUNET_SYSERR;
2790 if (type == GNUNET_BLOCK_TYPE_ONDEMAND)
2791 return GNUNET_SYSERR;
2792 if (GNUNET_BLOCK_TYPE_SBLOCK == type)
2794 sb = (const struct SBlock*) &put[1];
2795 GNUNET_CRYPTO_hash (&sb->subspace,
2796 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2801 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2802 "Received result for query `%s' from peer `%4s'\n",
2803 GNUNET_h2s (&query),
2804 GNUNET_i2s (other));
2806 GNUNET_STATISTICS_update (stats,
2807 gettext_noop ("# replies received (overall)"),
2810 /* now, lookup 'query' */
2811 prq.data = (const void*) &put[1];
2813 prq.sender = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2814 &other->hashPubKey);
2819 prq.expiration = expiration;
2821 prq.finished = GNUNET_NO;
2822 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2826 if (prq.sender != NULL)
2828 prq.sender->inc_preference += CONTENT_BANDWIDTH_VALUE + 1000 * prq.priority;
2829 prq.sender->trust += prq.priority;
2831 if (GNUNET_YES == active_migration)
2834 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2835 "Replicating result for query `%s' with priority %u\n",
2836 GNUNET_h2s (&query),
2839 GNUNET_DATASTORE_put (dsh,
2840 0, &query, dsize, &put[1],
2841 type, prq.priority, 1 /* anonymity */,
2843 1 + prq.priority, MAX_DATASTORE_QUEUE,
2844 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
2845 &put_migration_continuation,
2852 /* **************************** P2P GET Handling ************************ */
2856 * Closure for 'check_duplicate_request_{peer,client}'.
2858 struct CheckDuplicateRequestClosure
2861 * The new request we should check if it already exists.
2863 const struct PendingRequest *pr;
2866 * Existing request found by the checker, NULL if none.
2868 struct PendingRequest *have;
2873 * Iterator over entries in the 'query_request_map' that
2874 * tries to see if we have the same request pending from
2875 * the same client already.
2877 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
2878 * @param key current key code (query, ignored, must match)
2879 * @param value value in the hash map (a 'struct PendingRequest'
2880 * that already exists)
2881 * @return GNUNET_YES if we should continue to
2882 * iterate (no match yet)
2883 * GNUNET_NO if not (match found).
2886 check_duplicate_request_client (void *cls,
2887 const GNUNET_HashCode * key,
2890 struct CheckDuplicateRequestClosure *cdc = cls;
2891 struct PendingRequest *have = value;
2893 if (have->client_request_list == NULL)
2895 if ( (cdc->pr->client_request_list->client_list->client == have->client_request_list->client_list->client) &&
2906 * We're processing (local) results for a search request
2907 * from another peer. Pass applicable results to the
2908 * peer and if we are done either clean up (operation
2909 * complete) or forward to other peers (more results possible).
2911 * @param cls our closure (struct LocalGetContext)
2912 * @param key key for the content
2913 * @param size number of bytes in data
2914 * @param data content stored
2915 * @param type type of the content
2916 * @param priority priority of the content
2917 * @param anonymity anonymity-level for the content
2918 * @param expiration expiration time for the content
2919 * @param uid unique identifier for the datum;
2920 * maybe 0 if no unique identifier is available
2923 process_local_reply (void *cls,
2924 const GNUNET_HashCode * key,
2927 enum GNUNET_BLOCK_Type type,
2930 struct GNUNET_TIME_Absolute
2934 struct PendingRequest *pr = cls;
2935 struct ProcessReplyClosure prq;
2936 struct CheckDuplicateRequestClosure cdrc;
2937 const struct SBlock *sb;
2938 GNUNET_HashCode dhash;
2939 GNUNET_HashCode mhash;
2940 GNUNET_HashCode query;
2945 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2946 "Done processing local replies, forwarding request to other peers.\n");
2949 if (pr->client_request_list != NULL)
2951 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
2953 /* Figure out if this is a duplicate request and possibly
2954 merge 'struct PendingRequest' entries */
2957 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2959 &check_duplicate_request_client,
2961 if (cdrc.have != NULL)
2964 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2965 "Received request for block `%s' twice from client, will only request once.\n",
2966 GNUNET_h2s (&pr->query));
2969 destroy_pending_request (pr);
2974 /* no more results */
2975 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2976 pr->task = GNUNET_SCHEDULER_add_now (sched,
2977 &forward_request_task,
2982 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2983 "New local response to `%s' of type %u.\n",
2987 if (type == GNUNET_BLOCK_TYPE_ONDEMAND)
2990 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2991 "Found ONDEMAND block, performing on-demand encoding\n");
2993 GNUNET_STATISTICS_update (stats,
2994 gettext_noop ("# on-demand blocks matched requests"),
2998 GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
2999 anonymity, expiration, uid,
3000 &process_local_reply,
3003 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3006 /* check for duplicates */
3007 GNUNET_CRYPTO_hash (data, size, &dhash);
3008 mingle_hash (&dhash,
3011 if ( (pr->bf != NULL) &&
3013 GNUNET_CONTAINER_bloomfilter_test (pr->bf,
3017 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3018 "Result from datastore filtered by bloomfilter (duplicate).\n");
3020 GNUNET_STATISTICS_update (stats,
3021 gettext_noop ("# results filtered by query bloomfilter"),
3025 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3029 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3030 "Found result for query `%s' in local datastore\n",
3033 GNUNET_STATISTICS_update (stats,
3034 gettext_noop ("# results found locally"),
3037 pr->results_found++;
3038 memset (&prq, 0, sizeof (prq));
3040 prq.expiration = expiration;
3042 if (GNUNET_BLOCK_TYPE_SBLOCK == type)
3044 sb = (const struct SBlock*) data;
3045 GNUNET_CRYPTO_hash (&sb->subspace,
3046 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3049 if (GNUNET_OK != GNUNET_BLOCK_check_block (type,
3055 GNUNET_DATASTORE_remove (dsh,
3059 GNUNET_TIME_UNIT_FOREVER_REL,
3061 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3065 prq.priority = priority;
3066 prq.finished = GNUNET_NO;
3067 process_reply (&prq, key, pr);
3068 if (prq.finished == GNUNET_YES)
3071 return; /* done here */
3072 if ( (type == GNUNET_BLOCK_TYPE_DBLOCK) ||
3073 (type == GNUNET_BLOCK_TYPE_IBLOCK) )
3075 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
3078 if ( (pr->client_request_list == NULL) &&
3079 ( (GNUNET_YES == test_load_too_high()) ||
3080 (pr->results_found > 5 + 2 * pr->priority) ) )
3083 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3084 "Load too high, done with request\n");
3086 GNUNET_STATISTICS_update (stats,
3087 gettext_noop ("# processing result set cut short due to load"),
3090 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
3093 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3098 * We've received a request with the specified priority. Bound it
3099 * according to how much we trust the given peer.
3101 * @param prio_in requested priority
3102 * @param cp the peer making the request
3103 * @return effective priority
3106 bound_priority (uint32_t prio_in,
3107 struct ConnectedPeer *cp)
3109 #define N ((double)128.0)
3114 ld = test_load_too_high ();
3115 if (ld == GNUNET_SYSERR)
3116 return 0; /* excess resources */
3117 ret = change_host_trust (cp, prio_in);
3120 if (ret > current_priorities + N)
3121 rret = current_priorities + N;
3125 = (current_priorities * (N-1) + rret)/N;
3133 * Iterator over entries in the 'query_request_map' that
3134 * tries to see if we have the same request pending from
3135 * the same peer already.
3137 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
3138 * @param key current key code (query, ignored, must match)
3139 * @param value value in the hash map (a 'struct PendingRequest'
3140 * that already exists)
3141 * @return GNUNET_YES if we should continue to
3142 * iterate (no match yet)
3143 * GNUNET_NO if not (match found).
3146 check_duplicate_request_peer (void *cls,
3147 const GNUNET_HashCode * key,
3150 struct CheckDuplicateRequestClosure *cdc = cls;
3151 struct PendingRequest *have = value;
3153 if (cdc->pr->target_pid == have->target_pid)
3163 * Handle P2P "GET" request.
3165 * @param cls closure, always NULL
3166 * @param other the other peer involved (sender or receiver, NULL
3167 * for loopback messages where we are both sender and receiver)
3168 * @param message the actual message
3169 * @param latency reported latency of the connection with 'other'
3170 * @param distance reported distance (DV) to 'other'
3171 * @return GNUNET_OK to keep the connection open,
3172 * GNUNET_SYSERR to close it (signal serious error)
3175 handle_p2p_get (void *cls,
3176 const struct GNUNET_PeerIdentity *other,
3177 const struct GNUNET_MessageHeader *message,
3178 struct GNUNET_TIME_Relative latency,
3181 struct PendingRequest *pr;
3182 struct ConnectedPeer *cp;
3183 struct ConnectedPeer *cps;
3184 struct CheckDuplicateRequestClosure cdc;
3185 struct GNUNET_TIME_Relative timeout;
3187 const struct GetMessage *gm;
3189 const GNUNET_HashCode *opt;
3192 uint32_t ttl_decrement;
3193 enum GNUNET_BLOCK_Type type;
3197 msize = ntohs(message->size);
3198 if (msize < sizeof (struct GetMessage))
3200 GNUNET_break_op (0);
3201 return GNUNET_SYSERR;
3203 gm = (const struct GetMessage*) message;
3204 type = ntohl (gm->type);
3207 case GNUNET_BLOCK_TYPE_ANY:
3208 case GNUNET_BLOCK_TYPE_DBLOCK:
3209 case GNUNET_BLOCK_TYPE_IBLOCK:
3210 case GNUNET_BLOCK_TYPE_KBLOCK:
3211 case GNUNET_BLOCK_TYPE_SBLOCK:
3214 GNUNET_break_op (0);
3215 return GNUNET_SYSERR;
3217 bm = ntohl (gm->hash_bitmap);
3225 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
3227 GNUNET_break_op (0);
3228 return GNUNET_SYSERR;
3230 opt = (const GNUNET_HashCode*) &gm[1];
3231 bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
3232 bm = ntohl (gm->hash_bitmap);
3233 if ( (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)) &&
3234 (type != GNUNET_BLOCK_TYPE_SBLOCK) )
3236 GNUNET_break_op (0);
3237 return GNUNET_SYSERR;
3240 cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3241 &other->hashPubKey);
3244 /* peer must have just disconnected */
3245 GNUNET_STATISTICS_update (stats,
3246 gettext_noop ("# requests dropped due to initiator not being connected"),
3249 return GNUNET_SYSERR;
3251 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
3252 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3259 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
3260 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3261 "Failed to find RETURN-TO peer `%4s' in connection set. Dropping query.\n",
3262 GNUNET_i2s ((const struct GNUNET_PeerIdentity*) &opt[bits-1]));
3265 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3266 "Failed to find peer `%4s' in connection set. Dropping query.\n",
3267 GNUNET_i2s (other));
3269 GNUNET_STATISTICS_update (stats,
3270 gettext_noop ("# requests dropped due to missing reverse route"),
3273 /* FIXME: try connect? */
3276 /* note that we can really only check load here since otherwise
3277 peers could find out that we are overloaded by not being
3278 disconnected after sending us a malformed query... */
3280 /* FIXME: query priority should play
3281 a major role here! */
3282 ld = test_load_too_high ();
3283 if (GNUNET_YES == ld)
3286 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3287 "Dropping query from `%s', this peer is too busy.\n",
3288 GNUNET_i2s (other));
3290 GNUNET_STATISTICS_update (stats,
3291 gettext_noop ("# requests dropped due to high load"),
3296 /* FIXME: if ld == GNUNET_NO, forward
3297 instead of indirecting! */
3300 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3301 "Received request for `%s' of type %u from peer `%4s' with flags %u\n",
3302 GNUNET_h2s (&gm->query),
3303 (unsigned int) type,
3307 have_ns = (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE));
3308 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
3309 (have_ns ? sizeof(GNUNET_HashCode) : 0));
3312 pr->namespace = (GNUNET_HashCode*) &pr[1];
3313 memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
3316 pr->mingle = ntohl (gm->filter_mutator);
3317 if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
3318 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
3320 pr->anonymity_level = 1;
3321 pr->priority = bound_priority (ntohl (gm->priority), cps);
3322 pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
3323 pr->query = gm->query;
3324 /* decrement ttl (always) */
3325 ttl_decrement = 2 * TTL_DECREMENT +
3326 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3328 if ( (pr->ttl < 0) &&
3329 (((int32_t)(pr->ttl - ttl_decrement)) > 0) )
3332 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3333 "Dropping query from `%s' due to TTL underflow (%d - %u).\n",
3338 GNUNET_STATISTICS_update (stats,
3339 gettext_noop ("# requests dropped due TTL underflow"),
3342 /* integer underflow => drop (should be very rare)! */
3346 pr->ttl -= ttl_decrement;
3347 pr->start_time = GNUNET_TIME_absolute_get ();
3349 /* get bloom filter */
3352 pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
3355 pr->bf_size = bfsize;
3360 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
3362 &check_duplicate_request_peer,
3364 if (cdc.have != NULL)
3366 if (cdc.have->start_time.value + cdc.have->ttl >=
3367 pr->start_time.value + pr->ttl)
3369 /* existing request has higher TTL, drop new one! */
3370 cdc.have->priority += pr->priority;
3371 destroy_pending_request (pr);
3373 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3374 "Have existing request with higher TTL, dropping new request.\n",
3375 GNUNET_i2s (other));
3377 GNUNET_STATISTICS_update (stats,
3378 gettext_noop ("# requests dropped due to higher-TTL request"),
3385 /* existing request has lower TTL, drop old one! */
3386 pr->priority += cdc.have->priority;
3387 /* Possible optimization: if we have applicable pending
3388 replies in 'cdc.have', we might want to move those over
3389 (this is a really rare special-case, so it is not clear
3390 that this would be worth it) */
3391 destroy_pending_request (cdc.have);
3392 /* keep processing 'pr'! */
3397 GNUNET_break (GNUNET_OK ==
3398 GNUNET_CONTAINER_multihashmap_put (query_request_map,
3401 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
3402 GNUNET_break (GNUNET_OK ==
3403 GNUNET_CONTAINER_multihashmap_put (peer_request_map,
3406 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
3408 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
3410 pr->start_time.value + pr->ttl);
3412 GNUNET_STATISTICS_update (stats,
3413 gettext_noop ("# P2P searches received"),
3416 GNUNET_STATISTICS_update (stats,
3417 gettext_noop ("# P2P searches active"),
3421 /* calculate change in traffic preference */
3422 cps->inc_preference += pr->priority * 1000 + QUERY_BANDWIDTH_VALUE;
3423 /* process locally */
3424 if (type == GNUNET_BLOCK_TYPE_DBLOCK)
3425 type = GNUNET_BLOCK_TYPE_ANY; /* to get on-demand as well */
3426 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
3427 (pr->priority + 1));
3428 pr->qe = GNUNET_DATASTORE_get (dsh,
3432 MAX_DATASTORE_QUEUE,
3434 &process_local_reply,
3437 /* Are multiple results possible? If so, start processing remotely now! */
3440 case GNUNET_BLOCK_TYPE_DBLOCK:
3441 case GNUNET_BLOCK_TYPE_IBLOCK:
3442 /* only one result, wait for datastore */
3445 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
3446 pr->task = GNUNET_SCHEDULER_add_now (sched,
3447 &forward_request_task,
3451 /* make sure we don't track too many requests */
3452 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
3454 pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
3455 destroy_pending_request (pr);
3461 /* **************************** CS GET Handling ************************ */
3465 * Handle START_SEARCH-message (search request from client).
3467 * @param cls closure
3468 * @param client identification of the client
3469 * @param message the actual message
3472 handle_start_search (void *cls,
3473 struct GNUNET_SERVER_Client *client,
3474 const struct GNUNET_MessageHeader *message)
3476 static GNUNET_HashCode all_zeros;
3477 const struct SearchMessage *sm;
3478 struct ClientList *cl;
3479 struct ClientRequestList *crl;
3480 struct PendingRequest *pr;
3483 enum GNUNET_BLOCK_Type type;
3485 msize = ntohs (message->size);
3486 if ( (msize < sizeof (struct SearchMessage)) ||
3487 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
3490 GNUNET_SERVER_receive_done (client,
3494 GNUNET_STATISTICS_update (stats,
3495 gettext_noop ("# client searches received"),
3498 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
3499 sm = (const struct SearchMessage*) message;
3500 type = ntohl (sm->type);
3502 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3503 "Received request for `%s' of type %u from local client\n",
3504 GNUNET_h2s (&sm->query),
3505 (unsigned int) type);
3509 case GNUNET_BLOCK_TYPE_ANY:
3510 case GNUNET_BLOCK_TYPE_DBLOCK:
3511 case GNUNET_BLOCK_TYPE_IBLOCK:
3512 case GNUNET_BLOCK_TYPE_KBLOCK:
3513 case GNUNET_BLOCK_TYPE_SBLOCK:
3514 case GNUNET_BLOCK_TYPE_NBLOCK:
3518 GNUNET_SERVER_receive_done (client,
3524 while ( (cl != NULL) &&
3525 (cl->client != client) )
3529 cl = GNUNET_malloc (sizeof (struct ClientList));
3530 cl->client = client;
3531 GNUNET_SERVER_client_keep (client);
3532 cl->next = client_list;
3535 /* detect duplicate KBLOCK requests */
3536 if ( (type == GNUNET_BLOCK_TYPE_KBLOCK) ||
3537 (type == GNUNET_BLOCK_TYPE_NBLOCK) ||
3538 (type == GNUNET_BLOCK_TYPE_ANY) )
3541 while ( (crl != NULL) &&
3542 ( (0 != memcmp (&crl->req->query,
3544 sizeof (GNUNET_HashCode))) ||
3545 (crl->req->type != type) ) )
3550 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3551 "Have existing request, merging content-seen lists.\n");
3554 /* Duplicate request (used to send long list of
3555 known/blocked results); merge 'pr->replies_seen'
3556 and update bloom filter */
3557 GNUNET_array_grow (pr->replies_seen,
3558 pr->replies_seen_size,
3559 pr->replies_seen_off + sc);
3560 memcpy (&pr->replies_seen[pr->replies_seen_off],
3562 sc * sizeof (GNUNET_HashCode));
3563 pr->replies_seen_off += sc;
3564 refresh_bloomfilter (pr);
3565 GNUNET_STATISTICS_update (stats,
3566 gettext_noop ("# client searches updated (merged content seen list)"),
3569 GNUNET_SERVER_receive_done (client,
3574 GNUNET_STATISTICS_update (stats,
3575 gettext_noop ("# client searches active"),
3578 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
3579 ((type == GNUNET_BLOCK_TYPE_SBLOCK) ? sizeof(GNUNET_HashCode) : 0));
3580 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
3581 memset (crl, 0, sizeof (struct ClientRequestList));
3582 crl->client_list = cl;
3583 GNUNET_CONTAINER_DLL_insert (cl->rl_head,
3588 pr->client_request_list = crl;
3589 GNUNET_array_grow (pr->replies_seen,
3590 pr->replies_seen_size,
3592 memcpy (pr->replies_seen,
3594 sc * sizeof (GNUNET_HashCode));
3595 pr->replies_seen_off = sc;
3596 pr->anonymity_level = ntohl (sm->anonymity_level);
3597 refresh_bloomfilter (pr);
3598 pr->query = sm->query;
3599 if (0 == (1 & ntohl (sm->options)))
3600 pr->local_only = GNUNET_NO;
3602 pr->local_only = GNUNET_YES;
3605 case GNUNET_BLOCK_TYPE_DBLOCK:
3606 case GNUNET_BLOCK_TYPE_IBLOCK:
3607 if (0 != memcmp (&sm->target,
3609 sizeof (GNUNET_HashCode)))
3610 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
3612 case GNUNET_BLOCK_TYPE_SBLOCK:
3613 pr->namespace = (GNUNET_HashCode*) &pr[1];
3614 memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
3619 GNUNET_break (GNUNET_OK ==
3620 GNUNET_CONTAINER_multihashmap_put (query_request_map,
3623 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
3624 if (type == GNUNET_BLOCK_TYPE_DBLOCK)
3625 type = GNUNET_BLOCK_TYPE_ANY; /* get on-demand blocks too! */
3626 pr->qe = GNUNET_DATASTORE_get (dsh,
3630 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
3631 &process_local_reply,
3636 /* **************************** Startup ************************ */
3639 * Process fs requests.
3641 * @param s scheduler to use
3642 * @param server the initialized server
3643 * @param c configuration to use
3646 main_init (struct GNUNET_SCHEDULER_Handle *s,
3647 struct GNUNET_SERVER_Handle *server,
3648 const struct GNUNET_CONFIGURATION_Handle *c)
3650 static const struct GNUNET_CORE_MessageHandler p2p_handlers[] =
3653 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
3655 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
3658 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
3659 {&GNUNET_FS_handle_index_start, NULL,
3660 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
3661 {&GNUNET_FS_handle_index_list_get, NULL,
3662 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
3663 {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
3664 sizeof (struct UnindexMessage) },
3665 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
3672 stats = GNUNET_STATISTICS_create (sched, "fs", cfg);
3673 min_migration_delay = GNUNET_TIME_UNIT_SECONDS; // FIXME: get from config
3674 connected_peers = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3675 query_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3676 peer_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3677 requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
3678 core = GNUNET_CORE_connect (sched,
3680 GNUNET_TIME_UNIT_FOREVER_REL,
3683 &peer_connect_handler,
3684 &peer_disconnect_handler,
3691 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3692 _("Failed to connect to `%s' service.\n"),
3694 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
3695 connected_peers = NULL;
3696 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
3697 query_request_map = NULL;
3698 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
3699 requests_by_expiration_heap = NULL;
3700 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
3701 peer_request_map = NULL;
3704 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
3707 return GNUNET_SYSERR;
3709 /* FIXME: distinguish between sending and storing in options? */
3710 if (active_migration)
3712 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3713 _("Content migration is enabled, will start to gather data\n"));
3714 consider_migration_gathering ();
3716 GNUNET_SERVER_disconnect_notify (server,
3717 &handle_client_disconnect,
3719 GNUNET_assert (GNUNET_OK ==
3720 GNUNET_CONFIGURATION_get_value_filename (cfg,
3724 GNUNET_DISK_directory_create (trustDirectory);
3725 GNUNET_SCHEDULER_add_with_priority (sched,
3726 GNUNET_SCHEDULER_PRIORITY_HIGH,
3727 &cron_flush_trust, NULL);
3730 GNUNET_SERVER_add_handlers (server, handlers);
3731 GNUNET_SCHEDULER_add_delayed (sched,
3732 GNUNET_TIME_UNIT_FOREVER_REL,
3740 * Process fs requests.
3742 * @param cls closure
3743 * @param sched scheduler to use
3744 * @param server the initialized server
3745 * @param cfg configuration to use
3749 struct GNUNET_SCHEDULER_Handle *sched,
3750 struct GNUNET_SERVER_Handle *server,
3751 const struct GNUNET_CONFIGURATION_Handle *cfg)
3753 active_migration = GNUNET_CONFIGURATION_get_value_yesno (cfg,
3756 dsh = GNUNET_DATASTORE_connect (cfg,
3760 GNUNET_SCHEDULER_shutdown (sched);
3763 if ( (GNUNET_OK != GNUNET_FS_indexing_init (sched, cfg, dsh)) ||
3764 (GNUNET_OK != main_init (sched, server, cfg)) )
3766 GNUNET_SCHEDULER_shutdown (sched);
3767 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
3775 * The main function for the fs service.
3777 * @param argc number of arguments from the command line
3778 * @param argv command line arguments
3779 * @return 0 ok, 1 on error
3782 main (int argc, char *const *argv)
3784 return (GNUNET_OK ==
3785 GNUNET_SERVICE_run (argc,
3788 GNUNET_SERVICE_OPTION_NONE,
3789 &run, NULL)) ? 0 : 1;
3792 /* end of gnunet-service-fs.c */