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
31 #include "gnunet_constants.h"
32 #include "gnunet_core_service.h"
33 #include "gnunet_dht_service.h"
34 #include "gnunet_datastore_service.h"
35 #include "gnunet_load_lib.h"
36 #include "gnunet_peer_lib.h"
37 #include "gnunet_protocols.h"
38 #include "gnunet_signatures.h"
39 #include "gnunet_statistics_service.h"
40 #include "gnunet_util_lib.h"
41 #include "gnunet-service-fs_indexing.h"
44 #define DEBUG_FS GNUNET_NO
47 * Should we introduce random latency in processing? Required for proper
48 * implementation of GAP, but can be disabled for performance evaluation of
49 * the basic routing algorithm.
51 * Note that with delays enabled, performance can be significantly lower
52 * (several orders of magnitude in 2-peer test runs); if you want to
53 * measure throughput of other components, set this to NO. Also, you
54 * might want to consider changing 'RETRY_PROBABILITY_INV' to 1 for
55 * a rather wasteful mode of operation (that might still get the highest
56 * throughput overall).
58 #define SUPPORT_DELAYS GNUNET_NO
61 * Currently experimental code...
63 #define ENABLE_LOAD_MGMT GNUNET_YES
66 * Size for the hash map for DHT requests from the FS
67 * service. Should be about the number of concurrent
68 * DHT requests we plan to make.
70 #define FS_DHT_HT_SIZE 1024
72 #define DATASTORE_LOAD_AUTODECLINE GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 250)
75 * How often do we flush trust values to disk?
77 #define TRUST_FLUSH_FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
80 * How often do we at most PUT content into the DHT?
82 #define MAX_DHT_PUT_FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
85 * Inverse of the probability that we will submit the same query
86 * to the same peer again. If the same peer already got the query
87 * repeatedly recently, the probability is multiplied by the inverse
88 * of this number each time. Note that we only try about every TTL_DECREMENT/2
89 * plus MAX_CORK_DELAY (so roughly every 3.5s).
91 * Note that this factor is a key influence to performance in small
92 * networks (especially test networks of 2 peers) because if there is
93 * only a single peer with the data, this value will determine how
94 * soon we might re-try. For example, a value of 3 can result in
95 * 1.7 MB/s transfer rates for a 10 MB file when a value of 1 would
96 * give us 5 MB/s. OTOH, obviously re-trying the same peer can be
97 * rather inefficient in larger networks, hence picking 1 is in
98 * general not the best choice.
100 #define RETRY_PROBABILITY_INV 1
103 * What is the maximum delay for a P2P FS message (in our interaction
104 * with core)? FS-internal delays are another story. The value is
105 * chosen based on the 32k block size. Given that peers typcially
106 * have at least 1 kb/s bandwidth, 45s waits give us a chance to
107 * transmit one message even to the lowest-bandwidth peers.
109 #define MAX_TRANSMIT_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 45)
112 * Maximum number of requests (from other peers, overall) that we're
113 * willing to have pending at any given point in time. Can be changed
114 * via the configuration file (32k is just the default).
116 static unsigned long long max_pending_requests = (32 * 1024);
120 * Information we keep for each pending reply. The
121 * actual message follows at the end of this struct.
123 struct PendingMessage;
126 * Function called upon completion of a transmission.
129 * @param pid ID of receiving peer, 0 on transmission error
131 typedef void (*TransmissionContinuation)(void * cls,
132 GNUNET_PEER_Id tpid);
136 * Information we keep for each pending message (GET/PUT). The
137 * actual message follows at the end of this struct.
139 struct PendingMessage
142 * This is a doubly-linked list of messages to the same peer.
144 struct PendingMessage *next;
147 * This is a doubly-linked list of messages to the same peer.
149 struct PendingMessage *prev;
152 * Entry in pending message list for this pending message.
154 struct PendingMessageList *pml;
157 * Function to call immediately once we have transmitted this
160 TransmissionContinuation cont;
168 * Do not transmit this pending message until this deadline.
170 struct GNUNET_TIME_Absolute delay_until;
173 * Size of the reply; actual reply message follows
174 * at the end of this struct.
179 * How important is this message for us?
187 * Information about a peer that we are connected to.
188 * We track data that is useful for determining which
189 * peers should receive our requests. We also keep
190 * a list of messages to transmit to this peer.
196 * List of the last clients for which this peer successfully
199 struct GNUNET_SERVER_Client *last_client_replies[CS2P_SUCCESS_LIST_SIZE];
202 * List of the last PIDs for which
203 * this peer successfully answered a query;
204 * We use 0 to indicate no successful reply.
206 GNUNET_PEER_Id last_p2p_replies[P2P_SUCCESS_LIST_SIZE];
209 * Average delay between sending the peer a request and
210 * getting a reply (only calculated over the requests for
211 * which we actually got a reply). Calculated
212 * as a moving average: new_delay = ((n-1)*last_delay+curr_delay) / n
214 struct GNUNET_TIME_Relative avg_delay;
217 * Point in time until which this peer does not want us to migrate content
220 struct GNUNET_TIME_Absolute migration_blocked;
223 * Time until when we blocked this peer from migrating
226 struct GNUNET_TIME_Absolute last_migration_block;
229 * Transmission times for the last MAX_QUEUE_PER_PEER
230 * requests for this peer. Used as a ring buffer, current
231 * offset is stored in 'last_request_times_off'. If the
232 * oldest entry is more recent than the 'avg_delay', we should
233 * not send any more requests right now.
235 struct GNUNET_TIME_Absolute last_request_times[MAX_QUEUE_PER_PEER];
238 * Handle for an active request for transmission to this
241 struct GNUNET_CORE_TransmitHandle *cth;
244 * Messages (replies, queries, content migration) we would like to
245 * send to this peer in the near future. Sorted by priority, head.
247 struct PendingMessage *pending_messages_head;
250 * Messages (replies, queries, content migration) we would like to
251 * send to this peer in the near future. Sorted by priority, tail.
253 struct PendingMessage *pending_messages_tail;
256 * How long does it typically take for us to transmit a message
257 * to this peer? (delay between the request being issued and
258 * the callback being invoked).
260 struct GNUNET_LOAD_Value *transmission_delay;
263 * Time when the last transmission request was issued.
265 struct GNUNET_TIME_Absolute last_transmission_request_start;
268 * ID of delay task for scheduling transmission.
270 GNUNET_SCHEDULER_TaskIdentifier delayed_transmission_request_task;
273 * Average priority of successful replies. Calculated
274 * as a moving average: new_avg = ((n-1)*last_avg+curr_prio) / n
279 * Increase in traffic preference still to be submitted
280 * to the core service for this peer.
282 uint64_t inc_preference;
285 * Trust rating for this peer
290 * Trust rating for this peer on disk.
295 * The peer's identity.
300 * Size of the linked list of 'pending_messages'.
302 unsigned int pending_requests;
305 * Which offset in "last_p2p_replies" will be updated next?
306 * (we go round-robin).
308 unsigned int last_p2p_replies_woff;
311 * Which offset in "last_client_replies" will be updated next?
312 * (we go round-robin).
314 unsigned int last_client_replies_woff;
317 * Current offset into 'last_request_times' ring buffer.
319 unsigned int last_request_times_off;
325 * Information we keep for each pending request. We should try to
326 * keep this struct as small as possible since its memory consumption
327 * is key to how many requests we can have pending at once.
329 struct PendingRequest;
333 * Doubly-linked list of requests we are performing
334 * on behalf of the same client.
336 struct ClientRequestList
340 * This is a doubly-linked list.
342 struct ClientRequestList *next;
345 * This is a doubly-linked list.
347 struct ClientRequestList *prev;
350 * Request this entry represents.
352 struct PendingRequest *req;
355 * Client list this request belongs to.
357 struct ClientList *client_list;
363 * Replies to be transmitted to the client. The actual
364 * response message is allocated after this struct.
366 struct ClientResponseMessage
369 * This is a doubly-linked list.
371 struct ClientResponseMessage *next;
374 * This is a doubly-linked list.
376 struct ClientResponseMessage *prev;
379 * Client list entry this response belongs to.
381 struct ClientList *client_list;
384 * Number of bytes in the response.
391 * Linked list of clients we are performing requests
397 * This is a linked list.
399 struct ClientList *next;
402 * ID of a client making a request, NULL if this entry is for a
405 struct GNUNET_SERVER_Client *client;
408 * Head of list of requests performed on behalf
409 * of this client right now.
411 struct ClientRequestList *rl_head;
414 * Tail of list of requests performed on behalf
415 * of this client right now.
417 struct ClientRequestList *rl_tail;
420 * Head of linked list of responses.
422 struct ClientResponseMessage *res_head;
425 * Tail of linked list of responses.
427 struct ClientResponseMessage *res_tail;
430 * Context for sending replies.
432 struct GNUNET_CONNECTION_TransmitHandle *th;
438 * Information about a peer that we have forwarded this
439 * request to already.
441 struct UsedTargetEntry
444 * What was the last time we have transmitted this request to this
447 struct GNUNET_TIME_Absolute last_request_time;
450 * How often have we transmitted this request to this peer?
452 unsigned int num_requests;
455 * PID of the target peer.
466 * Doubly-linked list of messages we are performing
467 * due to a pending request.
469 struct PendingMessageList
473 * This is a doubly-linked list of messages on behalf of the same request.
475 struct PendingMessageList *next;
478 * This is a doubly-linked list of messages on behalf of the same request.
480 struct PendingMessageList *prev;
483 * Message this entry represents.
485 struct PendingMessage *pm;
488 * Request this entry belongs to.
490 struct PendingRequest *req;
493 * Peer this message is targeted for.
495 struct ConnectedPeer *target;
501 * Information we keep for each pending request. We should try to
502 * keep this struct as small as possible since its memory consumption
503 * is key to how many requests we can have pending at once.
505 struct PendingRequest
509 * If this request was made by a client, this is our entry in the
510 * client request list; otherwise NULL.
512 struct ClientRequestList *client_request_list;
515 * Entry of peer responsible for this entry (if this request
516 * was made by a peer).
518 struct ConnectedPeer *cp;
521 * If this is a namespace query, pointer to the hash of the public
522 * key of the namespace; otherwise NULL. Pointer will be to the
523 * end of this struct (so no need to free it).
525 const GNUNET_HashCode *namespace;
528 * Bloomfilter we use to filter out replies that we don't care about
529 * (anymore). NULL as long as we are interested in all replies.
531 struct GNUNET_CONTAINER_BloomFilter *bf;
534 * Context of our GNUNET_CORE_peer_change_preference call.
536 struct GNUNET_CORE_InformationRequestContext *irc;
539 * Reference to DHT get operation for this request (or NULL).
541 struct GNUNET_DHT_GetHandle *dht_get;
544 * Hash code of all replies that we have seen so far (only valid
545 * if client is not NULL since we only track replies like this for
548 GNUNET_HashCode *replies_seen;
551 * Node in the heap representing this entry; NULL
552 * if we have no heap node.
554 struct GNUNET_CONTAINER_HeapNode *hnode;
557 * Head of list of messages being performed on behalf of this
560 struct PendingMessageList *pending_head;
563 * Tail of list of messages being performed on behalf of this
566 struct PendingMessageList *pending_tail;
569 * When did we first see this request (form this peer), or, if our
570 * client is initiating, when did we last initiate a search?
572 struct GNUNET_TIME_Absolute start_time;
575 * The query that this request is for.
577 GNUNET_HashCode query;
580 * The task responsible for transmitting queries
583 GNUNET_SCHEDULER_TaskIdentifier task;
586 * (Interned) Peer identifier that identifies a preferred target
589 GNUNET_PEER_Id target_pid;
592 * (Interned) Peer identifiers of peers that have already
593 * received our query for this content.
595 struct UsedTargetEntry *used_targets;
598 * Our entry in the queue (non-NULL while we wait for our
599 * turn to interact with the local database).
601 struct GNUNET_DATASTORE_QueueEntry *qe;
604 * Size of the 'bf' (in bytes).
609 * Desired anonymity level; only valid for requests from a local client.
611 uint32_t anonymity_level;
614 * How many entries in "used_targets" are actually valid?
616 unsigned int used_targets_off;
619 * How long is the "used_targets" array?
621 unsigned int used_targets_size;
624 * Number of results found for this request.
626 unsigned int results_found;
629 * How many entries in "replies_seen" are actually valid?
631 unsigned int replies_seen_off;
634 * How long is the "replies_seen" array?
636 unsigned int replies_seen_size;
639 * Priority with which this request was made. If one of our clients
640 * made the request, then this is the current priority that we are
641 * using when initiating the request. This value is used when
642 * we decide to reward other peers with trust for providing a reply.
647 * Priority points left for us to spend when forwarding this request
650 uint32_t remaining_priority;
653 * Number to mingle hashes for bloom-filter tests with.
658 * TTL with which we saw this request (or, if we initiated, TTL that
659 * we used for the request).
664 * Type of the content that this request is for.
666 enum GNUNET_BLOCK_Type type;
669 * Remove this request after transmission of the current response.
674 * GNUNET_YES if we should not forward this request to other peers.
679 * GNUNET_YES if we should not forward this request to other peers.
687 * Block that is ready for migration to other peers. Actual data is at the end of the block.
689 struct MigrationReadyBlock
693 * This is a doubly-linked list.
695 struct MigrationReadyBlock *next;
698 * This is a doubly-linked list.
700 struct MigrationReadyBlock *prev;
703 * Query for the block.
705 GNUNET_HashCode query;
708 * When does this block expire?
710 struct GNUNET_TIME_Absolute expiration;
713 * Peers we would consider forwarding this
714 * block to. Zero for empty entries.
716 GNUNET_PEER_Id target_list[MIGRATION_LIST_SIZE];
724 * Number of targets already used.
726 unsigned int used_targets;
731 enum GNUNET_BLOCK_Type type;
736 * Our connection to the datastore.
738 static struct GNUNET_DATASTORE_Handle *dsh;
743 static struct GNUNET_BLOCK_Context *block_ctx;
746 * Our block configuration.
748 static struct GNUNET_CONFIGURATION_Handle *block_cfg;
753 static struct GNUNET_SCHEDULER_Handle *sched;
758 static const struct GNUNET_CONFIGURATION_Handle *cfg;
761 * Map of peer identifiers to "struct ConnectedPeer" (for that peer).
763 static struct GNUNET_CONTAINER_MultiHashMap *connected_peers;
766 * Map of peer identifiers to "struct PendingRequest" (for that peer).
768 static struct GNUNET_CONTAINER_MultiHashMap *peer_request_map;
771 * Map of query identifiers to "struct PendingRequest" (for that query).
773 static struct GNUNET_CONTAINER_MultiHashMap *query_request_map;
776 * Heap with the request that will expire next at the top. Contains
777 * pointers of type "struct PendingRequest*"; these will *also* be
778 * aliased from the "requests_by_peer" data structures and the
779 * "requests_by_query" table. Note that requests from our clients
780 * don't expire and are thus NOT in the "requests_by_expiration"
781 * (or the "requests_by_peer" tables).
783 static struct GNUNET_CONTAINER_Heap *requests_by_expiration_heap;
786 * Handle for reporting statistics.
788 static struct GNUNET_STATISTICS_Handle *stats;
791 * Linked list of clients we are currently processing requests for.
793 static struct ClientList *client_list;
796 * Pointer to handle to the core service (points to NULL until we've
799 static struct GNUNET_CORE_Handle *core;
802 * Head of linked list of blocks that can be migrated.
804 static struct MigrationReadyBlock *mig_head;
807 * Tail of linked list of blocks that can be migrated.
809 static struct MigrationReadyBlock *mig_tail;
812 * Request to datastore for migration (or NULL).
814 static struct GNUNET_DATASTORE_QueueEntry *mig_qe;
817 * Request to datastore for DHT PUTs (or NULL).
819 static struct GNUNET_DATASTORE_QueueEntry *dht_qe;
822 * Type we will request for the next DHT PUT round from the datastore.
824 static enum GNUNET_BLOCK_Type dht_put_type = GNUNET_BLOCK_TYPE_FS_KBLOCK;
827 * Where do we store trust information?
829 static char *trustDirectory;
832 * ID of task that collects blocks for migration.
834 static GNUNET_SCHEDULER_TaskIdentifier mig_task;
837 * ID of task that collects blocks for DHT PUTs.
839 static GNUNET_SCHEDULER_TaskIdentifier dht_task;
842 * What is the maximum frequency at which we are allowed to
843 * poll the datastore for migration content?
845 static struct GNUNET_TIME_Relative min_migration_delay;
848 * Handle for DHT operations.
850 static struct GNUNET_DHT_Handle *dht_handle;
853 * Size of the doubly-linked list of migration blocks.
855 static unsigned int mig_size;
858 * Are we allowed to migrate content to this peer.
860 static int active_migration;
863 * How many entires with zero anonymity do we currently estimate
864 * to have in the database?
866 static unsigned int zero_anonymity_count_estimate;
869 * Typical priorities we're seeing from other peers right now. Since
870 * most priorities will be zero, this value is the weighted average of
871 * non-zero priorities seen "recently". In order to ensure that new
872 * values do not dramatically change the ratio, values are first
873 * "capped" to a reasonable range (+N of the current value) and then
874 * averaged into the existing value by a ratio of 1:N. Hence
875 * receiving the largest possible priority can still only raise our
876 * "current_priorities" by at most 1.
878 static double current_priorities;
881 * Datastore 'GET' load tracking.
883 static struct GNUNET_LOAD_Value *datastore_get_load;
886 * Datastore 'PUT' load tracking.
888 static struct GNUNET_LOAD_Value *datastore_put_load;
891 * How long do requests typically stay in the routing table?
893 static struct GNUNET_LOAD_Value *rt_entry_lifetime;
896 * We've just now completed a datastore request. Update our
897 * datastore load calculations.
899 * @param start time when the datastore request was issued
902 update_datastore_delays (struct GNUNET_TIME_Absolute start)
904 struct GNUNET_TIME_Relative delay;
906 delay = GNUNET_TIME_absolute_get_duration (start);
907 GNUNET_LOAD_update (datastore_get_load,
913 * Get the filename under which we would store the GNUNET_HELLO_Message
914 * for the given host and protocol.
915 * @return filename of the form DIRECTORY/HOSTID
918 get_trust_filename (const struct GNUNET_PeerIdentity *id)
920 struct GNUNET_CRYPTO_HashAsciiEncoded fil;
923 GNUNET_CRYPTO_hash_to_enc (&id->hashPubKey, &fil);
924 GNUNET_asprintf (&fn, "%s%s%s", trustDirectory, DIR_SEPARATOR_STR, &fil);
931 * Transmit messages by copying it to the target buffer
932 * "buf". "buf" will be NULL and "size" zero if the socket was closed
933 * for writing in the meantime. In that case, do nothing
934 * (the disconnect or shutdown handler will take care of the rest).
935 * If we were able to transmit messages and there are still more
936 * pending, ask core again for further calls to this function.
938 * @param cls closure, pointer to the 'struct ConnectedPeer*'
939 * @param size number of bytes available in buf
940 * @param buf where the callee should write the message
941 * @return number of bytes written to buf
944 transmit_to_peer (void *cls,
945 size_t size, void *buf);
948 /* ******************* clean up functions ************************ */
951 * Delete the given migration block.
953 * @param mb block to delete
956 delete_migration_block (struct MigrationReadyBlock *mb)
958 GNUNET_CONTAINER_DLL_remove (mig_head,
961 GNUNET_PEER_decrement_rcs (mb->target_list,
962 MIGRATION_LIST_SIZE);
969 * Compare the distance of two peers to a key.
972 * @param p1 first peer
973 * @param p2 second peer
974 * @return GNUNET_YES if P1 is closer to key than P2
977 is_closer (const GNUNET_HashCode *key,
978 const struct GNUNET_PeerIdentity *p1,
979 const struct GNUNET_PeerIdentity *p2)
981 return GNUNET_CRYPTO_hash_xorcmp (&p1->hashPubKey,
988 * Consider migrating content to a given peer.
990 * @param cls 'struct MigrationReadyBlock*' to select
991 * targets for (or NULL for none)
992 * @param key ID of the peer
993 * @param value 'struct ConnectedPeer' of the peer
994 * @return GNUNET_YES (always continue iteration)
997 consider_migration (void *cls,
998 const GNUNET_HashCode *key,
1001 struct MigrationReadyBlock *mb = cls;
1002 struct ConnectedPeer *cp = value;
1003 struct MigrationReadyBlock *pos;
1004 struct GNUNET_PeerIdentity cppid;
1005 struct GNUNET_PeerIdentity otherpid;
1006 struct GNUNET_PeerIdentity worstpid;
1011 /* consider 'cp' as a migration target for mb */
1012 if (GNUNET_TIME_absolute_get_remaining (cp->migration_blocked).value > 0)
1013 return GNUNET_YES; /* peer has requested no migration! */
1016 GNUNET_PEER_resolve (cp->pid,
1018 repl = MIGRATION_LIST_SIZE;
1019 for (i=0;i<MIGRATION_LIST_SIZE;i++)
1021 if (mb->target_list[i] == 0)
1023 mb->target_list[i] = cp->pid;
1024 GNUNET_PEER_change_rc (mb->target_list[i], 1);
1025 repl = MIGRATION_LIST_SIZE;
1028 GNUNET_PEER_resolve (mb->target_list[i],
1030 if ( (repl == MIGRATION_LIST_SIZE) &&
1031 is_closer (&mb->query,
1036 worstpid = otherpid;
1038 else if ( (repl != MIGRATION_LIST_SIZE) &&
1039 (is_closer (&mb->query,
1044 worstpid = otherpid;
1047 if (repl != MIGRATION_LIST_SIZE)
1049 GNUNET_PEER_change_rc (mb->target_list[repl], -1);
1050 mb->target_list[repl] = cp->pid;
1051 GNUNET_PEER_change_rc (mb->target_list[repl], 1);
1055 /* consider scheduling transmission to cp for content migration */
1056 if (cp->cth != NULL)
1062 for (i=0;i<MIGRATION_LIST_SIZE;i++)
1064 if (cp->pid == pos->target_list[i])
1069 msize = GNUNET_MIN (msize,
1077 return GNUNET_YES; /* no content available */
1079 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1080 "Trying to migrate at least %u bytes to peer `%s'\n",
1084 if (cp->delayed_transmission_request_task != GNUNET_SCHEDULER_NO_TASK)
1086 GNUNET_SCHEDULER_cancel (sched, cp->delayed_transmission_request_task);
1087 cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
1090 = GNUNET_CORE_notify_transmit_ready (core,
1091 0, GNUNET_TIME_UNIT_FOREVER_REL,
1092 (const struct GNUNET_PeerIdentity*) key,
1093 msize + sizeof (struct PutMessage),
1101 * Task that is run periodically to obtain blocks for content
1105 * @param tc scheduler context (also unused)
1108 gather_migration_blocks (void *cls,
1109 const struct GNUNET_SCHEDULER_TaskContext *tc);
1115 * Task that is run periodically to obtain blocks for DHT PUTs.
1117 * @param cls type of blocks to gather
1118 * @param tc scheduler context (unused)
1121 gather_dht_put_blocks (void *cls,
1122 const struct GNUNET_SCHEDULER_TaskContext *tc);
1126 * If the migration task is not currently running, consider
1127 * (re)scheduling it with the appropriate delay.
1130 consider_migration_gathering ()
1132 struct GNUNET_TIME_Relative delay;
1138 if (mig_task != GNUNET_SCHEDULER_NO_TASK)
1140 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
1142 delay = GNUNET_TIME_relative_divide (delay,
1143 MAX_MIGRATION_QUEUE);
1144 delay = GNUNET_TIME_relative_max (delay,
1145 min_migration_delay);
1146 mig_task = GNUNET_SCHEDULER_add_delayed (sched,
1148 &gather_migration_blocks,
1154 * If the DHT PUT gathering task is not currently running, consider
1155 * (re)scheduling it with the appropriate delay.
1158 consider_dht_put_gathering (void *cls)
1160 struct GNUNET_TIME_Relative delay;
1166 if (dht_task != GNUNET_SCHEDULER_NO_TASK)
1168 if (zero_anonymity_count_estimate > 0)
1170 delay = GNUNET_TIME_relative_divide (GNUNET_DHT_DEFAULT_REPUBLISH_FREQUENCY,
1171 zero_anonymity_count_estimate);
1172 delay = GNUNET_TIME_relative_min (delay,
1177 /* if we have NO zero-anonymity content yet, wait 5 minutes for some to
1178 (hopefully) appear */
1179 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5);
1181 dht_task = GNUNET_SCHEDULER_add_delayed (sched,
1183 &gather_dht_put_blocks,
1189 * Process content offered for migration.
1191 * @param cls closure
1192 * @param key key for the content
1193 * @param size number of bytes in data
1194 * @param data content stored
1195 * @param type type of the content
1196 * @param priority priority of the content
1197 * @param anonymity anonymity-level for the content
1198 * @param expiration expiration time for the content
1199 * @param uid unique identifier for the datum;
1200 * maybe 0 if no unique identifier is available
1203 process_migration_content (void *cls,
1204 const GNUNET_HashCode * key,
1207 enum GNUNET_BLOCK_Type type,
1210 struct GNUNET_TIME_Absolute
1211 expiration, uint64_t uid)
1213 struct MigrationReadyBlock *mb;
1218 if (mig_size < MAX_MIGRATION_QUEUE)
1219 consider_migration_gathering ();
1222 if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
1225 GNUNET_FS_handle_on_demand_block (key, size, data,
1226 type, priority, anonymity,
1228 &process_migration_content,
1231 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1236 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1237 "Retrieved block `%s' of type %u for migration\n",
1241 mb = GNUNET_malloc (sizeof (struct MigrationReadyBlock) + size);
1243 mb->expiration = expiration;
1246 memcpy (&mb[1], data, size);
1247 GNUNET_CONTAINER_DLL_insert_after (mig_head,
1252 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1253 &consider_migration,
1255 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1260 * Function called upon completion of the DHT PUT operation.
1263 dht_put_continuation (void *cls,
1264 const struct GNUNET_SCHEDULER_TaskContext *tc)
1266 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1271 * Store content in DHT.
1273 * @param cls closure
1274 * @param key key for the content
1275 * @param size number of bytes in data
1276 * @param data content stored
1277 * @param type type of the content
1278 * @param priority priority of the content
1279 * @param anonymity anonymity-level for the content
1280 * @param expiration expiration time for the content
1281 * @param uid unique identifier for the datum;
1282 * maybe 0 if no unique identifier is available
1285 process_dht_put_content (void *cls,
1286 const GNUNET_HashCode * key,
1289 enum GNUNET_BLOCK_Type type,
1292 struct GNUNET_TIME_Absolute
1293 expiration, uint64_t uid)
1295 static unsigned int counter;
1296 static GNUNET_HashCode last_vhash;
1297 static GNUNET_HashCode vhash;
1302 consider_dht_put_gathering (cls);
1305 /* slightly funky code to estimate the total number of values with zero
1306 anonymity from the maximum observed length of a monotonically increasing
1307 sequence of hashes over the contents */
1308 GNUNET_CRYPTO_hash (data, size, &vhash);
1309 if (GNUNET_CRYPTO_hash_cmp (&vhash, &last_vhash) <= 0)
1311 if (zero_anonymity_count_estimate > 0)
1312 zero_anonymity_count_estimate /= 2;
1318 if (zero_anonymity_count_estimate < (1 << counter))
1319 zero_anonymity_count_estimate = (1 << counter);
1321 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1322 "Retrieved block `%s' of type %u for DHT PUT\n",
1326 GNUNET_DHT_put (dht_handle,
1333 GNUNET_TIME_UNIT_FOREVER_REL,
1334 &dht_put_continuation,
1340 * Task that is run periodically to obtain blocks for content
1344 * @param tc scheduler context (also unused)
1347 gather_migration_blocks (void *cls,
1348 const struct GNUNET_SCHEDULER_TaskContext *tc)
1350 mig_task = GNUNET_SCHEDULER_NO_TASK;
1353 mig_qe = GNUNET_DATASTORE_get_random (dsh, 0, UINT_MAX,
1354 GNUNET_TIME_UNIT_FOREVER_REL,
1355 &process_migration_content, NULL);
1356 GNUNET_assert (mig_qe != NULL);
1362 * Task that is run periodically to obtain blocks for DHT PUTs.
1364 * @param cls type of blocks to gather
1365 * @param tc scheduler context (unused)
1368 gather_dht_put_blocks (void *cls,
1369 const struct GNUNET_SCHEDULER_TaskContext *tc)
1371 dht_task = GNUNET_SCHEDULER_NO_TASK;
1374 if (dht_put_type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
1375 dht_put_type = GNUNET_BLOCK_TYPE_FS_KBLOCK;
1376 dht_qe = GNUNET_DATASTORE_get_zero_anonymity (dsh, 0, UINT_MAX,
1377 GNUNET_TIME_UNIT_FOREVER_REL,
1379 &process_dht_put_content, NULL);
1380 GNUNET_assert (dht_qe != NULL);
1386 * We're done with a particular message list entry.
1387 * Free all associated resources.
1389 * @param pml entry to destroy
1392 destroy_pending_message_list_entry (struct PendingMessageList *pml)
1394 GNUNET_CONTAINER_DLL_remove (pml->req->pending_head,
1395 pml->req->pending_tail,
1397 GNUNET_CONTAINER_DLL_remove (pml->target->pending_messages_head,
1398 pml->target->pending_messages_tail,
1400 pml->target->pending_requests--;
1401 GNUNET_free (pml->pm);
1407 * Destroy the given pending message (and call the respective
1410 * @param pm message to destroy
1411 * @param tpid id of peer that the message was delivered to, or 0 for none
1414 destroy_pending_message (struct PendingMessage *pm,
1415 GNUNET_PEER_Id tpid)
1417 struct PendingMessageList *pml = pm->pml;
1418 TransmissionContinuation cont;
1422 cont_cls = pm->cont_cls;
1425 GNUNET_assert (pml->pm == pm);
1426 GNUNET_assert ( (tpid == 0) || (tpid == pml->target->pid) );
1427 destroy_pending_message_list_entry (pml);
1434 cont (cont_cls, tpid);
1439 * We're done processing a particular request.
1440 * Free all associated resources.
1442 * @param pr request to destroy
1445 destroy_pending_request (struct PendingRequest *pr)
1447 struct GNUNET_PeerIdentity pid;
1450 if (pr->hnode != NULL)
1452 GNUNET_CONTAINER_heap_remove_node (requests_by_expiration_heap,
1456 if (NULL == pr->client_request_list)
1458 GNUNET_STATISTICS_update (stats,
1459 gettext_noop ("# P2P searches active"),
1465 GNUNET_STATISTICS_update (stats,
1466 gettext_noop ("# client searches active"),
1471 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
1475 GNUNET_LOAD_update (rt_entry_lifetime,
1476 GNUNET_TIME_absolute_get_duration (pr->start_time).value);
1480 GNUNET_DATASTORE_cancel (pr->qe);
1483 if (pr->dht_get != NULL)
1485 GNUNET_DHT_get_stop (pr->dht_get);
1488 if (pr->client_request_list != NULL)
1490 GNUNET_CONTAINER_DLL_remove (pr->client_request_list->client_list->rl_head,
1491 pr->client_request_list->client_list->rl_tail,
1492 pr->client_request_list);
1493 GNUNET_free (pr->client_request_list);
1494 pr->client_request_list = NULL;
1498 GNUNET_PEER_resolve (pr->cp->pid,
1500 (void) GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
1507 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
1510 if (pr->irc != NULL)
1512 GNUNET_CORE_peer_change_preference_cancel (pr->irc);
1515 if (pr->replies_seen != NULL)
1517 GNUNET_free (pr->replies_seen);
1518 pr->replies_seen = NULL;
1520 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
1522 GNUNET_SCHEDULER_cancel (sched,
1524 pr->task = GNUNET_SCHEDULER_NO_TASK;
1526 while (NULL != pr->pending_head)
1527 destroy_pending_message_list_entry (pr->pending_head);
1528 GNUNET_PEER_change_rc (pr->target_pid, -1);
1529 if (pr->used_targets != NULL)
1531 for (i=0;i<pr->used_targets_off;i++)
1532 GNUNET_PEER_change_rc (pr->used_targets[i].pid, -1);
1533 GNUNET_free (pr->used_targets);
1534 pr->used_targets_off = 0;
1535 pr->used_targets_size = 0;
1536 pr->used_targets = NULL;
1543 * Method called whenever a given peer connects.
1545 * @param cls closure, not used
1546 * @param peer peer identity this notification is about
1547 * @param latency reported latency of the connection with 'other'
1548 * @param distance reported distance (DV) to 'other'
1551 peer_connect_handler (void *cls,
1553 GNUNET_PeerIdentity * peer,
1554 struct GNUNET_TIME_Relative latency,
1557 struct ConnectedPeer *cp;
1558 struct MigrationReadyBlock *pos;
1562 cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
1563 cp->transmission_delay = GNUNET_LOAD_value_init (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1564 cp->pid = GNUNET_PEER_intern (peer);
1566 fn = get_trust_filename (peer);
1567 if ((GNUNET_DISK_file_test (fn) == GNUNET_YES) &&
1568 (sizeof (trust) == GNUNET_DISK_fn_read (fn, &trust, sizeof (trust))))
1569 cp->disk_trust = cp->trust = ntohl (trust);
1572 GNUNET_break (GNUNET_OK ==
1573 GNUNET_CONTAINER_multihashmap_put (connected_peers,
1576 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1581 (void) consider_migration (pos, &peer->hashPubKey, cp);
1588 * Increase the host credit by a value.
1590 * @param host which peer to change the trust value on
1591 * @param value is the int value by which the
1592 * host credit is to be increased or decreased
1593 * @returns the actual change in trust (positive or negative)
1596 change_host_trust (struct ConnectedPeer *host, int value)
1598 unsigned int old_trust;
1602 GNUNET_assert (host != NULL);
1603 old_trust = host->trust;
1606 if (host->trust + value < host->trust)
1608 value = UINT32_MAX - host->trust;
1609 host->trust = UINT32_MAX;
1612 host->trust += value;
1616 if (host->trust < -value)
1618 value = -host->trust;
1622 host->trust += value;
1629 * Write host-trust information to a file - flush the buffer entry!
1632 flush_trust (void *cls,
1633 const GNUNET_HashCode *key,
1636 struct ConnectedPeer *host = value;
1639 struct GNUNET_PeerIdentity pid;
1641 if (host->trust == host->disk_trust)
1642 return GNUNET_OK; /* unchanged */
1643 GNUNET_PEER_resolve (host->pid,
1645 fn = get_trust_filename (&pid);
1646 if (host->trust == 0)
1648 if ((0 != UNLINK (fn)) && (errno != ENOENT))
1649 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
1650 GNUNET_ERROR_TYPE_BULK, "unlink", fn);
1654 trust = htonl (host->trust);
1655 if (sizeof(uint32_t) == GNUNET_DISK_fn_write (fn, &trust,
1657 GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE
1658 | GNUNET_DISK_PERM_GROUP_READ | GNUNET_DISK_PERM_OTHER_READ))
1659 host->disk_trust = host->trust;
1666 * Call this method periodically to scan data/hosts for new hosts.
1669 cron_flush_trust (void *cls,
1670 const struct GNUNET_SCHEDULER_TaskContext *tc)
1673 if (NULL == connected_peers)
1675 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1680 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1682 GNUNET_SCHEDULER_add_delayed (tc->sched,
1683 TRUST_FLUSH_FREQ, &cron_flush_trust, NULL);
1688 * Free (each) request made by the peer.
1690 * @param cls closure, points to peer that the request belongs to
1691 * @param key current key code
1692 * @param value value in the hash map
1693 * @return GNUNET_YES (we should continue to iterate)
1696 destroy_request (void *cls,
1697 const GNUNET_HashCode * key,
1700 const struct GNUNET_PeerIdentity * peer = cls;
1701 struct PendingRequest *pr = value;
1703 GNUNET_break (GNUNET_YES ==
1704 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
1707 destroy_pending_request (pr);
1713 * Method called whenever a peer disconnects.
1715 * @param cls closure, not used
1716 * @param peer peer identity this notification is about
1719 peer_disconnect_handler (void *cls,
1721 GNUNET_PeerIdentity * peer)
1723 struct ConnectedPeer *cp;
1724 struct PendingMessage *pm;
1726 struct MigrationReadyBlock *pos;
1727 struct MigrationReadyBlock *next;
1729 GNUNET_CONTAINER_multihashmap_get_multiple (peer_request_map,
1733 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1737 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1739 if (NULL != cp->last_client_replies[i])
1741 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1742 cp->last_client_replies[i] = NULL;
1745 GNUNET_break (GNUNET_YES ==
1746 GNUNET_CONTAINER_multihashmap_remove (connected_peers,
1749 /* remove this peer from migration considerations; schedule
1752 while (NULL != (pos = next))
1755 for (i=0;i<MIGRATION_LIST_SIZE;i++)
1757 if (pos->target_list[i] == cp->pid)
1759 GNUNET_PEER_change_rc (pos->target_list[i], -1);
1760 pos->target_list[i] = 0;
1763 if (pos->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers))
1765 delete_migration_block (pos);
1766 consider_migration_gathering ();
1769 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1770 &consider_migration,
1773 GNUNET_PEER_change_rc (cp->pid, -1);
1774 GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
1775 if (NULL != cp->cth)
1777 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
1780 if (cp->delayed_transmission_request_task != GNUNET_SCHEDULER_NO_TASK)
1782 GNUNET_SCHEDULER_cancel (sched, cp->delayed_transmission_request_task);
1783 cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
1785 while (NULL != (pm = cp->pending_messages_head))
1786 destroy_pending_message (pm, 0 /* delivery failed */);
1787 GNUNET_LOAD_value_free (cp->transmission_delay);
1788 GNUNET_break (0 == cp->pending_requests);
1794 * Iterator over hash map entries that removes all occurences
1795 * of the given 'client' from the 'last_client_replies' of the
1796 * given connected peer.
1798 * @param cls closure, the 'struct GNUNET_SERVER_Client*' to remove
1799 * @param key current key code (unused)
1800 * @param value value in the hash map (the 'struct ConnectedPeer*' to change)
1801 * @return GNUNET_YES (we should continue to iterate)
1804 remove_client_from_last_client_replies (void *cls,
1805 const GNUNET_HashCode * key,
1808 struct GNUNET_SERVER_Client *client = cls;
1809 struct ConnectedPeer *cp = value;
1812 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1814 if (cp->last_client_replies[i] == client)
1816 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1817 cp->last_client_replies[i] = NULL;
1825 * A client disconnected. Remove all of its pending queries.
1827 * @param cls closure, NULL
1828 * @param client identification of the client
1831 handle_client_disconnect (void *cls,
1832 struct GNUNET_SERVER_Client
1835 struct ClientList *pos;
1836 struct ClientList *prev;
1837 struct ClientRequestList *rcl;
1838 struct ClientResponseMessage *creply;
1844 while ( (NULL != pos) &&
1845 (pos->client != client) )
1851 return; /* no requests pending for this client */
1852 while (NULL != (rcl = pos->rl_head))
1854 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1855 "Destroying pending request `%s' on disconnect\n",
1856 GNUNET_h2s (&rcl->req->query));
1857 destroy_pending_request (rcl->req);
1860 client_list = pos->next;
1862 prev->next = pos->next;
1863 if (pos->th != NULL)
1865 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
1868 while (NULL != (creply = pos->res_head))
1870 GNUNET_CONTAINER_DLL_remove (pos->res_head,
1873 GNUNET_free (creply);
1875 GNUNET_SERVER_client_drop (pos->client);
1877 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1878 &remove_client_from_last_client_replies,
1884 * Iterator to free peer entries.
1886 * @param cls closure, unused
1887 * @param key current key code
1888 * @param value value in the hash map (peer entry)
1889 * @return GNUNET_YES (we should continue to iterate)
1892 clean_peer (void *cls,
1893 const GNUNET_HashCode * key,
1896 peer_disconnect_handler (NULL, (const struct GNUNET_PeerIdentity*) key);
1902 * Task run during shutdown.
1908 shutdown_task (void *cls,
1909 const struct GNUNET_SCHEDULER_TaskContext *tc)
1913 GNUNET_DATASTORE_cancel (mig_qe);
1918 GNUNET_DATASTORE_cancel (dht_qe);
1921 if (GNUNET_SCHEDULER_NO_TASK != mig_task)
1923 GNUNET_SCHEDULER_cancel (sched, mig_task);
1924 mig_task = GNUNET_SCHEDULER_NO_TASK;
1926 if (GNUNET_SCHEDULER_NO_TASK != dht_task)
1928 GNUNET_SCHEDULER_cancel (sched, dht_task);
1929 dht_task = GNUNET_SCHEDULER_NO_TASK;
1931 while (client_list != NULL)
1932 handle_client_disconnect (NULL,
1933 client_list->client);
1934 cron_flush_trust (NULL, NULL);
1935 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1938 GNUNET_break (0 == GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap));
1939 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
1940 requests_by_expiration_heap = 0;
1941 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
1942 connected_peers = NULL;
1943 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (query_request_map));
1944 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
1945 query_request_map = NULL;
1946 GNUNET_LOAD_value_free (rt_entry_lifetime);
1947 rt_entry_lifetime = NULL;
1948 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (peer_request_map));
1949 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
1950 peer_request_map = NULL;
1951 GNUNET_assert (NULL != core);
1952 GNUNET_CORE_disconnect (core);
1956 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1961 GNUNET_DATASTORE_disconnect (dsh,
1965 while (mig_head != NULL)
1966 delete_migration_block (mig_head);
1967 GNUNET_assert (0 == mig_size);
1968 GNUNET_DHT_disconnect (dht_handle);
1970 GNUNET_LOAD_value_free (datastore_get_load);
1971 datastore_get_load = NULL;
1972 GNUNET_LOAD_value_free (datastore_put_load);
1973 datastore_put_load = NULL;
1974 GNUNET_BLOCK_context_destroy (block_ctx);
1976 GNUNET_CONFIGURATION_destroy (block_cfg);
1980 GNUNET_free_non_null (trustDirectory);
1981 trustDirectory = NULL;
1985 /* ******************* Utility functions ******************** */
1989 * We've had to delay a request for transmission to core, but now
1990 * we should be ready. Run it.
1992 * @param cls the 'struct ConnectedPeer' for which a request was delayed
1993 * @param tc task context (unused)
1996 delayed_transmission_request (void *cls,
1997 const struct GNUNET_SCHEDULER_TaskContext *tc)
1999 struct ConnectedPeer *cp = cls;
2000 struct GNUNET_PeerIdentity pid;
2001 struct PendingMessage *pm;
2003 pm = cp->pending_messages_head;
2004 cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
2005 GNUNET_assert (cp->cth == NULL);
2008 GNUNET_PEER_resolve (cp->pid,
2010 cp->last_transmission_request_start = GNUNET_TIME_absolute_get ();
2011 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
2013 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
2022 * Transmit messages by copying it to the target buffer
2023 * "buf". "buf" will be NULL and "size" zero if the socket was closed
2024 * for writing in the meantime. In that case, do nothing
2025 * (the disconnect or shutdown handler will take care of the rest).
2026 * If we were able to transmit messages and there are still more
2027 * pending, ask core again for further calls to this function.
2029 * @param cls closure, pointer to the 'struct ConnectedPeer*'
2030 * @param size number of bytes available in buf
2031 * @param buf where the callee should write the message
2032 * @return number of bytes written to buf
2035 transmit_to_peer (void *cls,
2036 size_t size, void *buf)
2038 struct ConnectedPeer *cp = cls;
2040 struct PendingMessage *pm;
2041 struct PendingMessage *next_pm;
2042 struct GNUNET_TIME_Absolute now;
2043 struct GNUNET_TIME_Relative min_delay;
2044 struct MigrationReadyBlock *mb;
2045 struct MigrationReadyBlock *next;
2046 struct PutMessage migm;
2049 struct GNUNET_PeerIdentity pid;
2055 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2056 "Dropping message, core too busy.\n");
2058 GNUNET_LOAD_update (cp->transmission_delay,
2062 GNUNET_LOAD_update (cp->transmission_delay,
2063 GNUNET_TIME_absolute_get_duration (cp->last_transmission_request_start).value);
2064 now = GNUNET_TIME_absolute_get ();
2066 min_delay = GNUNET_TIME_UNIT_FOREVER_REL;
2067 next_pm = cp->pending_messages_head;
2068 while ( (NULL != (pm = next_pm) ) &&
2069 (pm->msize <= size) )
2072 if (pm->delay_until.value > now.value)
2074 min_delay = GNUNET_TIME_relative_min (min_delay,
2075 GNUNET_TIME_absolute_get_remaining (pm->delay_until));
2078 memcpy (&cbuf[msize], &pm[1], pm->msize);
2081 if (NULL == pm->pml)
2083 GNUNET_CONTAINER_DLL_remove (cp->pending_messages_head,
2084 cp->pending_messages_tail,
2086 cp->pending_requests--;
2088 destroy_pending_message (pm, cp->pid);
2091 min_delay = GNUNET_TIME_UNIT_ZERO;
2092 if (NULL != cp->pending_messages_head)
2094 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == cp->delayed_transmission_request_task);
2095 cp->delayed_transmission_request_task
2096 = GNUNET_SCHEDULER_add_delayed (sched,
2098 &delayed_transmission_request,
2103 GNUNET_PEER_resolve (cp->pid,
2106 while (NULL != (mb = next))
2109 for (i=0;i<MIGRATION_LIST_SIZE;i++)
2111 if ( (cp->pid == mb->target_list[i]) &&
2112 (mb->size + sizeof (migm) <= size) )
2114 GNUNET_PEER_change_rc (mb->target_list[i], -1);
2115 mb->target_list[i] = 0;
2117 memset (&migm, 0, sizeof (migm));
2118 migm.header.size = htons (sizeof (migm) + mb->size);
2119 migm.header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2120 migm.type = htonl (mb->type);
2121 migm.expiration = GNUNET_TIME_absolute_hton (mb->expiration);
2122 memcpy (&cbuf[msize], &migm, sizeof (migm));
2123 msize += sizeof (migm);
2124 size -= sizeof (migm);
2125 memcpy (&cbuf[msize], &mb[1], mb->size);
2129 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2130 "Pushing migration block `%s' (%u bytes) to `%s'\n",
2131 GNUNET_h2s (&mb->query),
2132 (unsigned int) mb->size,
2140 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2141 "Migration block `%s' (%u bytes) is not on migration list for peer `%s'\n",
2142 GNUNET_h2s (&mb->query),
2143 (unsigned int) mb->size,
2148 if ( (mb->used_targets >= MIGRATION_TARGET_COUNT) ||
2149 (mb->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers)) )
2151 delete_migration_block (mb);
2152 consider_migration_gathering ();
2155 consider_migration (NULL,
2160 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2161 "Transmitting %u bytes to peer with PID %u\n",
2162 (unsigned int) msize,
2163 (unsigned int) cp->pid);
2170 * Add a message to the set of pending messages for the given peer.
2172 * @param cp peer to send message to
2173 * @param pm message to queue
2174 * @param pr request on which behalf this message is being queued
2177 add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
2178 struct PendingMessage *pm,
2179 struct PendingRequest *pr)
2181 struct PendingMessage *pos;
2182 struct PendingMessageList *pml;
2183 struct GNUNET_PeerIdentity pid;
2185 GNUNET_assert (pm->next == NULL);
2186 GNUNET_assert (pm->pml == NULL);
2189 pml = GNUNET_malloc (sizeof (struct PendingMessageList));
2194 GNUNET_CONTAINER_DLL_insert (pr->pending_head,
2198 pos = cp->pending_messages_head;
2199 while ( (pos != NULL) &&
2200 (pm->priority < pos->priority) )
2202 GNUNET_CONTAINER_DLL_insert_after (cp->pending_messages_head,
2203 cp->pending_messages_tail,
2206 cp->pending_requests++;
2207 if (cp->pending_requests > MAX_QUEUE_PER_PEER)
2209 GNUNET_STATISTICS_update (stats,
2210 gettext_noop ("# P2P searches discarded (queue length bound)"),
2213 destroy_pending_message (cp->pending_messages_tail, 0);
2215 GNUNET_PEER_resolve (cp->pid, &pid);
2216 if (NULL != cp->cth)
2218 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
2221 if (cp->delayed_transmission_request_task != GNUNET_SCHEDULER_NO_TASK)
2223 GNUNET_SCHEDULER_cancel (sched, cp->delayed_transmission_request_task);
2224 cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
2226 /* need to schedule transmission */
2227 cp->last_transmission_request_start = GNUNET_TIME_absolute_get ();
2228 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
2229 cp->pending_messages_head->priority,
2232 cp->pending_messages_head->msize,
2235 if (cp->cth == NULL)
2238 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2239 "Failed to schedule transmission with core!\n");
2241 GNUNET_STATISTICS_update (stats,
2242 gettext_noop ("# CORE transmission failures"),
2250 * Test if the DATABASE (GET) load on this peer is too high
2251 * to even consider processing the query at
2254 * @return GNUNET_YES if the load is too high to do anything (load high)
2255 * GNUNET_NO to process normally (load normal)
2256 * GNUNET_SYSERR to process for free (load low)
2259 test_get_load_too_high (uint32_t priority)
2263 ld = GNUNET_LOAD_get_load (datastore_get_load);
2266 GNUNET_STATISTICS_update (stats,
2267 gettext_noop ("# requests done for free (low load)"),
2270 return GNUNET_SYSERR;
2274 GNUNET_STATISTICS_update (stats,
2275 gettext_noop ("# requests done for a price (normal load)"),
2280 GNUNET_STATISTICS_update (stats,
2281 gettext_noop ("# priority determined to be high"),
2291 * Test if the DATABASE (PUT) load on this peer is too high
2292 * to even consider processing the query at
2295 * @return GNUNET_YES if the load is too high to do anything (load high)
2296 * GNUNET_NO to process normally (load normal or low)
2299 test_put_load_too_high (uint32_t priority)
2303 if (GNUNET_LOAD_get_average (datastore_put_load) < 50)
2304 return GNUNET_NO; /* very fast */
2305 ld = GNUNET_LOAD_get_load (datastore_put_load);
2306 if (ld < 2.0 * (1 + priority))
2308 GNUNET_STATISTICS_update (stats,
2309 gettext_noop ("# storage requests dropped due to high load"),
2316 /* ******************* Pending Request Refresh Task ******************** */
2321 * We use a random delay to make the timing of requests less
2322 * predictable. This function returns such a random delay. We add a base
2323 * delay of MAX_CORK_DELAY (1s).
2325 * FIXME: make schedule dependent on the specifics of the request?
2326 * Or bandwidth and number of connected peers and load?
2328 * @return random delay to use for some request, between 1s and 1000+TTL_DECREMENT ms
2330 static struct GNUNET_TIME_Relative
2331 get_processing_delay ()
2334 GNUNET_TIME_relative_add (GNUNET_CONSTANTS_MAX_CORK_DELAY,
2335 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
2336 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2342 * We're processing a GET request from another peer and have decided
2343 * to forward it to other peers. This function is called periodically
2344 * and should forward the request to other peers until we have all
2345 * possible replies. If we have transmitted the *only* reply to
2346 * the initiator we should destroy the pending request. If we have
2347 * many replies in the queue to the initiator, we should delay sending
2348 * out more queries until the reply queue has shrunk some.
2350 * @param cls our "struct ProcessGetContext *"
2354 forward_request_task (void *cls,
2355 const struct GNUNET_SCHEDULER_TaskContext *tc);
2359 * Function called after we either failed or succeeded
2360 * at transmitting a query to a peer.
2362 * @param cls the requests "struct PendingRequest*"
2363 * @param tpid ID of receiving peer, 0 on transmission error
2366 transmit_query_continuation (void *cls,
2367 GNUNET_PEER_Id tpid)
2369 struct PendingRequest *pr = cls;
2372 GNUNET_STATISTICS_update (stats,
2373 gettext_noop ("# queries scheduled for forwarding"),
2379 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2380 "Transmission of request failed, will try again later.\n");
2382 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2383 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
2384 get_processing_delay (),
2385 &forward_request_task,
2390 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2391 "Transmitted query `%s'\n",
2392 GNUNET_h2s (&pr->query));
2394 GNUNET_STATISTICS_update (stats,
2395 gettext_noop ("# queries forwarded"),
2398 for (i=0;i<pr->used_targets_off;i++)
2399 if (pr->used_targets[i].pid == tpid)
2400 break; /* found match! */
2401 if (i == pr->used_targets_off)
2403 /* need to create new entry */
2404 if (pr->used_targets_off == pr->used_targets_size)
2405 GNUNET_array_grow (pr->used_targets,
2406 pr->used_targets_size,
2407 pr->used_targets_size * 2 + 2);
2408 GNUNET_PEER_change_rc (tpid, 1);
2409 pr->used_targets[pr->used_targets_off].pid = tpid;
2410 pr->used_targets[pr->used_targets_off].num_requests = 0;
2411 i = pr->used_targets_off++;
2413 pr->used_targets[i].last_request_time = GNUNET_TIME_absolute_get ();
2414 pr->used_targets[i].num_requests++;
2415 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2416 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
2417 get_processing_delay (),
2418 &forward_request_task,
2424 * How many bytes should a bloomfilter be if we have already seen
2425 * entry_count responses? Note that BLOOMFILTER_K gives us the number
2426 * of bits set per entry. Furthermore, we should not re-size the
2427 * filter too often (to keep it cheap).
2429 * Since other peers will also add entries but not resize the filter,
2430 * we should generally pick a slightly larger size than what the
2431 * strict math would suggest.
2433 * @return must be a power of two and smaller or equal to 2^15.
2436 compute_bloomfilter_size (unsigned int entry_count)
2439 unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
2440 uint16_t max = 1 << 15;
2442 if (entry_count > max)
2445 while ((size < max) && (size < ideal))
2454 * Recalculate our bloom filter for filtering replies. This function
2455 * will create a new bloom filter from scratch, so it should only be
2456 * called if we have no bloomfilter at all (and hence can create a
2457 * fresh one of minimal size without problems) OR if our peer is the
2458 * initiator (in which case we may resize to larger than mimimum size).
2460 * @param pr request for which the BF is to be recomputed
2463 refresh_bloomfilter (struct PendingRequest *pr)
2467 GNUNET_HashCode mhash;
2469 nsize = compute_bloomfilter_size (pr->replies_seen_off);
2470 if (nsize == pr->bf_size)
2471 return; /* size not changed */
2473 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
2474 pr->bf_size = nsize;
2475 pr->mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
2476 pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
2479 for (i=0;i<pr->replies_seen_off;i++)
2481 GNUNET_BLOCK_mingle_hash (&pr->replies_seen[i],
2484 GNUNET_CONTAINER_bloomfilter_add (pr->bf, &mhash);
2490 * Function called after we've tried to reserve a certain amount of
2491 * bandwidth for a reply. Check if we succeeded and if so send our
2494 * @param cls the requests "struct PendingRequest*"
2495 * @param peer identifies the peer
2496 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
2497 * @param bpm_out set to the current bandwidth limit (sending) for this peer
2498 * @param amount set to the amount that was actually reserved or unreserved
2499 * @param preference current traffic preference for the given peer
2502 target_reservation_cb (void *cls,
2504 GNUNET_PeerIdentity * peer,
2505 struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
2506 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
2508 uint64_t preference)
2510 struct PendingRequest *pr = cls;
2511 struct ConnectedPeer *cp;
2512 struct PendingMessage *pm;
2513 struct GetMessage *gm;
2514 GNUNET_HashCode *ext;
2525 /* error in communication with core, try again later */
2526 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2527 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
2528 get_processing_delay (),
2529 &forward_request_task,
2533 /* (3) transmit, update ttl/priority */
2534 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2538 /* Peer must have just left */
2540 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2541 "Selected peer disconnected!\n");
2543 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2544 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
2545 get_processing_delay (),
2546 &forward_request_task,
2550 no_route = GNUNET_NO;
2556 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2557 "Failed to reserve bandwidth for reply (got %d/%u bytes only)!\n",
2561 GNUNET_STATISTICS_update (stats,
2562 gettext_noop ("# reply bandwidth reservation requests failed"),
2565 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2566 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
2567 get_processing_delay (),
2568 &forward_request_task,
2570 return; /* this target round failed */
2572 no_route = GNUNET_YES;
2575 GNUNET_STATISTICS_update (stats,
2576 gettext_noop ("# queries scheduled for forwarding"),
2579 for (i=0;i<pr->used_targets_off;i++)
2580 if (pr->used_targets[i].pid == cp->pid)
2582 GNUNET_STATISTICS_update (stats,
2583 gettext_noop ("# queries retransmitted to same target"),
2589 /* build message and insert message into priority queue */
2591 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2592 "Forwarding request `%s' to `%4s'!\n",
2593 GNUNET_h2s (&pr->query),
2598 if (GNUNET_YES == no_route)
2600 bm |= GET_MESSAGE_BIT_RETURN_TO;
2603 if (pr->namespace != NULL)
2605 bm |= GET_MESSAGE_BIT_SKS_NAMESPACE;
2608 if (pr->target_pid != 0)
2610 bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
2613 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
2614 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
2615 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
2617 gm = (struct GetMessage*) &pm[1];
2618 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
2619 gm->header.size = htons (msize);
2620 gm->type = htonl (pr->type);
2621 pr->remaining_priority /= 2;
2622 gm->priority = htonl (pr->remaining_priority);
2623 gm->ttl = htonl (pr->ttl);
2624 gm->filter_mutator = htonl(pr->mingle);
2625 gm->hash_bitmap = htonl (bm);
2626 gm->query = pr->query;
2627 ext = (GNUNET_HashCode*) &gm[1];
2629 if (GNUNET_YES == no_route)
2630 GNUNET_PEER_resolve (pr->cp->pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
2631 if (pr->namespace != NULL)
2632 memcpy (&ext[k++], pr->namespace, sizeof (GNUNET_HashCode));
2633 if (pr->target_pid != 0)
2634 GNUNET_PEER_resolve (pr->target_pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
2635 bfdata = (char *) &ext[k];
2637 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
2640 pm->cont = &transmit_query_continuation;
2642 cp->last_request_times[(cp->last_request_times_off++) % MAX_QUEUE_PER_PEER] = GNUNET_TIME_absolute_get ();
2643 add_to_pending_messages_for_peer (cp, pm, pr);
2648 * Closure used for "target_peer_select_cb".
2650 struct PeerSelectionContext
2653 * The request for which we are selecting
2656 struct PendingRequest *pr;
2659 * Current "prime" target.
2661 struct GNUNET_PeerIdentity target;
2664 * How much do we like this target?
2666 double target_score;
2672 * Function called for each connected peer to determine
2673 * which one(s) would make good targets for forwarding.
2675 * @param cls closure (struct PeerSelectionContext)
2676 * @param key current key code (peer identity)
2677 * @param value value in the hash map (struct ConnectedPeer)
2678 * @return GNUNET_YES if we should continue to
2683 target_peer_select_cb (void *cls,
2684 const GNUNET_HashCode * key,
2687 struct PeerSelectionContext *psc = cls;
2688 struct ConnectedPeer *cp = value;
2689 struct PendingRequest *pr = psc->pr;
2690 struct GNUNET_TIME_Relative delay;
2695 /* 1) check that this peer is not the initiator */
2699 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2700 "Skipping initiator in forwarding selection\n");
2702 return GNUNET_YES; /* skip */
2705 /* 2) check if we have already (recently) forwarded to this peer */
2706 /* 2a) this particular request */
2708 for (i=0;i<pr->used_targets_off;i++)
2709 if (pr->used_targets[i].pid == cp->pid)
2711 pc = pr->used_targets[i].num_requests;
2712 GNUNET_assert (pc > 0);
2713 if (0 != GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2714 RETRY_PROBABILITY_INV * pc))
2717 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2718 "NOT re-trying query that was previously transmitted %u times\n",
2721 return GNUNET_YES; /* skip */
2728 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2729 "Re-trying query that was previously transmitted %u times to this peer\n",
2733 /* 2b) many other requests to this peer */
2734 delay = GNUNET_TIME_absolute_get_duration (cp->last_request_times[cp->last_request_times_off % MAX_QUEUE_PER_PEER]);
2735 if (delay.value <= cp->avg_delay.value)
2738 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2739 "NOT sending query since we send %u others to this peer in the last %llums\n",
2741 cp->avg_delay.value);
2743 return GNUNET_YES; /* skip */
2746 /* 3) calculate how much we'd like to forward to this peer,
2747 starting with a random value that is strong enough
2748 to at least give any peer a chance sometimes
2749 (compared to the other factors that come later) */
2750 /* 3a) count successful (recent) routes from cp for same source */
2753 score = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2754 P2P_SUCCESS_LIST_SIZE);
2755 for (i=0;i<P2P_SUCCESS_LIST_SIZE;i++)
2756 if (cp->last_p2p_replies[i] == pr->cp->pid)
2757 score += 1.0; /* likely successful based on hot path */
2761 score = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2762 CS2P_SUCCESS_LIST_SIZE);
2763 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
2764 if (cp->last_client_replies[i] == pr->client_request_list->client_list->client)
2765 score += 1.0; /* likely successful based on hot path */
2767 /* 3b) include latency */
2768 if (cp->avg_delay.value < 4 * TTL_DECREMENT)
2769 score += 1.0; /* likely fast based on latency */
2770 /* 3c) include priorities */
2771 if (cp->avg_priority <= pr->remaining_priority / 2.0)
2772 score += 1.0; /* likely successful based on priorities */
2773 /* 3d) penalize for queue size */
2774 score -= (2.0 * cp->pending_requests / (double) MAX_QUEUE_PER_PEER);
2775 /* 3e) include peer proximity */
2776 score -= (2.0 * (GNUNET_CRYPTO_hash_distance_u32 (key,
2777 &pr->query)) / (double) UINT32_MAX);
2778 /* 4) super-bonus for being the known target */
2779 if (pr->target_pid == cp->pid)
2781 /* store best-fit in closure */
2783 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2784 "Peer `%s' gets score %f for forwarding query, max is %f\n",
2789 score++; /* avoid zero */
2790 if (score > psc->target_score)
2792 psc->target_score = score;
2793 psc->target.hashPubKey = *key;
2800 * The priority level imposes a bound on the maximum
2801 * value for the ttl that can be requested.
2803 * @param ttl_in requested ttl
2804 * @param prio given priority
2805 * @return ttl_in if ttl_in is below the limit,
2806 * otherwise the ttl-limit for the given priority
2809 bound_ttl (int32_t ttl_in, uint32_t prio)
2811 unsigned long long allowed;
2815 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
2816 if (ttl_in > allowed)
2818 if (allowed >= (1 << 30))
2827 * Iterator called on each result obtained for a DHT
2828 * operation that expects a reply
2830 * @param cls closure
2831 * @param exp when will this value expire
2832 * @param key key of the result
2833 * @param get_path NULL-terminated array of pointers
2834 * to the peers on reverse GET path (or NULL if not recorded)
2835 * @param put_path NULL-terminated array of pointers
2836 * to the peers on the PUT path (or NULL if not recorded)
2837 * @param type type of the result
2838 * @param size number of bytes in data
2839 * @param data pointer to the result data
2842 process_dht_reply (void *cls,
2843 struct GNUNET_TIME_Absolute exp,
2844 const GNUNET_HashCode * key,
2845 const struct GNUNET_PeerIdentity * const *get_path,
2846 const struct GNUNET_PeerIdentity * const *put_path,
2847 enum GNUNET_BLOCK_Type type,
2853 * We're processing a GET request and have decided
2854 * to forward it to other peers. This function is called periodically
2855 * and should forward the request to other peers until we have all
2856 * possible replies. If we have transmitted the *only* reply to
2857 * the initiator we should destroy the pending request. If we have
2858 * many replies in the queue to the initiator, we should delay sending
2859 * out more queries until the reply queue has shrunk some.
2861 * @param cls our "struct ProcessGetContext *"
2865 forward_request_task (void *cls,
2866 const struct GNUNET_SCHEDULER_TaskContext *tc)
2868 struct PendingRequest *pr = cls;
2869 struct PeerSelectionContext psc;
2870 struct ConnectedPeer *cp;
2871 struct GNUNET_TIME_Relative delay;
2873 pr->task = GNUNET_SCHEDULER_NO_TASK;
2874 if (pr->irc != NULL)
2877 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2878 "Forwarding of query `%s' not attempted due to pending local lookup!\n",
2879 GNUNET_h2s (&pr->query));
2881 return; /* already pending */
2883 if (GNUNET_YES == pr->local_only)
2884 return; /* configured to not do P2P search */
2886 if ( (0 == pr->anonymity_level) &&
2887 (GNUNET_YES != pr->forward_only) &&
2888 (pr->type != GNUNET_BLOCK_TYPE_FS_DBLOCK) &&
2889 (pr->type != GNUNET_BLOCK_TYPE_FS_IBLOCK) )
2891 pr->dht_get = GNUNET_DHT_get_start (dht_handle,
2892 GNUNET_TIME_UNIT_FOREVER_REL,
2899 (pr->namespace != NULL) ? sizeof (GNUNET_HashCode) : 0,
2903 /* (1) select target */
2905 psc.target_score = -DBL_MAX;
2906 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
2907 &target_peer_select_cb,
2909 if (psc.target_score == -DBL_MAX)
2911 delay = get_processing_delay ();
2913 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2914 "No peer selected for forwarding of query `%s', will try again in %llu ms!\n",
2915 GNUNET_h2s (&pr->query),
2918 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
2920 &forward_request_task,
2922 return; /* nobody selected */
2924 /* (3) update TTL/priority */
2925 if (pr->client_request_list != NULL)
2927 /* FIXME: use better algorithm!? */
2928 if (0 == GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2931 /* bound priority we use by priorities we see from other peers
2932 rounded up (must round up so that we can see non-zero
2933 priorities, but round up as little as possible to make it
2934 plausible that we forwarded another peers request) */
2935 if (pr->priority > current_priorities + 1.0)
2936 pr->priority = (uint32_t) current_priorities + 1.0;
2937 pr->ttl = bound_ttl (pr->ttl + TTL_DECREMENT * 2,
2940 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2941 "Trying query `%s' with priority %u and TTL %d.\n",
2942 GNUNET_h2s (&pr->query),
2948 /* (3) reserve reply bandwidth */
2949 if (GNUNET_NO == pr->forward_only)
2951 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2952 &psc.target.hashPubKey);
2953 GNUNET_assert (NULL != cp);
2954 pr->irc = GNUNET_CORE_peer_change_preference (sched, cfg,
2956 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
2957 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
2960 &target_reservation_cb,
2962 cp->inc_preference = 0;
2966 /* force forwarding */
2967 static struct GNUNET_BANDWIDTH_Value32NBO zerobw;
2968 target_reservation_cb (pr, &psc.target,
2969 zerobw, zerobw, 0, 0.0);
2974 /* **************************** P2P PUT Handling ************************ */
2978 * Function called after we either failed or succeeded
2979 * at transmitting a reply to a peer.
2981 * @param cls the requests "struct PendingRequest*"
2982 * @param tpid ID of receiving peer, 0 on transmission error
2985 transmit_reply_continuation (void *cls,
2986 GNUNET_PEER_Id tpid)
2988 struct PendingRequest *pr = cls;
2992 case GNUNET_BLOCK_TYPE_FS_DBLOCK:
2993 case GNUNET_BLOCK_TYPE_FS_IBLOCK:
2994 /* only one reply expected, done with the request! */
2995 destroy_pending_request (pr);
2997 case GNUNET_BLOCK_TYPE_ANY:
2998 case GNUNET_BLOCK_TYPE_FS_KBLOCK:
2999 case GNUNET_BLOCK_TYPE_FS_SBLOCK:
3009 * Transmit the given message by copying it to the target buffer
3010 * "buf". "buf" will be NULL and "size" zero if the socket was closed
3011 * for writing in the meantime. In that case, do nothing
3012 * (the disconnect or shutdown handler will take care of the rest).
3013 * If we were able to transmit messages and there are still more
3014 * pending, ask core again for further calls to this function.
3016 * @param cls closure, pointer to the 'struct ClientList*'
3017 * @param size number of bytes available in buf
3018 * @param buf where the callee should write the message
3019 * @return number of bytes written to buf
3022 transmit_to_client (void *cls,
3023 size_t size, void *buf)
3025 struct ClientList *cl = cls;
3027 struct ClientResponseMessage *creply;
3034 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3035 "Not sending reply, client communication problem.\n");
3040 while ( (NULL != (creply = cl->res_head) ) &&
3041 (creply->msize <= size) )
3043 memcpy (&cbuf[msize], &creply[1], creply->msize);
3044 msize += creply->msize;
3045 size -= creply->msize;
3046 GNUNET_CONTAINER_DLL_remove (cl->res_head,
3049 GNUNET_free (creply);
3052 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
3054 GNUNET_TIME_UNIT_FOREVER_REL,
3055 &transmit_to_client,
3058 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3059 "Transmitted %u bytes to client\n",
3060 (unsigned int) msize);
3067 * Closure for "process_reply" function.
3069 struct ProcessReplyClosure
3072 * The data for the reply.
3077 * Who gave us this reply? NULL for local host (or DHT)
3079 struct ConnectedPeer *sender;
3082 * When the reply expires.
3084 struct GNUNET_TIME_Absolute expiration;
3092 * Type of the block.
3094 enum GNUNET_BLOCK_Type type;
3097 * How much was this reply worth to us?
3102 * Evaluation result (returned).
3104 enum GNUNET_BLOCK_EvaluationResult eval;
3107 * Did we finish processing the associated request?
3112 * Did we find a matching request?
3119 * We have received a reply; handle it!
3121 * @param cls response (struct ProcessReplyClosure)
3122 * @param key our query
3123 * @param value value in the hash map (info about the query)
3124 * @return GNUNET_YES (we should continue to iterate)
3127 process_reply (void *cls,
3128 const GNUNET_HashCode * key,
3131 struct ProcessReplyClosure *prq = cls;
3132 struct PendingRequest *pr = value;
3133 struct PendingMessage *reply;
3134 struct ClientResponseMessage *creply;
3135 struct ClientList *cl;
3136 struct PutMessage *pm;
3137 struct ConnectedPeer *cp;
3138 struct GNUNET_TIME_Relative cur_delay;
3140 struct GNUNET_TIME_Relative art_delay;
3146 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3147 "Matched result (type %u) for query `%s' with pending request\n",
3148 (unsigned int) prq->type,
3151 GNUNET_STATISTICS_update (stats,
3152 gettext_noop ("# replies received and matched"),
3155 if (prq->sender != NULL)
3157 for (i=0;i<pr->used_targets_off;i++)
3158 if (pr->used_targets[i].pid == prq->sender->pid)
3160 if (i < pr->used_targets_off)
3162 cur_delay = GNUNET_TIME_absolute_get_duration (pr->used_targets[i].last_request_time);
3163 prq->sender->avg_delay.value
3164 = (prq->sender->avg_delay.value *
3165 (RUNAVG_DELAY_N - 1) + cur_delay.value) / RUNAVG_DELAY_N;
3166 prq->sender->avg_priority
3167 = (prq->sender->avg_priority *
3168 (RUNAVG_DELAY_N - 1) + pr->priority) / (double) RUNAVG_DELAY_N;
3172 GNUNET_PEER_change_rc (prq->sender->last_p2p_replies
3173 [prq->sender->last_p2p_replies_woff % P2P_SUCCESS_LIST_SIZE],
3175 GNUNET_PEER_change_rc (pr->cp->pid, 1);
3176 prq->sender->last_p2p_replies
3177 [(prq->sender->last_p2p_replies_woff++) % P2P_SUCCESS_LIST_SIZE]
3182 if (NULL != prq->sender->last_client_replies
3183 [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE])
3184 GNUNET_SERVER_client_drop (prq->sender->last_client_replies
3185 [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE]);
3186 prq->sender->last_client_replies
3187 [(prq->sender->last_client_replies_woff++) % CS2P_SUCCESS_LIST_SIZE]
3188 = pr->client_request_list->client_list->client;
3189 GNUNET_SERVER_client_keep (pr->client_request_list->client_list->client);
3192 prq->eval = GNUNET_BLOCK_evaluate (block_ctx,
3197 pr->namespace, (pr->namespace != NULL) ? sizeof (GNUNET_HashCode) : 0,
3202 case GNUNET_BLOCK_EVALUATION_OK_MORE:
3204 case GNUNET_BLOCK_EVALUATION_OK_LAST:
3205 while (NULL != pr->pending_head)
3206 destroy_pending_message_list_entry (pr->pending_head);
3209 if (pr->client_request_list != NULL)
3210 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
3212 GNUNET_DATASTORE_cancel (pr->qe);
3215 pr->do_remove = GNUNET_YES;
3216 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
3218 GNUNET_SCHEDULER_cancel (sched,
3220 pr->task = GNUNET_SCHEDULER_NO_TASK;
3222 GNUNET_break (GNUNET_YES ==
3223 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
3226 GNUNET_LOAD_update (rt_entry_lifetime,
3227 GNUNET_TIME_absolute_get_duration (pr->start_time).value);
3229 case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
3230 GNUNET_STATISTICS_update (stats,
3231 gettext_noop ("# duplicate replies discarded (bloomfilter)"),
3235 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3236 "Duplicate response `%s', discarding.\n",
3237 GNUNET_h2s (&mhash));
3239 return GNUNET_YES; /* duplicate */
3240 case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
3241 return GNUNET_YES; /* wrong namespace */
3242 case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
3245 case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
3248 case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
3249 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3250 _("Unsupported block type %u\n"),
3254 if (pr->client_request_list != NULL)
3256 if (pr->replies_seen_size == pr->replies_seen_off)
3257 GNUNET_array_grow (pr->replies_seen,
3258 pr->replies_seen_size,
3259 pr->replies_seen_size * 2 + 4);
3260 GNUNET_CRYPTO_hash (prq->data,
3262 &pr->replies_seen[pr->replies_seen_off++]);
3263 refresh_bloomfilter (pr);
3265 if (NULL == prq->sender)
3268 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3269 "Found result for query `%s' in local datastore\n",
3272 GNUNET_STATISTICS_update (stats,
3273 gettext_noop ("# results found locally"),
3277 prq->priority += pr->remaining_priority;
3278 pr->remaining_priority = 0;
3279 pr->results_found++;
3280 prq->request_found = GNUNET_YES;
3281 if (NULL != pr->client_request_list)
3283 GNUNET_STATISTICS_update (stats,
3284 gettext_noop ("# replies received for local clients"),
3287 cl = pr->client_request_list->client_list;
3288 msize = sizeof (struct PutMessage) + prq->size;
3289 creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
3290 creply->msize = msize;
3291 creply->client_list = cl;
3292 GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
3296 pm = (struct PutMessage*) &creply[1];
3297 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
3298 pm->header.size = htons (msize);
3299 pm->type = htonl (prq->type);
3300 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
3301 memcpy (&pm[1], prq->data, prq->size);
3305 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3306 "Transmitting result for query `%s' to client\n",
3309 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
3311 GNUNET_TIME_UNIT_FOREVER_REL,
3312 &transmit_to_client,
3315 GNUNET_break (cl->th != NULL);
3318 prq->finished = GNUNET_YES;
3319 destroy_pending_request (pr);
3326 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3327 "Transmitting result for query `%s' to other peer (PID=%u)\n",
3329 (unsigned int) cp->pid);
3331 GNUNET_STATISTICS_update (stats,
3332 gettext_noop ("# replies received for other peers"),
3335 msize = sizeof (struct PutMessage) + prq->size;
3336 reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
3337 reply->cont = &transmit_reply_continuation;
3338 reply->cont_cls = pr;
3340 art_delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
3341 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3344 = GNUNET_TIME_relative_to_absolute (art_delay);
3345 GNUNET_STATISTICS_update (stats,
3346 gettext_noop ("cummulative artificial delay introduced (ms)"),
3350 reply->msize = msize;
3351 reply->priority = UINT32_MAX; /* send replies first! */
3352 pm = (struct PutMessage*) &reply[1];
3353 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
3354 pm->header.size = htons (msize);
3355 pm->type = htonl (prq->type);
3356 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
3357 memcpy (&pm[1], prq->data, prq->size);
3358 add_to_pending_messages_for_peer (cp, reply, pr);
3365 * Iterator called on each result obtained for a DHT
3366 * operation that expects a reply
3368 * @param cls closure
3369 * @param exp when will this value expire
3370 * @param key key of the result
3371 * @param get_path NULL-terminated array of pointers
3372 * to the peers on reverse GET path (or NULL if not recorded)
3373 * @param put_path NULL-terminated array of pointers
3374 * to the peers on the PUT path (or NULL if not recorded)
3375 * @param type type of the result
3376 * @param size number of bytes in data
3377 * @param data pointer to the result data
3380 process_dht_reply (void *cls,
3381 struct GNUNET_TIME_Absolute exp,
3382 const GNUNET_HashCode * key,
3383 const struct GNUNET_PeerIdentity * const *get_path,
3384 const struct GNUNET_PeerIdentity * const *put_path,
3385 enum GNUNET_BLOCK_Type type,
3389 struct PendingRequest *pr = cls;
3390 struct ProcessReplyClosure prq;
3392 memset (&prq, 0, sizeof (prq));
3394 prq.expiration = exp;
3397 process_reply (&prq, key, pr);
3403 * Continuation called to notify client about result of the
3406 * @param cls closure
3407 * @param success GNUNET_SYSERR on failure
3408 * @param msg NULL on success, otherwise an error message
3411 put_migration_continuation (void *cls,
3415 struct GNUNET_TIME_Absolute *start = cls;
3416 struct GNUNET_TIME_Relative delay;
3418 delay = GNUNET_TIME_absolute_get_duration (*start);
3419 GNUNET_free (start);
3420 GNUNET_LOAD_update (datastore_put_load,
3422 if (GNUNET_OK == success)
3424 GNUNET_STATISTICS_update (stats,
3425 gettext_noop ("# datastore 'put' failures"),
3432 * Handle P2P "PUT" message.
3434 * @param cls closure, always NULL
3435 * @param other the other peer involved (sender or receiver, NULL
3436 * for loopback messages where we are both sender and receiver)
3437 * @param message the actual message
3438 * @param latency reported latency of the connection with 'other'
3439 * @param distance reported distance (DV) to 'other'
3440 * @return GNUNET_OK to keep the connection open,
3441 * GNUNET_SYSERR to close it (signal serious error)
3444 handle_p2p_put (void *cls,
3445 const struct GNUNET_PeerIdentity *other,
3446 const struct GNUNET_MessageHeader *message,
3447 struct GNUNET_TIME_Relative latency,
3450 const struct PutMessage *put;
3453 enum GNUNET_BLOCK_Type type;
3454 struct GNUNET_TIME_Absolute expiration;
3455 GNUNET_HashCode query;
3456 struct ProcessReplyClosure prq;
3457 struct GNUNET_TIME_Absolute *start;
3458 struct GNUNET_TIME_Relative block_time;
3460 struct ConnectedPeer *cp;
3461 struct PendingMessage *pm;
3462 struct MigrationStopMessage *msm;
3464 msize = ntohs (message->size);
3465 if (msize < sizeof (struct PutMessage))
3468 return GNUNET_SYSERR;
3470 put = (const struct PutMessage*) message;
3471 dsize = msize - sizeof (struct PutMessage);
3472 type = ntohl (put->type);
3473 expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
3475 if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
3476 return GNUNET_SYSERR;
3478 GNUNET_BLOCK_get_key (block_ctx,
3484 GNUNET_break_op (0);
3485 return GNUNET_SYSERR;
3488 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3489 "Received result for query `%s' from peer `%4s'\n",
3490 GNUNET_h2s (&query),
3491 GNUNET_i2s (other));
3493 GNUNET_STATISTICS_update (stats,
3494 gettext_noop ("# replies received (overall)"),
3497 /* now, lookup 'query' */
3498 prq.data = (const void*) &put[1];
3500 prq.sender = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3501 &other->hashPubKey);
3506 prq.expiration = expiration;
3508 prq.finished = GNUNET_NO;
3509 prq.request_found = GNUNET_NO;
3510 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
3514 if (prq.sender != NULL)
3516 prq.sender->inc_preference += CONTENT_BANDWIDTH_VALUE + 1000 * prq.priority;
3517 prq.sender->trust += prq.priority;
3519 if ( (GNUNET_YES == active_migration) &&
3520 (GNUNET_NO == test_put_load_too_high (prq.priority)) )
3523 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3524 "Replicating result for query `%s' with priority %u\n",
3525 GNUNET_h2s (&query),
3528 start = GNUNET_malloc (sizeof (struct GNUNET_TIME_Absolute));
3529 *start = GNUNET_TIME_absolute_get ();
3530 GNUNET_DATASTORE_put (dsh,
3531 0, &query, dsize, &put[1],
3532 type, prq.priority, 1 /* anonymity */,
3534 1 + prq.priority, MAX_DATASTORE_QUEUE,
3535 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
3536 &put_migration_continuation,
3539 putl = GNUNET_LOAD_get_load (datastore_put_load);
3540 if ( (GNUNET_NO == prq.request_found) &&
3541 ( (GNUNET_YES != active_migration) ||
3542 (putl > 2.5 * (1 + prq.priority)) ) )
3544 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3545 &other->hashPubKey);
3546 if (GNUNET_TIME_absolute_get_duration (cp->last_migration_block).value < 5000)
3547 return GNUNET_OK; /* already blocked */
3548 /* We're too busy; send MigrationStop message! */
3549 if (GNUNET_YES != active_migration)
3550 putl = 1.0 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 5);
3551 block_time = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
3552 5000 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3553 (unsigned int) (60000 * putl * putl)));
3555 cp->last_migration_block = GNUNET_TIME_relative_to_absolute (block_time);
3556 pm = GNUNET_malloc (sizeof (struct PendingMessage) +
3557 sizeof (struct MigrationStopMessage));
3558 pm->msize = sizeof (struct MigrationStopMessage);
3559 pm->priority = UINT32_MAX;
3560 msm = (struct MigrationStopMessage*) &pm[1];
3561 msm->header.size = htons (sizeof (struct MigrationStopMessage));
3562 msm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP);
3563 msm->duration = GNUNET_TIME_relative_hton (block_time);
3564 add_to_pending_messages_for_peer (cp,
3573 * Handle P2P "MIGRATION_STOP" message.
3575 * @param cls closure, always NULL
3576 * @param other the other peer involved (sender or receiver, NULL
3577 * for loopback messages where we are both sender and receiver)
3578 * @param message the actual message
3579 * @param latency reported latency of the connection with 'other'
3580 * @param distance reported distance (DV) to 'other'
3581 * @return GNUNET_OK to keep the connection open,
3582 * GNUNET_SYSERR to close it (signal serious error)
3585 handle_p2p_migration_stop (void *cls,
3586 const struct GNUNET_PeerIdentity *other,
3587 const struct GNUNET_MessageHeader *message,
3588 struct GNUNET_TIME_Relative latency,
3591 struct ConnectedPeer *cp;
3592 const struct MigrationStopMessage *msm;
3594 msm = (const struct MigrationStopMessage*) message;
3595 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3596 &other->hashPubKey);
3602 cp->migration_blocked = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (msm->duration));
3608 /* **************************** P2P GET Handling ************************ */
3612 * Closure for 'check_duplicate_request_{peer,client}'.
3614 struct CheckDuplicateRequestClosure
3617 * The new request we should check if it already exists.
3619 const struct PendingRequest *pr;
3622 * Existing request found by the checker, NULL if none.
3624 struct PendingRequest *have;
3629 * Iterator over entries in the 'query_request_map' that
3630 * tries to see if we have the same request pending from
3631 * the same client already.
3633 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
3634 * @param key current key code (query, ignored, must match)
3635 * @param value value in the hash map (a 'struct PendingRequest'
3636 * that already exists)
3637 * @return GNUNET_YES if we should continue to
3638 * iterate (no match yet)
3639 * GNUNET_NO if not (match found).
3642 check_duplicate_request_client (void *cls,
3643 const GNUNET_HashCode * key,
3646 struct CheckDuplicateRequestClosure *cdc = cls;
3647 struct PendingRequest *have = value;
3649 if (have->client_request_list == NULL)
3651 if ( (cdc->pr->client_request_list->client_list->client == have->client_request_list->client_list->client) &&
3662 * We're processing (local) results for a search request
3663 * from another peer. Pass applicable results to the
3664 * peer and if we are done either clean up (operation
3665 * complete) or forward to other peers (more results possible).
3667 * @param cls our closure (struct LocalGetContext)
3668 * @param key key for the content
3669 * @param size number of bytes in data
3670 * @param data content stored
3671 * @param type type of the content
3672 * @param priority priority of the content
3673 * @param anonymity anonymity-level for the content
3674 * @param expiration expiration time for the content
3675 * @param uid unique identifier for the datum;
3676 * maybe 0 if no unique identifier is available
3679 process_local_reply (void *cls,
3680 const GNUNET_HashCode * key,
3683 enum GNUNET_BLOCK_Type type,
3686 struct GNUNET_TIME_Absolute
3690 struct PendingRequest *pr = cls;
3691 struct ProcessReplyClosure prq;
3692 struct CheckDuplicateRequestClosure cdrc;
3693 GNUNET_HashCode query;
3694 unsigned int old_rf;
3699 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3700 "Done processing local replies, forwarding request to other peers.\n");
3703 if (pr->client_request_list != NULL)
3705 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
3707 /* Figure out if this is a duplicate request and possibly
3708 merge 'struct PendingRequest' entries */
3711 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
3713 &check_duplicate_request_client,
3715 if (cdrc.have != NULL)
3718 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3719 "Received request for block `%s' twice from client, will only request once.\n",
3720 GNUNET_h2s (&pr->query));
3723 destroy_pending_request (pr);
3727 if (pr->local_only == GNUNET_YES)
3729 destroy_pending_request (pr);
3732 /* no more results */
3733 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
3734 pr->task = GNUNET_SCHEDULER_add_now (sched,
3735 &forward_request_task,
3740 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3741 "New local response to `%s' of type %u.\n",
3745 if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
3748 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3749 "Found ONDEMAND block, performing on-demand encoding\n");
3751 GNUNET_STATISTICS_update (stats,
3752 gettext_noop ("# on-demand blocks matched requests"),
3756 GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
3757 anonymity, expiration, uid,
3758 &process_local_reply,
3762 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3766 old_rf = pr->results_found;
3767 memset (&prq, 0, sizeof (prq));
3769 prq.expiration = expiration;
3772 GNUNET_BLOCK_get_key (block_ctx,
3779 GNUNET_DATASTORE_remove (dsh,
3783 GNUNET_TIME_UNIT_FOREVER_REL,
3785 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3789 prq.priority = priority;
3790 prq.finished = GNUNET_NO;
3791 prq.request_found = GNUNET_NO;
3792 if ( (old_rf == 0) &&
3793 (pr->results_found == 0) )
3794 update_datastore_delays (pr->start_time);
3795 process_reply (&prq, key, pr);
3796 if (prq.finished == GNUNET_YES)
3799 return; /* done here */
3800 if (prq.eval == GNUNET_BLOCK_EVALUATION_OK_LAST)
3802 pr->local_only = GNUNET_YES; /* do not forward */
3803 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
3806 if ( (pr->client_request_list == NULL) &&
3807 ( (GNUNET_YES == test_get_load_too_high (0)) ||
3808 (pr->results_found > 5 + 2 * pr->priority) ) )
3811 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3812 "Load too high, done with request\n");
3814 GNUNET_STATISTICS_update (stats,
3815 gettext_noop ("# processing result set cut short due to load"),
3818 /* FIXME: if this is activated, we might stall large downloads
3819 indefinitely since (presumably) the load can never go down again! */
3820 #if ENABLE_LOAD_MGMT
3821 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
3825 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3830 * We've received a request with the specified priority. Bound it
3831 * according to how much we trust the given peer.
3833 * @param prio_in requested priority
3834 * @param cp the peer making the request
3835 * @return effective priority
3838 bound_priority (uint32_t prio_in,
3839 struct ConnectedPeer *cp)
3841 #define N ((double)128.0)
3846 ld = test_get_load_too_high (0);
3847 if (ld == GNUNET_SYSERR)
3848 return 0; /* excess resources */
3849 ret = change_host_trust (cp, prio_in);
3852 if (ret > current_priorities + N)
3853 rret = current_priorities + N;
3857 = (current_priorities * (N-1) + rret)/N;
3859 if ( (ld == GNUNET_YES) && (ret > 0) )
3861 /* try with charging */
3862 ld = test_get_load_too_high (ret);
3864 if (ld == GNUNET_YES)
3868 change_host_trust (cp, -ret);
3869 return -1; /* not enough resources */
3877 * Iterator over entries in the 'query_request_map' that
3878 * tries to see if we have the same request pending from
3879 * the same peer already.
3881 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
3882 * @param key current key code (query, ignored, must match)
3883 * @param value value in the hash map (a 'struct PendingRequest'
3884 * that already exists)
3885 * @return GNUNET_YES if we should continue to
3886 * iterate (no match yet)
3887 * GNUNET_NO if not (match found).
3890 check_duplicate_request_peer (void *cls,
3891 const GNUNET_HashCode * key,
3894 struct CheckDuplicateRequestClosure *cdc = cls;
3895 struct PendingRequest *have = value;
3897 if (cdc->pr->target_pid == have->target_pid)
3907 * Handle P2P "GET" request.
3909 * @param cls closure, always NULL
3910 * @param other the other peer involved (sender or receiver, NULL
3911 * for loopback messages where we are both sender and receiver)
3912 * @param message the actual message
3913 * @param latency reported latency of the connection with 'other'
3914 * @param distance reported distance (DV) to 'other'
3915 * @return GNUNET_OK to keep the connection open,
3916 * GNUNET_SYSERR to close it (signal serious error)
3919 handle_p2p_get (void *cls,
3920 const struct GNUNET_PeerIdentity *other,
3921 const struct GNUNET_MessageHeader *message,
3922 struct GNUNET_TIME_Relative latency,
3925 struct PendingRequest *pr;
3926 struct ConnectedPeer *cp;
3927 struct ConnectedPeer *cps;
3928 struct CheckDuplicateRequestClosure cdc;
3929 struct GNUNET_TIME_Relative timeout;
3931 const struct GetMessage *gm;
3933 const GNUNET_HashCode *opt;
3936 uint32_t ttl_decrement;
3938 enum GNUNET_BLOCK_Type type;
3941 msize = ntohs(message->size);
3942 if (msize < sizeof (struct GetMessage))
3944 GNUNET_break_op (0);
3945 return GNUNET_SYSERR;
3947 gm = (const struct GetMessage*) message;
3949 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3950 "Received request for `%s'\n",
3951 GNUNET_h2s (&gm->query));
3953 type = ntohl (gm->type);
3954 bm = ntohl (gm->hash_bitmap);
3962 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
3964 GNUNET_break_op (0);
3965 return GNUNET_SYSERR;
3967 opt = (const GNUNET_HashCode*) &gm[1];
3968 bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
3969 bm = ntohl (gm->hash_bitmap);
3971 cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3972 &other->hashPubKey);
3975 /* peer must have just disconnected */
3976 GNUNET_STATISTICS_update (stats,
3977 gettext_noop ("# requests dropped due to initiator not being connected"),
3980 return GNUNET_SYSERR;
3982 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
3983 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3990 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
3991 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3992 "Failed to find RETURN-TO peer `%4s' in connection set. Dropping query.\n",
3993 GNUNET_i2s ((const struct GNUNET_PeerIdentity*) &opt[bits-1]));
3996 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3997 "Failed to find peer `%4s' in connection set. Dropping query.\n",
3998 GNUNET_i2s (other));
4000 GNUNET_STATISTICS_update (stats,
4001 gettext_noop ("# requests dropped due to missing reverse route"),
4004 /* FIXME: try connect? */
4007 /* note that we can really only check load here since otherwise
4008 peers could find out that we are overloaded by not being
4009 disconnected after sending us a malformed query... */
4010 priority = bound_priority (ntohl (gm->priority), cps);
4014 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4015 "Dropping query from `%s', this peer is too busy.\n",
4016 GNUNET_i2s (other));
4018 GNUNET_STATISTICS_update (stats,
4019 gettext_noop ("# requests dropped due to high load"),
4022 #if ENABLE_LOAD_MGMT
4023 /* FIXME: this causes problems... */
4028 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4029 "Received request for `%s' of type %u from peer `%4s' with flags %u\n",
4030 GNUNET_h2s (&gm->query),
4031 (unsigned int) type,
4035 have_ns = (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE));
4036 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
4037 (have_ns ? sizeof(GNUNET_HashCode) : 0));
4040 pr->namespace = (GNUNET_HashCode*) &pr[1];
4041 memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
4043 if ( (GNUNET_LOAD_get_load (cp->transmission_delay) > 3 * (1 + priority)) ||
4044 (GNUNET_LOAD_get_average (cp->transmission_delay) >
4045 GNUNET_CONSTANTS_MAX_CORK_DELAY.value * 2 + GNUNET_LOAD_get_average (rt_entry_lifetime)) )
4047 /* don't have BW to send to peer, or would likely take longer than we have for it,
4048 so at best indirect the query */
4050 #if ENABLE_LOAD_MGMT
4051 /* FIXME: if this line is enabled, the 'perf' test for larger files simply "hangs";
4052 the cause seems to be that the load goes up (to the point where we do this)
4053 and then never goes down again... (outch) */
4054 pr->forward_only = GNUNET_YES;
4058 pr->mingle = ntohl (gm->filter_mutator);
4059 if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
4060 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
4061 pr->anonymity_level = 1;
4062 pr->priority = (uint32_t) priority;
4063 pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
4064 pr->query = gm->query;
4065 /* decrement ttl (always) */
4066 ttl_decrement = 2 * TTL_DECREMENT +
4067 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
4069 if ( (pr->ttl < 0) &&
4070 (((int32_t)(pr->ttl - ttl_decrement)) > 0) )
4073 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4074 "Dropping query from `%s' due to TTL underflow (%d - %u).\n",
4079 GNUNET_STATISTICS_update (stats,
4080 gettext_noop ("# requests dropped due TTL underflow"),
4083 /* integer underflow => drop (should be very rare)! */
4087 pr->ttl -= ttl_decrement;
4088 pr->start_time = GNUNET_TIME_absolute_get ();
4090 /* get bloom filter */
4093 pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
4096 pr->bf_size = bfsize;
4100 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
4102 &check_duplicate_request_peer,
4104 if (cdc.have != NULL)
4106 if (cdc.have->start_time.value + cdc.have->ttl >=
4107 pr->start_time.value + pr->ttl)
4109 /* existing request has higher TTL, drop new one! */
4110 cdc.have->priority += pr->priority;
4111 destroy_pending_request (pr);
4113 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4114 "Have existing request with higher TTL, dropping new request.\n",
4115 GNUNET_i2s (other));
4117 GNUNET_STATISTICS_update (stats,
4118 gettext_noop ("# requests dropped due to higher-TTL request"),
4125 /* existing request has lower TTL, drop old one! */
4126 pr->priority += cdc.have->priority;
4127 /* Possible optimization: if we have applicable pending
4128 replies in 'cdc.have', we might want to move those over
4129 (this is a really rare special-case, so it is not clear
4130 that this would be worth it) */
4131 destroy_pending_request (cdc.have);
4132 /* keep processing 'pr'! */
4137 GNUNET_break (GNUNET_OK ==
4138 GNUNET_CONTAINER_multihashmap_put (query_request_map,
4141 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
4142 GNUNET_break (GNUNET_OK ==
4143 GNUNET_CONTAINER_multihashmap_put (peer_request_map,
4146 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
4148 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
4150 pr->start_time.value + pr->ttl);
4152 GNUNET_STATISTICS_update (stats,
4153 gettext_noop ("# P2P searches received"),
4156 GNUNET_STATISTICS_update (stats,
4157 gettext_noop ("# P2P searches active"),
4161 /* calculate change in traffic preference */
4162 cps->inc_preference += pr->priority * 1000 + QUERY_BANDWIDTH_VALUE;
4163 /* process locally */
4164 if (type == GNUNET_BLOCK_TYPE_FS_DBLOCK)
4165 type = GNUNET_BLOCK_TYPE_ANY; /* to get on-demand as well */
4166 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
4167 (pr->priority + 1));
4168 if (GNUNET_YES != pr->forward_only)
4171 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4172 "Handing request for `%s' to datastore\n",
4173 GNUNET_h2s (&gm->query));
4175 pr->qe = GNUNET_DATASTORE_get (dsh,
4179 MAX_DATASTORE_QUEUE,
4181 &process_local_reply,
4185 GNUNET_STATISTICS_update (stats,
4186 gettext_noop ("# requests dropped by datastore (queue length limit)"),
4193 GNUNET_STATISTICS_update (stats,
4194 gettext_noop ("# requests forwarded due to high load"),
4199 /* Are multiple results possible (and did we look locally)? If so, start processing remotely now! */
4202 case GNUNET_BLOCK_TYPE_FS_DBLOCK:
4203 case GNUNET_BLOCK_TYPE_FS_IBLOCK:
4204 /* only one result, wait for datastore */
4205 if (GNUNET_YES != pr->forward_only)
4207 GNUNET_STATISTICS_update (stats,
4208 gettext_noop ("# requests not instantly forwarded (waiting for datastore)"),
4214 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
4215 pr->task = GNUNET_SCHEDULER_add_now (sched,
4216 &forward_request_task,
4220 /* make sure we don't track too many requests */
4221 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
4223 pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
4224 GNUNET_assert (pr != NULL);
4225 destroy_pending_request (pr);
4231 /* **************************** CS GET Handling ************************ */
4235 * Handle START_SEARCH-message (search request from client).
4237 * @param cls closure
4238 * @param client identification of the client
4239 * @param message the actual message
4242 handle_start_search (void *cls,
4243 struct GNUNET_SERVER_Client *client,
4244 const struct GNUNET_MessageHeader *message)
4246 static GNUNET_HashCode all_zeros;
4247 const struct SearchMessage *sm;
4248 struct ClientList *cl;
4249 struct ClientRequestList *crl;
4250 struct PendingRequest *pr;
4253 enum GNUNET_BLOCK_Type type;
4255 msize = ntohs (message->size);
4256 if ( (msize < sizeof (struct SearchMessage)) ||
4257 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
4260 GNUNET_SERVER_receive_done (client,
4264 GNUNET_STATISTICS_update (stats,
4265 gettext_noop ("# client searches received"),
4268 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
4269 sm = (const struct SearchMessage*) message;
4270 type = ntohl (sm->type);
4272 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4273 "Received request for `%s' of type %u from local client\n",
4274 GNUNET_h2s (&sm->query),
4275 (unsigned int) type);
4278 while ( (cl != NULL) &&
4279 (cl->client != client) )
4283 cl = GNUNET_malloc (sizeof (struct ClientList));
4284 cl->client = client;
4285 GNUNET_SERVER_client_keep (client);
4286 cl->next = client_list;
4289 /* detect duplicate KBLOCK requests */
4290 if ( (type == GNUNET_BLOCK_TYPE_FS_KBLOCK) ||
4291 (type == GNUNET_BLOCK_TYPE_FS_NBLOCK) ||
4292 (type == GNUNET_BLOCK_TYPE_ANY) )
4295 while ( (crl != NULL) &&
4296 ( (0 != memcmp (&crl->req->query,
4298 sizeof (GNUNET_HashCode))) ||
4299 (crl->req->type != type) ) )
4304 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4305 "Have existing request, merging content-seen lists.\n");
4308 /* Duplicate request (used to send long list of
4309 known/blocked results); merge 'pr->replies_seen'
4310 and update bloom filter */
4311 GNUNET_array_grow (pr->replies_seen,
4312 pr->replies_seen_size,
4313 pr->replies_seen_off + sc);
4314 memcpy (&pr->replies_seen[pr->replies_seen_off],
4316 sc * sizeof (GNUNET_HashCode));
4317 pr->replies_seen_off += sc;
4318 refresh_bloomfilter (pr);
4319 GNUNET_STATISTICS_update (stats,
4320 gettext_noop ("# client searches updated (merged content seen list)"),
4323 GNUNET_SERVER_receive_done (client,
4328 GNUNET_STATISTICS_update (stats,
4329 gettext_noop ("# client searches active"),
4332 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
4333 ((type == GNUNET_BLOCK_TYPE_FS_SBLOCK) ? sizeof(GNUNET_HashCode) : 0));
4334 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
4335 memset (crl, 0, sizeof (struct ClientRequestList));
4336 crl->client_list = cl;
4337 GNUNET_CONTAINER_DLL_insert (cl->rl_head,
4342 pr->client_request_list = crl;
4343 GNUNET_array_grow (pr->replies_seen,
4344 pr->replies_seen_size,
4346 memcpy (pr->replies_seen,
4348 sc * sizeof (GNUNET_HashCode));
4349 pr->replies_seen_off = sc;
4350 pr->anonymity_level = ntohl (sm->anonymity_level);
4351 pr->start_time = GNUNET_TIME_absolute_get ();
4352 refresh_bloomfilter (pr);
4353 pr->query = sm->query;
4354 if (0 == (1 & ntohl (sm->options)))
4355 pr->local_only = GNUNET_NO;
4357 pr->local_only = GNUNET_YES;
4360 case GNUNET_BLOCK_TYPE_FS_DBLOCK:
4361 case GNUNET_BLOCK_TYPE_FS_IBLOCK:
4362 if (0 != memcmp (&sm->target,
4364 sizeof (GNUNET_HashCode)))
4365 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
4367 case GNUNET_BLOCK_TYPE_FS_SBLOCK:
4368 pr->namespace = (GNUNET_HashCode*) &pr[1];
4369 memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
4374 GNUNET_break (GNUNET_OK ==
4375 GNUNET_CONTAINER_multihashmap_put (query_request_map,
4378 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
4379 if (type == GNUNET_BLOCK_TYPE_FS_DBLOCK)
4380 type = GNUNET_BLOCK_TYPE_ANY; /* get on-demand blocks too! */
4381 pr->qe = GNUNET_DATASTORE_get (dsh,
4385 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
4386 &process_local_reply,
4391 /* **************************** Startup ************************ */
4394 * Process fs requests.
4396 * @param s scheduler to use
4397 * @param server the initialized server
4398 * @param c configuration to use
4401 main_init (struct GNUNET_SCHEDULER_Handle *s,
4402 struct GNUNET_SERVER_Handle *server,
4403 const struct GNUNET_CONFIGURATION_Handle *c)
4405 static const struct GNUNET_CORE_MessageHandler p2p_handlers[] =
4408 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
4410 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
4411 { &handle_p2p_migration_stop,
4412 GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP,
4413 sizeof (struct MigrationStopMessage) },
4416 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
4417 {&GNUNET_FS_handle_index_start, NULL,
4418 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
4419 {&GNUNET_FS_handle_index_list_get, NULL,
4420 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
4421 {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
4422 sizeof (struct UnindexMessage) },
4423 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
4427 unsigned long long enc = 128;
4431 stats = GNUNET_STATISTICS_create (sched, "fs", cfg);
4432 min_migration_delay = GNUNET_TIME_UNIT_SECONDS;
4434 GNUNET_CONFIGURATION_get_value_number (cfg,
4436 "MAX_PENDING_REQUESTS",
4437 &max_pending_requests)) ||
4439 GNUNET_CONFIGURATION_get_value_number (cfg,
4441 "EXPECTED_NEIGHBOUR_COUNT",
4444 GNUNET_CONFIGURATION_get_value_time (cfg,
4446 "MIN_MIGRATION_DELAY",
4447 &min_migration_delay)) )
4449 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4450 _("Configuration fails to specify certain parameters, assuming default values."));
4452 connected_peers = GNUNET_CONTAINER_multihashmap_create (enc);
4453 query_request_map = GNUNET_CONTAINER_multihashmap_create (max_pending_requests);
4454 rt_entry_lifetime = GNUNET_LOAD_value_init (GNUNET_TIME_UNIT_FOREVER_REL);
4455 peer_request_map = GNUNET_CONTAINER_multihashmap_create (enc);
4456 requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
4457 core = GNUNET_CORE_connect (sched,
4459 GNUNET_TIME_UNIT_FOREVER_REL,
4462 &peer_connect_handler,
4463 &peer_disconnect_handler,
4470 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4471 _("Failed to connect to `%s' service.\n"),
4473 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
4474 connected_peers = NULL;
4475 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
4476 query_request_map = NULL;
4477 GNUNET_LOAD_value_free (rt_entry_lifetime);
4478 rt_entry_lifetime = NULL;
4479 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
4480 requests_by_expiration_heap = NULL;
4481 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
4482 peer_request_map = NULL;
4485 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
4488 return GNUNET_SYSERR;
4490 /* FIXME: distinguish between sending and storing in options? */
4491 if (active_migration)
4493 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4494 _("Content migration is enabled, will start to gather data\n"));
4495 consider_migration_gathering ();
4497 consider_dht_put_gathering (NULL);
4498 GNUNET_SERVER_disconnect_notify (server,
4499 &handle_client_disconnect,
4501 GNUNET_assert (GNUNET_OK ==
4502 GNUNET_CONFIGURATION_get_value_filename (cfg,
4506 GNUNET_DISK_directory_create (trustDirectory);
4507 GNUNET_SCHEDULER_add_with_priority (sched,
4508 GNUNET_SCHEDULER_PRIORITY_HIGH,
4509 &cron_flush_trust, NULL);
4512 GNUNET_SERVER_add_handlers (server, handlers);
4513 GNUNET_SCHEDULER_add_delayed (sched,
4514 GNUNET_TIME_UNIT_FOREVER_REL,
4522 * Process fs requests.
4524 * @param cls closure
4525 * @param sched scheduler to use
4526 * @param server the initialized server
4527 * @param cfg configuration to use
4531 struct GNUNET_SCHEDULER_Handle *sched,
4532 struct GNUNET_SERVER_Handle *server,
4533 const struct GNUNET_CONFIGURATION_Handle *cfg)
4535 active_migration = GNUNET_CONFIGURATION_get_value_yesno (cfg,
4538 dsh = GNUNET_DATASTORE_connect (cfg,
4542 GNUNET_SCHEDULER_shutdown (sched);
4545 datastore_get_load = GNUNET_LOAD_value_init (DATASTORE_LOAD_AUTODECLINE);
4546 datastore_put_load = GNUNET_LOAD_value_init (DATASTORE_LOAD_AUTODECLINE);
4547 block_cfg = GNUNET_CONFIGURATION_create ();
4548 GNUNET_CONFIGURATION_set_value_string (block_cfg,
4552 block_ctx = GNUNET_BLOCK_context_create (block_cfg);
4553 GNUNET_assert (NULL != block_ctx);
4554 dht_handle = GNUNET_DHT_connect (sched,
4557 if ( (GNUNET_OK != GNUNET_FS_indexing_init (sched, cfg, dsh)) ||
4558 (GNUNET_OK != main_init (sched, server, cfg)) )
4560 GNUNET_SCHEDULER_shutdown (sched);
4561 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
4563 GNUNET_DHT_disconnect (dht_handle);
4565 GNUNET_BLOCK_context_destroy (block_ctx);
4567 GNUNET_CONFIGURATION_destroy (block_cfg);
4569 GNUNET_LOAD_value_free (datastore_get_load);
4570 datastore_get_load = NULL;
4571 GNUNET_LOAD_value_free (datastore_put_load);
4572 datastore_put_load = NULL;
4579 * The main function for the fs service.
4581 * @param argc number of arguments from the command line
4582 * @param argv command line arguments
4583 * @return 0 ok, 1 on error
4586 main (int argc, char *const *argv)
4588 return (GNUNET_OK ==
4589 GNUNET_SERVICE_run (argc,
4592 GNUNET_SERVICE_OPTION_NONE,
4593 &run, NULL)) ? 0 : 1;
4596 /* end of gnunet-service-fs.c */