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 /* 4) super-bonus for being the known target */
2217 if (pr->target_pid == cp->pid)
2219 /* store best-fit in closure */
2221 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2222 "Peer `%s' gets score %f for forwarding query, max is %f\n",
2227 score++; /* avoid zero */
2228 if (score > psc->target_score)
2230 psc->target_score = score;
2231 psc->target.hashPubKey = *key;
2238 * The priority level imposes a bound on the maximum
2239 * value for the ttl that can be requested.
2241 * @param ttl_in requested ttl
2242 * @param prio given priority
2243 * @return ttl_in if ttl_in is below the limit,
2244 * otherwise the ttl-limit for the given priority
2247 bound_ttl (int32_t ttl_in, uint32_t prio)
2249 unsigned long long allowed;
2253 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
2254 if (ttl_in > allowed)
2256 if (allowed >= (1 << 30))
2265 * We're processing a GET request and have decided
2266 * to forward it to other peers. This function is called periodically
2267 * and should forward the request to other peers until we have all
2268 * possible replies. If we have transmitted the *only* reply to
2269 * the initiator we should destroy the pending request. If we have
2270 * many replies in the queue to the initiator, we should delay sending
2271 * out more queries until the reply queue has shrunk some.
2273 * @param cls our "struct ProcessGetContext *"
2277 forward_request_task (void *cls,
2278 const struct GNUNET_SCHEDULER_TaskContext *tc)
2280 struct PendingRequest *pr = cls;
2281 struct PeerSelectionContext psc;
2282 struct ConnectedPeer *cp;
2283 struct GNUNET_TIME_Relative delay;
2285 pr->task = GNUNET_SCHEDULER_NO_TASK;
2286 if (pr->irc != NULL)
2289 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2290 "Forwarding of query `%s' not attempted due to pending local lookup!\n",
2291 GNUNET_h2s (&pr->query));
2293 return; /* already pending */
2295 if (GNUNET_YES == pr->local_only)
2296 return; /* configured to not do P2P search */
2297 /* (1) select target */
2299 psc.target_score = -DBL_MAX;
2300 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
2301 &target_peer_select_cb,
2303 if (psc.target_score == -DBL_MAX)
2305 delay = get_processing_delay ();
2307 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2308 "No peer selected for forwarding of query `%s', will try again in %llu ms!\n",
2309 GNUNET_h2s (&pr->query),
2312 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
2314 &forward_request_task,
2316 return; /* nobody selected */
2318 /* (3) update TTL/priority */
2319 if (pr->client_request_list != NULL)
2321 /* FIXME: use better algorithm!? */
2322 if (0 == GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2325 /* bound priority we use by priorities we see from other peers
2326 rounded up (must round up so that we can see non-zero
2327 priorities, but round up as little as possible to make it
2328 plausible that we forwarded another peers request) */
2329 if (pr->priority > current_priorities + 1.0)
2330 pr->priority = (uint32_t) current_priorities + 1.0;
2331 pr->ttl = bound_ttl (pr->ttl + TTL_DECREMENT * 2,
2334 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2335 "Trying query `%s' with priority %u and TTL %d.\n",
2336 GNUNET_h2s (&pr->query),
2342 /* (3) reserve reply bandwidth */
2343 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2344 &psc.target.hashPubKey);
2345 GNUNET_assert (NULL != cp);
2346 pr->irc = GNUNET_CORE_peer_change_preference (sched, cfg,
2348 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
2349 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
2352 &target_reservation_cb,
2354 cp->inc_preference = 0;
2358 /* **************************** P2P PUT Handling ************************ */
2362 * Function called after we either failed or succeeded
2363 * at transmitting a reply to a peer.
2365 * @param cls the requests "struct PendingRequest*"
2366 * @param tpid ID of receiving peer, 0 on transmission error
2369 transmit_reply_continuation (void *cls,
2370 GNUNET_PEER_Id tpid)
2372 struct PendingRequest *pr = cls;
2376 case GNUNET_BLOCK_TYPE_DBLOCK:
2377 case GNUNET_BLOCK_TYPE_IBLOCK:
2378 /* only one reply expected, done with the request! */
2379 destroy_pending_request (pr);
2381 case GNUNET_BLOCK_TYPE_ANY:
2382 case GNUNET_BLOCK_TYPE_KBLOCK:
2383 case GNUNET_BLOCK_TYPE_SBLOCK:
2393 * Transmit the given message by copying it to the target buffer
2394 * "buf". "buf" will be NULL and "size" zero if the socket was closed
2395 * for writing in the meantime. In that case, do nothing
2396 * (the disconnect or shutdown handler will take care of the rest).
2397 * If we were able to transmit messages and there are still more
2398 * pending, ask core again for further calls to this function.
2400 * @param cls closure, pointer to the 'struct ClientList*'
2401 * @param size number of bytes available in buf
2402 * @param buf where the callee should write the message
2403 * @return number of bytes written to buf
2406 transmit_to_client (void *cls,
2407 size_t size, void *buf)
2409 struct ClientList *cl = cls;
2411 struct ClientResponseMessage *creply;
2418 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2419 "Not sending reply, client communication problem.\n");
2424 while ( (NULL != (creply = cl->res_head) ) &&
2425 (creply->msize <= size) )
2427 memcpy (&cbuf[msize], &creply[1], creply->msize);
2428 msize += creply->msize;
2429 size -= creply->msize;
2430 GNUNET_CONTAINER_DLL_remove (cl->res_head,
2433 GNUNET_free (creply);
2436 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
2438 GNUNET_TIME_UNIT_FOREVER_REL,
2439 &transmit_to_client,
2442 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2443 "Transmitted %u bytes to client\n",
2444 (unsigned int) msize);
2451 * Closure for "process_reply" function.
2453 struct ProcessReplyClosure
2456 * The data for the reply.
2461 * Who gave us this reply? NULL for local host.
2463 struct ConnectedPeer *sender;
2466 * When the reply expires.
2468 struct GNUNET_TIME_Absolute expiration;
2476 * Namespace that this reply belongs to
2477 * (if it is of type SBLOCK).
2479 GNUNET_HashCode namespace;
2482 * Type of the block.
2484 enum GNUNET_BLOCK_Type type;
2487 * How much was this reply worth to us?
2492 * Did we finish processing the associated request?
2499 * We have received a reply; handle it!
2501 * @param cls response (struct ProcessReplyClosure)
2502 * @param key our query
2503 * @param value value in the hash map (info about the query)
2504 * @return GNUNET_YES (we should continue to iterate)
2507 process_reply (void *cls,
2508 const GNUNET_HashCode * key,
2511 struct ProcessReplyClosure *prq = cls;
2512 struct PendingRequest *pr = value;
2513 struct PendingMessage *reply;
2514 struct ClientResponseMessage *creply;
2515 struct ClientList *cl;
2516 struct PutMessage *pm;
2517 struct ConnectedPeer *cp;
2518 struct GNUNET_TIME_Relative cur_delay;
2519 GNUNET_HashCode chash;
2520 GNUNET_HashCode mhash;
2524 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2525 "Matched result (type %u) for query `%s' with pending request\n",
2526 (unsigned int) prq->type,
2529 GNUNET_STATISTICS_update (stats,
2530 gettext_noop ("# replies received and matched"),
2533 if (prq->sender != NULL)
2535 /* FIXME: should we be more precise here and not use
2536 "start_time" but a peer-specific time stamp? */
2537 cur_delay = GNUNET_TIME_absolute_get_duration (pr->start_time);
2538 prq->sender->avg_delay.value
2539 = (prq->sender->avg_delay.value *
2540 (RUNAVG_DELAY_N - 1) + cur_delay.value) / RUNAVG_DELAY_N;
2541 prq->sender->avg_priority
2542 = (prq->sender->avg_priority *
2543 (RUNAVG_DELAY_N - 1) + pr->priority) / (double) RUNAVG_DELAY_N;
2546 GNUNET_PEER_change_rc (prq->sender->last_p2p_replies
2547 [prq->sender->last_p2p_replies_woff % P2P_SUCCESS_LIST_SIZE],
2549 GNUNET_PEER_change_rc (pr->cp->pid, 1);
2550 prq->sender->last_p2p_replies
2551 [(prq->sender->last_p2p_replies_woff++) % P2P_SUCCESS_LIST_SIZE]
2556 if (NULL != prq->sender->last_client_replies
2557 [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE])
2558 GNUNET_SERVER_client_drop (prq->sender->last_client_replies
2559 [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE]);
2560 prq->sender->last_client_replies
2561 [(prq->sender->last_client_replies_woff++) % CS2P_SUCCESS_LIST_SIZE]
2562 = pr->client_request_list->client_list->client;
2563 GNUNET_SERVER_client_keep (pr->client_request_list->client_list->client);
2566 GNUNET_CRYPTO_hash (prq->data,
2571 case GNUNET_BLOCK_TYPE_DBLOCK:
2572 case GNUNET_BLOCK_TYPE_IBLOCK:
2573 /* only possible reply, stop requesting! */
2574 while (NULL != pr->pending_head)
2575 destroy_pending_message_list_entry (pr->pending_head);
2578 if (pr->client_request_list != NULL)
2579 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
2581 GNUNET_DATASTORE_cancel (pr->qe);
2584 pr->do_remove = GNUNET_YES;
2585 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
2587 GNUNET_SCHEDULER_cancel (sched,
2589 pr->task = GNUNET_SCHEDULER_NO_TASK;
2591 GNUNET_break (GNUNET_YES ==
2592 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
2596 case GNUNET_BLOCK_TYPE_SBLOCK:
2597 if (pr->namespace == NULL)
2602 if (0 != memcmp (pr->namespace,
2604 sizeof (GNUNET_HashCode)))
2606 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2607 _("Reply mismatched in terms of namespace. Discarded.\n"));
2608 return GNUNET_YES; /* wrong namespace */
2610 /* then: fall-through! */
2611 case GNUNET_BLOCK_TYPE_KBLOCK:
2612 case GNUNET_BLOCK_TYPE_NBLOCK:
2615 mingle_hash (&chash, pr->mingle, &mhash);
2616 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
2619 GNUNET_STATISTICS_update (stats,
2620 gettext_noop ("# duplicate replies discarded (bloomfilter)"),
2624 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2625 "Duplicate response `%s', discarding.\n",
2626 GNUNET_h2s (&mhash));
2628 return GNUNET_YES; /* duplicate */
2631 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2632 "New response `%s', adding to filter.\n",
2633 GNUNET_h2s (&mhash));
2636 if (pr->client_request_list != NULL)
2638 if (pr->replies_seen_size == pr->replies_seen_off)
2639 GNUNET_array_grow (pr->replies_seen,
2640 pr->replies_seen_size,
2641 pr->replies_seen_size * 2 + 4);
2642 pr->replies_seen[pr->replies_seen_off++] = chash;
2644 if ( (pr->bf == NULL) ||
2645 (pr->client_request_list != NULL) )
2646 refresh_bloomfilter (pr);
2647 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
2654 prq->priority += pr->remaining_priority;
2655 pr->remaining_priority = 0;
2656 if (NULL != pr->client_request_list)
2658 GNUNET_STATISTICS_update (stats,
2659 gettext_noop ("# replies received for local clients"),
2662 cl = pr->client_request_list->client_list;
2663 msize = sizeof (struct PutMessage) + prq->size;
2664 creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
2665 creply->msize = msize;
2666 creply->client_list = cl;
2667 GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
2671 pm = (struct PutMessage*) &creply[1];
2672 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2673 pm->header.size = htons (msize);
2674 pm->type = htonl (prq->type);
2675 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
2676 memcpy (&pm[1], prq->data, prq->size);
2680 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2681 "Transmitting result for query `%s' to client\n",
2684 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
2686 GNUNET_TIME_UNIT_FOREVER_REL,
2687 &transmit_to_client,
2690 GNUNET_break (cl->th != NULL);
2693 prq->finished = GNUNET_YES;
2694 destroy_pending_request (pr);
2701 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2702 "Transmitting result for query `%s' to other peer (PID=%u)\n",
2704 (unsigned int) cp->pid);
2706 GNUNET_STATISTICS_update (stats,
2707 gettext_noop ("# replies received for other peers"),
2710 msize = sizeof (struct PutMessage) + prq->size;
2711 reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
2712 reply->cont = &transmit_reply_continuation;
2713 reply->cont_cls = pr;
2714 reply->msize = msize;
2715 reply->priority = UINT32_MAX; /* send replies first! */
2716 pm = (struct PutMessage*) &reply[1];
2717 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2718 pm->header.size = htons (msize);
2719 pm->type = htonl (prq->type);
2720 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
2721 memcpy (&pm[1], prq->data, prq->size);
2722 add_to_pending_messages_for_peer (cp, reply, pr);
2729 * Continuation called to notify client about result of the
2732 * @param cls closure
2733 * @param success GNUNET_SYSERR on failure
2734 * @param msg NULL on success, otherwise an error message
2737 put_migration_continuation (void *cls,
2746 * Handle P2P "PUT" message.
2748 * @param cls closure, always NULL
2749 * @param other the other peer involved (sender or receiver, NULL
2750 * for loopback messages where we are both sender and receiver)
2751 * @param message the actual message
2752 * @param latency reported latency of the connection with 'other'
2753 * @param distance reported distance (DV) to 'other'
2754 * @return GNUNET_OK to keep the connection open,
2755 * GNUNET_SYSERR to close it (signal serious error)
2758 handle_p2p_put (void *cls,
2759 const struct GNUNET_PeerIdentity *other,
2760 const struct GNUNET_MessageHeader *message,
2761 struct GNUNET_TIME_Relative latency,
2764 const struct PutMessage *put;
2767 enum GNUNET_BLOCK_Type type;
2768 struct GNUNET_TIME_Absolute expiration;
2769 GNUNET_HashCode query;
2770 struct ProcessReplyClosure prq;
2771 const struct SBlock *sb;
2773 msize = ntohs (message->size);
2774 if (msize < sizeof (struct PutMessage))
2777 return GNUNET_SYSERR;
2779 put = (const struct PutMessage*) message;
2780 dsize = msize - sizeof (struct PutMessage);
2781 type = ntohl (put->type);
2782 expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
2785 GNUNET_BLOCK_check_block (type,
2790 GNUNET_break_op (0);
2791 return GNUNET_SYSERR;
2793 if (type == GNUNET_BLOCK_TYPE_ONDEMAND)
2794 return GNUNET_SYSERR;
2795 if (GNUNET_BLOCK_TYPE_SBLOCK == type)
2797 sb = (const struct SBlock*) &put[1];
2798 GNUNET_CRYPTO_hash (&sb->subspace,
2799 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2804 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2805 "Received result for query `%s' from peer `%4s'\n",
2806 GNUNET_h2s (&query),
2807 GNUNET_i2s (other));
2809 GNUNET_STATISTICS_update (stats,
2810 gettext_noop ("# replies received (overall)"),
2813 /* now, lookup 'query' */
2814 prq.data = (const void*) &put[1];
2816 prq.sender = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2817 &other->hashPubKey);
2822 prq.expiration = expiration;
2824 prq.finished = GNUNET_NO;
2825 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2829 if (prq.sender != NULL)
2831 prq.sender->inc_preference += CONTENT_BANDWIDTH_VALUE + 1000 * prq.priority;
2832 prq.sender->trust += prq.priority;
2834 if (GNUNET_YES == active_migration)
2837 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2838 "Replicating result for query `%s' with priority %u\n",
2839 GNUNET_h2s (&query),
2842 GNUNET_DATASTORE_put (dsh,
2843 0, &query, dsize, &put[1],
2844 type, prq.priority, 1 /* anonymity */,
2846 1 + prq.priority, MAX_DATASTORE_QUEUE,
2847 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
2848 &put_migration_continuation,
2855 /* **************************** P2P GET Handling ************************ */
2859 * Closure for 'check_duplicate_request_{peer,client}'.
2861 struct CheckDuplicateRequestClosure
2864 * The new request we should check if it already exists.
2866 const struct PendingRequest *pr;
2869 * Existing request found by the checker, NULL if none.
2871 struct PendingRequest *have;
2876 * Iterator over entries in the 'query_request_map' that
2877 * tries to see if we have the same request pending from
2878 * the same client already.
2880 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
2881 * @param key current key code (query, ignored, must match)
2882 * @param value value in the hash map (a 'struct PendingRequest'
2883 * that already exists)
2884 * @return GNUNET_YES if we should continue to
2885 * iterate (no match yet)
2886 * GNUNET_NO if not (match found).
2889 check_duplicate_request_client (void *cls,
2890 const GNUNET_HashCode * key,
2893 struct CheckDuplicateRequestClosure *cdc = cls;
2894 struct PendingRequest *have = value;
2896 if (have->client_request_list == NULL)
2898 if ( (cdc->pr->client_request_list->client_list->client == have->client_request_list->client_list->client) &&
2909 * We're processing (local) results for a search request
2910 * from another peer. Pass applicable results to the
2911 * peer and if we are done either clean up (operation
2912 * complete) or forward to other peers (more results possible).
2914 * @param cls our closure (struct LocalGetContext)
2915 * @param key key for the content
2916 * @param size number of bytes in data
2917 * @param data content stored
2918 * @param type type of the content
2919 * @param priority priority of the content
2920 * @param anonymity anonymity-level for the content
2921 * @param expiration expiration time for the content
2922 * @param uid unique identifier for the datum;
2923 * maybe 0 if no unique identifier is available
2926 process_local_reply (void *cls,
2927 const GNUNET_HashCode * key,
2930 enum GNUNET_BLOCK_Type type,
2933 struct GNUNET_TIME_Absolute
2937 struct PendingRequest *pr = cls;
2938 struct ProcessReplyClosure prq;
2939 struct CheckDuplicateRequestClosure cdrc;
2940 const struct SBlock *sb;
2941 GNUNET_HashCode dhash;
2942 GNUNET_HashCode mhash;
2943 GNUNET_HashCode query;
2948 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2949 "Done processing local replies, forwarding request to other peers.\n");
2952 if (pr->client_request_list != NULL)
2954 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
2956 /* Figure out if this is a duplicate request and possibly
2957 merge 'struct PendingRequest' entries */
2960 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2962 &check_duplicate_request_client,
2964 if (cdrc.have != NULL)
2967 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2968 "Received request for block `%s' twice from client, will only request once.\n",
2969 GNUNET_h2s (&pr->query));
2972 destroy_pending_request (pr);
2977 /* no more results */
2978 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2979 pr->task = GNUNET_SCHEDULER_add_now (sched,
2980 &forward_request_task,
2985 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2986 "New local response to `%s' of type %u.\n",
2990 if (type == GNUNET_BLOCK_TYPE_ONDEMAND)
2993 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2994 "Found ONDEMAND block, performing on-demand encoding\n");
2996 GNUNET_STATISTICS_update (stats,
2997 gettext_noop ("# on-demand blocks matched requests"),
3001 GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
3002 anonymity, expiration, uid,
3003 &process_local_reply,
3006 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3009 /* check for duplicates */
3010 GNUNET_CRYPTO_hash (data, size, &dhash);
3011 mingle_hash (&dhash,
3014 if ( (pr->bf != NULL) &&
3016 GNUNET_CONTAINER_bloomfilter_test (pr->bf,
3020 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3021 "Result from datastore filtered by bloomfilter (duplicate).\n");
3023 GNUNET_STATISTICS_update (stats,
3024 gettext_noop ("# results filtered by query bloomfilter"),
3028 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3032 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3033 "Found result for query `%s' in local datastore\n",
3036 GNUNET_STATISTICS_update (stats,
3037 gettext_noop ("# results found locally"),
3040 pr->results_found++;
3041 memset (&prq, 0, sizeof (prq));
3043 prq.expiration = expiration;
3045 if (GNUNET_BLOCK_TYPE_SBLOCK == type)
3047 sb = (const struct SBlock*) data;
3048 GNUNET_CRYPTO_hash (&sb->subspace,
3049 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3052 if (GNUNET_OK != GNUNET_BLOCK_check_block (type,
3058 GNUNET_DATASTORE_remove (dsh,
3062 GNUNET_TIME_UNIT_FOREVER_REL,
3064 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3068 prq.priority = priority;
3069 prq.finished = GNUNET_NO;
3070 process_reply (&prq, key, pr);
3071 if (prq.finished == GNUNET_YES)
3074 return; /* done here */
3075 if ( (type == GNUNET_BLOCK_TYPE_DBLOCK) ||
3076 (type == GNUNET_BLOCK_TYPE_IBLOCK) )
3078 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
3081 if ( (pr->client_request_list == NULL) &&
3082 ( (GNUNET_YES == test_load_too_high()) ||
3083 (pr->results_found > 5 + 2 * pr->priority) ) )
3086 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3087 "Load too high, done with request\n");
3089 GNUNET_STATISTICS_update (stats,
3090 gettext_noop ("# processing result set cut short due to load"),
3093 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
3096 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3101 * We've received a request with the specified priority. Bound it
3102 * according to how much we trust the given peer.
3104 * @param prio_in requested priority
3105 * @param cp the peer making the request
3106 * @return effective priority
3109 bound_priority (uint32_t prio_in,
3110 struct ConnectedPeer *cp)
3112 #define N ((double)128.0)
3117 ld = test_load_too_high ();
3118 if (ld == GNUNET_SYSERR)
3119 return 0; /* excess resources */
3120 ret = change_host_trust (cp, prio_in);
3123 if (ret > current_priorities + N)
3124 rret = current_priorities + N;
3128 = (current_priorities * (N-1) + rret)/N;
3136 * Iterator over entries in the 'query_request_map' that
3137 * tries to see if we have the same request pending from
3138 * the same peer already.
3140 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
3141 * @param key current key code (query, ignored, must match)
3142 * @param value value in the hash map (a 'struct PendingRequest'
3143 * that already exists)
3144 * @return GNUNET_YES if we should continue to
3145 * iterate (no match yet)
3146 * GNUNET_NO if not (match found).
3149 check_duplicate_request_peer (void *cls,
3150 const GNUNET_HashCode * key,
3153 struct CheckDuplicateRequestClosure *cdc = cls;
3154 struct PendingRequest *have = value;
3156 if (cdc->pr->target_pid == have->target_pid)
3166 * Handle P2P "GET" request.
3168 * @param cls closure, always NULL
3169 * @param other the other peer involved (sender or receiver, NULL
3170 * for loopback messages where we are both sender and receiver)
3171 * @param message the actual message
3172 * @param latency reported latency of the connection with 'other'
3173 * @param distance reported distance (DV) to 'other'
3174 * @return GNUNET_OK to keep the connection open,
3175 * GNUNET_SYSERR to close it (signal serious error)
3178 handle_p2p_get (void *cls,
3179 const struct GNUNET_PeerIdentity *other,
3180 const struct GNUNET_MessageHeader *message,
3181 struct GNUNET_TIME_Relative latency,
3184 struct PendingRequest *pr;
3185 struct ConnectedPeer *cp;
3186 struct ConnectedPeer *cps;
3187 struct CheckDuplicateRequestClosure cdc;
3188 struct GNUNET_TIME_Relative timeout;
3190 const struct GetMessage *gm;
3192 const GNUNET_HashCode *opt;
3195 uint32_t ttl_decrement;
3196 enum GNUNET_BLOCK_Type type;
3200 msize = ntohs(message->size);
3201 if (msize < sizeof (struct GetMessage))
3203 GNUNET_break_op (0);
3204 return GNUNET_SYSERR;
3206 gm = (const struct GetMessage*) message;
3207 type = ntohl (gm->type);
3210 case GNUNET_BLOCK_TYPE_ANY:
3211 case GNUNET_BLOCK_TYPE_DBLOCK:
3212 case GNUNET_BLOCK_TYPE_IBLOCK:
3213 case GNUNET_BLOCK_TYPE_KBLOCK:
3214 case GNUNET_BLOCK_TYPE_SBLOCK:
3217 GNUNET_break_op (0);
3218 return GNUNET_SYSERR;
3220 bm = ntohl (gm->hash_bitmap);
3228 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
3230 GNUNET_break_op (0);
3231 return GNUNET_SYSERR;
3233 opt = (const GNUNET_HashCode*) &gm[1];
3234 bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
3235 bm = ntohl (gm->hash_bitmap);
3236 if ( (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)) &&
3237 (type != GNUNET_BLOCK_TYPE_SBLOCK) )
3239 GNUNET_break_op (0);
3240 return GNUNET_SYSERR;
3243 cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3244 &other->hashPubKey);
3247 /* peer must have just disconnected */
3248 GNUNET_STATISTICS_update (stats,
3249 gettext_noop ("# requests dropped due to initiator not being connected"),
3252 return GNUNET_SYSERR;
3254 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
3255 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3262 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
3263 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3264 "Failed to find RETURN-TO peer `%4s' in connection set. Dropping query.\n",
3265 GNUNET_i2s ((const struct GNUNET_PeerIdentity*) &opt[bits-1]));
3268 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3269 "Failed to find peer `%4s' in connection set. Dropping query.\n",
3270 GNUNET_i2s (other));
3272 GNUNET_STATISTICS_update (stats,
3273 gettext_noop ("# requests dropped due to missing reverse route"),
3276 /* FIXME: try connect? */
3279 /* note that we can really only check load here since otherwise
3280 peers could find out that we are overloaded by not being
3281 disconnected after sending us a malformed query... */
3283 /* FIXME: query priority should play
3284 a major role here! */
3285 ld = test_load_too_high ();
3286 if (GNUNET_YES == ld)
3289 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3290 "Dropping query from `%s', this peer is too busy.\n",
3291 GNUNET_i2s (other));
3293 GNUNET_STATISTICS_update (stats,
3294 gettext_noop ("# requests dropped due to high load"),
3299 /* FIXME: if ld == GNUNET_NO, forward
3300 instead of indirecting! */
3303 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3304 "Received request for `%s' of type %u from peer `%4s' with flags %u\n",
3305 GNUNET_h2s (&gm->query),
3306 (unsigned int) type,
3310 have_ns = (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE));
3311 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
3312 (have_ns ? sizeof(GNUNET_HashCode) : 0));
3315 pr->namespace = (GNUNET_HashCode*) &pr[1];
3316 memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
3319 pr->mingle = ntohl (gm->filter_mutator);
3320 if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
3321 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
3323 pr->anonymity_level = 1;
3324 pr->priority = bound_priority (ntohl (gm->priority), cps);
3325 pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
3326 pr->query = gm->query;
3327 /* decrement ttl (always) */
3328 ttl_decrement = 2 * TTL_DECREMENT +
3329 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3331 if ( (pr->ttl < 0) &&
3332 (((int32_t)(pr->ttl - ttl_decrement)) > 0) )
3335 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3336 "Dropping query from `%s' due to TTL underflow (%d - %u).\n",
3341 GNUNET_STATISTICS_update (stats,
3342 gettext_noop ("# requests dropped due TTL underflow"),
3345 /* integer underflow => drop (should be very rare)! */
3349 pr->ttl -= ttl_decrement;
3350 pr->start_time = GNUNET_TIME_absolute_get ();
3352 /* get bloom filter */
3355 pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
3358 pr->bf_size = bfsize;
3363 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
3365 &check_duplicate_request_peer,
3367 if (cdc.have != NULL)
3369 if (cdc.have->start_time.value + cdc.have->ttl >=
3370 pr->start_time.value + pr->ttl)
3372 /* existing request has higher TTL, drop new one! */
3373 cdc.have->priority += pr->priority;
3374 destroy_pending_request (pr);
3376 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3377 "Have existing request with higher TTL, dropping new request.\n",
3378 GNUNET_i2s (other));
3380 GNUNET_STATISTICS_update (stats,
3381 gettext_noop ("# requests dropped due to higher-TTL request"),
3388 /* existing request has lower TTL, drop old one! */
3389 pr->priority += cdc.have->priority;
3390 /* Possible optimization: if we have applicable pending
3391 replies in 'cdc.have', we might want to move those over
3392 (this is a really rare special-case, so it is not clear
3393 that this would be worth it) */
3394 destroy_pending_request (cdc.have);
3395 /* keep processing 'pr'! */
3400 GNUNET_break (GNUNET_OK ==
3401 GNUNET_CONTAINER_multihashmap_put (query_request_map,
3404 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
3405 GNUNET_break (GNUNET_OK ==
3406 GNUNET_CONTAINER_multihashmap_put (peer_request_map,
3409 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
3411 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
3413 pr->start_time.value + pr->ttl);
3415 GNUNET_STATISTICS_update (stats,
3416 gettext_noop ("# P2P searches received"),
3419 GNUNET_STATISTICS_update (stats,
3420 gettext_noop ("# P2P searches active"),
3424 /* calculate change in traffic preference */
3425 cps->inc_preference += pr->priority * 1000 + QUERY_BANDWIDTH_VALUE;
3426 /* process locally */
3427 if (type == GNUNET_BLOCK_TYPE_DBLOCK)
3428 type = GNUNET_BLOCK_TYPE_ANY; /* to get on-demand as well */
3429 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
3430 (pr->priority + 1));
3431 pr->qe = GNUNET_DATASTORE_get (dsh,
3435 MAX_DATASTORE_QUEUE,
3437 &process_local_reply,
3440 /* Are multiple results possible? If so, start processing remotely now! */
3443 case GNUNET_BLOCK_TYPE_DBLOCK:
3444 case GNUNET_BLOCK_TYPE_IBLOCK:
3445 /* only one result, wait for datastore */
3448 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
3449 pr->task = GNUNET_SCHEDULER_add_now (sched,
3450 &forward_request_task,
3454 /* make sure we don't track too many requests */
3455 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
3457 pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
3458 destroy_pending_request (pr);
3464 /* **************************** CS GET Handling ************************ */
3468 * Handle START_SEARCH-message (search request from client).
3470 * @param cls closure
3471 * @param client identification of the client
3472 * @param message the actual message
3475 handle_start_search (void *cls,
3476 struct GNUNET_SERVER_Client *client,
3477 const struct GNUNET_MessageHeader *message)
3479 static GNUNET_HashCode all_zeros;
3480 const struct SearchMessage *sm;
3481 struct ClientList *cl;
3482 struct ClientRequestList *crl;
3483 struct PendingRequest *pr;
3486 enum GNUNET_BLOCK_Type type;
3488 msize = ntohs (message->size);
3489 if ( (msize < sizeof (struct SearchMessage)) ||
3490 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
3493 GNUNET_SERVER_receive_done (client,
3497 GNUNET_STATISTICS_update (stats,
3498 gettext_noop ("# client searches received"),
3501 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
3502 sm = (const struct SearchMessage*) message;
3503 type = ntohl (sm->type);
3505 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3506 "Received request for `%s' of type %u from local client\n",
3507 GNUNET_h2s (&sm->query),
3508 (unsigned int) type);
3512 case GNUNET_BLOCK_TYPE_ANY:
3513 case GNUNET_BLOCK_TYPE_DBLOCK:
3514 case GNUNET_BLOCK_TYPE_IBLOCK:
3515 case GNUNET_BLOCK_TYPE_KBLOCK:
3516 case GNUNET_BLOCK_TYPE_SBLOCK:
3517 case GNUNET_BLOCK_TYPE_NBLOCK:
3521 GNUNET_SERVER_receive_done (client,
3527 while ( (cl != NULL) &&
3528 (cl->client != client) )
3532 cl = GNUNET_malloc (sizeof (struct ClientList));
3533 cl->client = client;
3534 GNUNET_SERVER_client_keep (client);
3535 cl->next = client_list;
3538 /* detect duplicate KBLOCK requests */
3539 if ( (type == GNUNET_BLOCK_TYPE_KBLOCK) ||
3540 (type == GNUNET_BLOCK_TYPE_NBLOCK) ||
3541 (type == GNUNET_BLOCK_TYPE_ANY) )
3544 while ( (crl != NULL) &&
3545 ( (0 != memcmp (&crl->req->query,
3547 sizeof (GNUNET_HashCode))) ||
3548 (crl->req->type != type) ) )
3553 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3554 "Have existing request, merging content-seen lists.\n");
3557 /* Duplicate request (used to send long list of
3558 known/blocked results); merge 'pr->replies_seen'
3559 and update bloom filter */
3560 GNUNET_array_grow (pr->replies_seen,
3561 pr->replies_seen_size,
3562 pr->replies_seen_off + sc);
3563 memcpy (&pr->replies_seen[pr->replies_seen_off],
3565 sc * sizeof (GNUNET_HashCode));
3566 pr->replies_seen_off += sc;
3567 refresh_bloomfilter (pr);
3568 GNUNET_STATISTICS_update (stats,
3569 gettext_noop ("# client searches updated (merged content seen list)"),
3572 GNUNET_SERVER_receive_done (client,
3577 GNUNET_STATISTICS_update (stats,
3578 gettext_noop ("# client searches active"),
3581 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
3582 ((type == GNUNET_BLOCK_TYPE_SBLOCK) ? sizeof(GNUNET_HashCode) : 0));
3583 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
3584 memset (crl, 0, sizeof (struct ClientRequestList));
3585 crl->client_list = cl;
3586 GNUNET_CONTAINER_DLL_insert (cl->rl_head,
3591 pr->client_request_list = crl;
3592 GNUNET_array_grow (pr->replies_seen,
3593 pr->replies_seen_size,
3595 memcpy (pr->replies_seen,
3597 sc * sizeof (GNUNET_HashCode));
3598 pr->replies_seen_off = sc;
3599 pr->anonymity_level = ntohl (sm->anonymity_level);
3600 refresh_bloomfilter (pr);
3601 pr->query = sm->query;
3602 if (0 == (1 & ntohl (sm->options)))
3603 pr->local_only = GNUNET_NO;
3605 pr->local_only = GNUNET_YES;
3608 case GNUNET_BLOCK_TYPE_DBLOCK:
3609 case GNUNET_BLOCK_TYPE_IBLOCK:
3610 if (0 != memcmp (&sm->target,
3612 sizeof (GNUNET_HashCode)))
3613 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
3615 case GNUNET_BLOCK_TYPE_SBLOCK:
3616 pr->namespace = (GNUNET_HashCode*) &pr[1];
3617 memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
3622 GNUNET_break (GNUNET_OK ==
3623 GNUNET_CONTAINER_multihashmap_put (query_request_map,
3626 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
3627 if (type == GNUNET_BLOCK_TYPE_DBLOCK)
3628 type = GNUNET_BLOCK_TYPE_ANY; /* get on-demand blocks too! */
3629 pr->qe = GNUNET_DATASTORE_get (dsh,
3633 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
3634 &process_local_reply,
3639 /* **************************** Startup ************************ */
3642 * Process fs requests.
3644 * @param s scheduler to use
3645 * @param server the initialized server
3646 * @param c configuration to use
3649 main_init (struct GNUNET_SCHEDULER_Handle *s,
3650 struct GNUNET_SERVER_Handle *server,
3651 const struct GNUNET_CONFIGURATION_Handle *c)
3653 static const struct GNUNET_CORE_MessageHandler p2p_handlers[] =
3656 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
3658 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
3661 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
3662 {&GNUNET_FS_handle_index_start, NULL,
3663 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
3664 {&GNUNET_FS_handle_index_list_get, NULL,
3665 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
3666 {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
3667 sizeof (struct UnindexMessage) },
3668 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
3675 stats = GNUNET_STATISTICS_create (sched, "fs", cfg);
3676 min_migration_delay = GNUNET_TIME_UNIT_SECONDS; // FIXME: get from config
3677 connected_peers = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3678 query_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3679 peer_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3680 requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
3681 core = GNUNET_CORE_connect (sched,
3683 GNUNET_TIME_UNIT_FOREVER_REL,
3686 &peer_connect_handler,
3687 &peer_disconnect_handler,
3694 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3695 _("Failed to connect to `%s' service.\n"),
3697 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
3698 connected_peers = NULL;
3699 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
3700 query_request_map = NULL;
3701 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
3702 requests_by_expiration_heap = NULL;
3703 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
3704 peer_request_map = NULL;
3707 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
3710 return GNUNET_SYSERR;
3712 /* FIXME: distinguish between sending and storing in options? */
3713 if (active_migration)
3715 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3716 _("Content migration is enabled, will start to gather data\n"));
3717 consider_migration_gathering ();
3719 GNUNET_SERVER_disconnect_notify (server,
3720 &handle_client_disconnect,
3722 GNUNET_assert (GNUNET_OK ==
3723 GNUNET_CONFIGURATION_get_value_filename (cfg,
3727 GNUNET_DISK_directory_create (trustDirectory);
3728 GNUNET_SCHEDULER_add_with_priority (sched,
3729 GNUNET_SCHEDULER_PRIORITY_HIGH,
3730 &cron_flush_trust, NULL);
3733 GNUNET_SERVER_add_handlers (server, handlers);
3734 GNUNET_SCHEDULER_add_delayed (sched,
3735 GNUNET_TIME_UNIT_FOREVER_REL,
3743 * Process fs requests.
3745 * @param cls closure
3746 * @param sched scheduler to use
3747 * @param server the initialized server
3748 * @param cfg configuration to use
3752 struct GNUNET_SCHEDULER_Handle *sched,
3753 struct GNUNET_SERVER_Handle *server,
3754 const struct GNUNET_CONFIGURATION_Handle *cfg)
3756 active_migration = GNUNET_CONFIGURATION_get_value_yesno (cfg,
3759 dsh = GNUNET_DATASTORE_connect (cfg,
3763 GNUNET_SCHEDULER_shutdown (sched);
3766 if ( (GNUNET_OK != GNUNET_FS_indexing_init (sched, cfg, dsh)) ||
3767 (GNUNET_OK != main_init (sched, server, cfg)) )
3769 GNUNET_SCHEDULER_shutdown (sched);
3770 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
3778 * The main function for the fs service.
3780 * @param argc number of arguments from the command line
3781 * @param argv command line arguments
3782 * @return 0 ok, 1 on error
3785 main (int argc, char *const *argv)
3787 return (GNUNET_OK ==
3788 GNUNET_SERVICE_run (argc,
3791 GNUNET_SERVICE_OPTION_NONE,
3792 &run, NULL)) ? 0 : 1;
3795 /* end of gnunet-service-fs.c */