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 * Performance measurements (for 50 MB file, 2 peers):
60 * - Without delays: 3300 kb/s
61 * - With delays: 101 kb/s
63 #define SUPPORT_DELAYS GNUNET_NO
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
73 * At what frequency should our datastore load decrease
74 * automatically (since if we don't use it, clearly the
75 * load must be going down).
77 #define DATASTORE_LOAD_AUTODECLINE GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 250)
80 * How often do we flush trust values to disk?
82 #define TRUST_FLUSH_FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
85 * How often do we at most PUT content into the DHT?
87 #define MAX_DHT_PUT_FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
90 * Inverse of the probability that we will submit the same query
91 * to the same peer again. If the same peer already got the query
92 * repeatedly recently, the probability is multiplied by the inverse
93 * of this number each time. Note that we only try about every TTL_DECREMENT/2
94 * plus MAX_CORK_DELAY (so roughly every 3.5s).
96 * Note that this factor is a key influence to performance in small
97 * networks (especially test networks of 2 peers) because if there is
98 * only a single peer with the data, this value will determine how
99 * soon we might re-try. For example, a value of 3 can result in
100 * 1.7 MB/s transfer rates for a 10 MB file when a value of 1 would
101 * give us 5 MB/s. OTOH, obviously re-trying the same peer can be
102 * rather inefficient in larger networks, hence picking 1 is in
103 * general not the best choice.
105 * Performance measurements (for 50 MB file, 2 peers, no delays):
107 * - 1: 3300 kb/s (consistently)
108 * - 3: 2046 kb/s, 754 kb/s, 3490 kb/s
109 * - 5: 759 kb/s, 968 kb/s, 1160 kb/s
111 * Note that this does NOT mean that the value should be 1 since
112 * a 2-peer network is far from representative here (and this fails
113 * to take into consideration bandwidth wasted by repeatedly
114 * sending queries to peers that don't have the content). Also,
115 * it is expected that higher values lead to more inconsistent
116 * measurements since this only affects lost messages towards the
117 * end of the download.
119 * Finally, we should probably consider changing this and making
120 * it dependent on the number of connected peers or a related
121 * metric (bad magic constants...).
123 #define RETRY_PROBABILITY_INV 1
126 * What is the maximum delay for a P2P FS message (in our interaction
127 * with core)? FS-internal delays are another story. The value is
128 * chosen based on the 32k block size. Given that peers typcially
129 * have at least 1 kb/s bandwidth, 45s waits give us a chance to
130 * transmit one message even to the lowest-bandwidth peers.
132 #define MAX_TRANSMIT_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 45)
135 * Maximum number of requests (from other peers, overall) that we're
136 * willing to have pending at any given point in time. Can be changed
137 * via the configuration file (32k is just the default).
139 static unsigned long long max_pending_requests = (32 * 1024);
143 * Information we keep for each pending reply. The
144 * actual message follows at the end of this struct.
146 struct PendingMessage;
149 * Function called upon completion of a transmission.
152 * @param pid ID of receiving peer, 0 on transmission error
154 typedef void (*TransmissionContinuation)(void * cls,
155 GNUNET_PEER_Id tpid);
159 * Information we keep for each pending message (GET/PUT). The
160 * actual message follows at the end of this struct.
162 struct PendingMessage
165 * This is a doubly-linked list of messages to the same peer.
167 struct PendingMessage *next;
170 * This is a doubly-linked list of messages to the same peer.
172 struct PendingMessage *prev;
175 * Entry in pending message list for this pending message.
177 struct PendingMessageList *pml;
180 * Function to call immediately once we have transmitted this
183 TransmissionContinuation cont;
191 * Do not transmit this pending message until this deadline.
193 struct GNUNET_TIME_Absolute delay_until;
196 * Size of the reply; actual reply message follows
197 * at the end of this struct.
202 * How important is this message for us?
210 * Information about a peer that we are connected to.
211 * We track data that is useful for determining which
212 * peers should receive our requests. We also keep
213 * a list of messages to transmit to this peer.
219 * List of the last clients for which this peer successfully
222 struct GNUNET_SERVER_Client *last_client_replies[CS2P_SUCCESS_LIST_SIZE];
225 * List of the last PIDs for which
226 * this peer successfully answered a query;
227 * We use 0 to indicate no successful reply.
229 GNUNET_PEER_Id last_p2p_replies[P2P_SUCCESS_LIST_SIZE];
232 * Average delay between sending the peer a request and
233 * getting a reply (only calculated over the requests for
234 * which we actually got a reply). Calculated
235 * as a moving average: new_delay = ((n-1)*last_delay+curr_delay) / n
237 struct GNUNET_TIME_Relative avg_delay;
240 * Point in time until which this peer does not want us to migrate content
243 struct GNUNET_TIME_Absolute migration_blocked;
246 * Time until when we blocked this peer from migrating
249 struct GNUNET_TIME_Absolute last_migration_block;
252 * Transmission times for the last MAX_QUEUE_PER_PEER
253 * requests for this peer. Used as a ring buffer, current
254 * offset is stored in 'last_request_times_off'. If the
255 * oldest entry is more recent than the 'avg_delay', we should
256 * not send any more requests right now.
258 struct GNUNET_TIME_Absolute last_request_times[MAX_QUEUE_PER_PEER];
261 * Handle for an active request for transmission to this
264 struct GNUNET_CORE_TransmitHandle *cth;
267 * Messages (replies, queries, content migration) we would like to
268 * send to this peer in the near future. Sorted by priority, head.
270 struct PendingMessage *pending_messages_head;
273 * Messages (replies, queries, content migration) we would like to
274 * send to this peer in the near future. Sorted by priority, tail.
276 struct PendingMessage *pending_messages_tail;
279 * How long does it typically take for us to transmit a message
280 * to this peer? (delay between the request being issued and
281 * the callback being invoked).
283 struct GNUNET_LOAD_Value *transmission_delay;
286 * Time when the last transmission request was issued.
288 struct GNUNET_TIME_Absolute last_transmission_request_start;
291 * ID of delay task for scheduling transmission.
293 GNUNET_SCHEDULER_TaskIdentifier delayed_transmission_request_task;
296 * Average priority of successful replies. Calculated
297 * as a moving average: new_avg = ((n-1)*last_avg+curr_prio) / n
302 * Increase in traffic preference still to be submitted
303 * to the core service for this peer.
305 uint64_t inc_preference;
308 * Trust rating for this peer
313 * Trust rating for this peer on disk.
318 * The peer's identity.
323 * Size of the linked list of 'pending_messages'.
325 unsigned int pending_requests;
328 * Which offset in "last_p2p_replies" will be updated next?
329 * (we go round-robin).
331 unsigned int last_p2p_replies_woff;
334 * Which offset in "last_client_replies" will be updated next?
335 * (we go round-robin).
337 unsigned int last_client_replies_woff;
340 * Current offset into 'last_request_times' ring buffer.
342 unsigned int last_request_times_off;
348 * Information we keep for each pending request. We should try to
349 * keep this struct as small as possible since its memory consumption
350 * is key to how many requests we can have pending at once.
352 struct PendingRequest;
356 * Doubly-linked list of requests we are performing
357 * on behalf of the same client.
359 struct ClientRequestList
363 * This is a doubly-linked list.
365 struct ClientRequestList *next;
368 * This is a doubly-linked list.
370 struct ClientRequestList *prev;
373 * Request this entry represents.
375 struct PendingRequest *req;
378 * Client list this request belongs to.
380 struct ClientList *client_list;
386 * Replies to be transmitted to the client. The actual
387 * response message is allocated after this struct.
389 struct ClientResponseMessage
392 * This is a doubly-linked list.
394 struct ClientResponseMessage *next;
397 * This is a doubly-linked list.
399 struct ClientResponseMessage *prev;
402 * Client list entry this response belongs to.
404 struct ClientList *client_list;
407 * Number of bytes in the response.
414 * Linked list of clients we are performing requests
420 * This is a linked list.
422 struct ClientList *next;
425 * ID of a client making a request, NULL if this entry is for a
428 struct GNUNET_SERVER_Client *client;
431 * Head of list of requests performed on behalf
432 * of this client right now.
434 struct ClientRequestList *rl_head;
437 * Tail of list of requests performed on behalf
438 * of this client right now.
440 struct ClientRequestList *rl_tail;
443 * Head of linked list of responses.
445 struct ClientResponseMessage *res_head;
448 * Tail of linked list of responses.
450 struct ClientResponseMessage *res_tail;
453 * Context for sending replies.
455 struct GNUNET_CONNECTION_TransmitHandle *th;
461 * Information about a peer that we have forwarded this
462 * request to already.
464 struct UsedTargetEntry
467 * What was the last time we have transmitted this request to this
470 struct GNUNET_TIME_Absolute last_request_time;
473 * How often have we transmitted this request to this peer?
475 unsigned int num_requests;
478 * PID of the target peer.
489 * Doubly-linked list of messages we are performing
490 * due to a pending request.
492 struct PendingMessageList
496 * This is a doubly-linked list of messages on behalf of the same request.
498 struct PendingMessageList *next;
501 * This is a doubly-linked list of messages on behalf of the same request.
503 struct PendingMessageList *prev;
506 * Message this entry represents.
508 struct PendingMessage *pm;
511 * Request this entry belongs to.
513 struct PendingRequest *req;
516 * Peer this message is targeted for.
518 struct ConnectedPeer *target;
524 * Information we keep for each pending request. We should try to
525 * keep this struct as small as possible since its memory consumption
526 * is key to how many requests we can have pending at once.
528 struct PendingRequest
532 * If this request was made by a client, this is our entry in the
533 * client request list; otherwise NULL.
535 struct ClientRequestList *client_request_list;
538 * Entry of peer responsible for this entry (if this request
539 * was made by a peer).
541 struct ConnectedPeer *cp;
544 * If this is a namespace query, pointer to the hash of the public
545 * key of the namespace; otherwise NULL. Pointer will be to the
546 * end of this struct (so no need to free it).
548 const GNUNET_HashCode *namespace;
551 * Bloomfilter we use to filter out replies that we don't care about
552 * (anymore). NULL as long as we are interested in all replies.
554 struct GNUNET_CONTAINER_BloomFilter *bf;
557 * Context of our GNUNET_CORE_peer_change_preference call.
559 struct GNUNET_CORE_InformationRequestContext *irc;
562 * Reference to DHT get operation for this request (or NULL).
564 struct GNUNET_DHT_GetHandle *dht_get;
567 * Hash code of all replies that we have seen so far (only valid
568 * if client is not NULL since we only track replies like this for
571 GNUNET_HashCode *replies_seen;
574 * Node in the heap representing this entry; NULL
575 * if we have no heap node.
577 struct GNUNET_CONTAINER_HeapNode *hnode;
580 * Head of list of messages being performed on behalf of this
583 struct PendingMessageList *pending_head;
586 * Tail of list of messages being performed on behalf of this
589 struct PendingMessageList *pending_tail;
592 * When did we first see this request (form this peer), or, if our
593 * client is initiating, when did we last initiate a search?
595 struct GNUNET_TIME_Absolute start_time;
598 * The query that this request is for.
600 GNUNET_HashCode query;
603 * The task responsible for transmitting queries
606 GNUNET_SCHEDULER_TaskIdentifier task;
609 * (Interned) Peer identifier that identifies a preferred target
612 GNUNET_PEER_Id target_pid;
615 * (Interned) Peer identifiers of peers that have already
616 * received our query for this content.
618 struct UsedTargetEntry *used_targets;
621 * Our entry in the queue (non-NULL while we wait for our
622 * turn to interact with the local database).
624 struct GNUNET_DATASTORE_QueueEntry *qe;
627 * Size of the 'bf' (in bytes).
632 * Desired anonymity level; only valid for requests from a local client.
634 uint32_t anonymity_level;
637 * How many entries in "used_targets" are actually valid?
639 unsigned int used_targets_off;
642 * How long is the "used_targets" array?
644 unsigned int used_targets_size;
647 * Number of results found for this request.
649 unsigned int results_found;
652 * How many entries in "replies_seen" are actually valid?
654 unsigned int replies_seen_off;
657 * How long is the "replies_seen" array?
659 unsigned int replies_seen_size;
662 * Priority with which this request was made. If one of our clients
663 * made the request, then this is the current priority that we are
664 * using when initiating the request. This value is used when
665 * we decide to reward other peers with trust for providing a reply.
670 * Priority points left for us to spend when forwarding this request
673 uint32_t remaining_priority;
676 * Number to mingle hashes for bloom-filter tests with.
681 * TTL with which we saw this request (or, if we initiated, TTL that
682 * we used for the request).
687 * Type of the content that this request is for.
689 enum GNUNET_BLOCK_Type type;
692 * Remove this request after transmission of the current response.
697 * GNUNET_YES if we should not forward this request to other peers.
702 * GNUNET_YES if we should not forward this request to other peers.
710 * Block that is ready for migration to other peers. Actual data is at the end of the block.
712 struct MigrationReadyBlock
716 * This is a doubly-linked list.
718 struct MigrationReadyBlock *next;
721 * This is a doubly-linked list.
723 struct MigrationReadyBlock *prev;
726 * Query for the block.
728 GNUNET_HashCode query;
731 * When does this block expire?
733 struct GNUNET_TIME_Absolute expiration;
736 * Peers we would consider forwarding this
737 * block to. Zero for empty entries.
739 GNUNET_PEER_Id target_list[MIGRATION_LIST_SIZE];
747 * Number of targets already used.
749 unsigned int used_targets;
754 enum GNUNET_BLOCK_Type type;
759 * Our connection to the datastore.
761 static struct GNUNET_DATASTORE_Handle *dsh;
766 static struct GNUNET_BLOCK_Context *block_ctx;
769 * Our block configuration.
771 static struct GNUNET_CONFIGURATION_Handle *block_cfg;
776 static const struct GNUNET_CONFIGURATION_Handle *cfg;
779 * Map of peer identifiers to "struct ConnectedPeer" (for that peer).
781 static struct GNUNET_CONTAINER_MultiHashMap *connected_peers;
784 * Map of peer identifiers to "struct PendingRequest" (for that peer).
786 static struct GNUNET_CONTAINER_MultiHashMap *peer_request_map;
789 * Map of query identifiers to "struct PendingRequest" (for that query).
791 static struct GNUNET_CONTAINER_MultiHashMap *query_request_map;
794 * Heap with the request that will expire next at the top. Contains
795 * pointers of type "struct PendingRequest*"; these will *also* be
796 * aliased from the "requests_by_peer" data structures and the
797 * "requests_by_query" table. Note that requests from our clients
798 * don't expire and are thus NOT in the "requests_by_expiration"
799 * (or the "requests_by_peer" tables).
801 static struct GNUNET_CONTAINER_Heap *requests_by_expiration_heap;
804 * Handle for reporting statistics.
806 static struct GNUNET_STATISTICS_Handle *stats;
809 * Linked list of clients we are currently processing requests for.
811 static struct ClientList *client_list;
814 * Pointer to handle to the core service (points to NULL until we've
817 static struct GNUNET_CORE_Handle *core;
820 * Head of linked list of blocks that can be migrated.
822 static struct MigrationReadyBlock *mig_head;
825 * Tail of linked list of blocks that can be migrated.
827 static struct MigrationReadyBlock *mig_tail;
830 * Request to datastore for migration (or NULL).
832 static struct GNUNET_DATASTORE_QueueEntry *mig_qe;
835 * Request to datastore for DHT PUTs (or NULL).
837 static struct GNUNET_DATASTORE_QueueEntry *dht_qe;
840 * Type we will request for the next DHT PUT round from the datastore.
842 static enum GNUNET_BLOCK_Type dht_put_type = GNUNET_BLOCK_TYPE_FS_KBLOCK;
845 * Where do we store trust information?
847 static char *trustDirectory;
850 * ID of task that collects blocks for migration.
852 static GNUNET_SCHEDULER_TaskIdentifier mig_task;
855 * ID of task that collects blocks for DHT PUTs.
857 static GNUNET_SCHEDULER_TaskIdentifier dht_task;
860 * What is the maximum frequency at which we are allowed to
861 * poll the datastore for migration content?
863 static struct GNUNET_TIME_Relative min_migration_delay;
866 * Handle for DHT operations.
868 static struct GNUNET_DHT_Handle *dht_handle;
871 * Size of the doubly-linked list of migration blocks.
873 static unsigned int mig_size;
876 * Are we allowed to migrate content to this peer.
878 static int active_migration;
881 * How many entires with zero anonymity do we currently estimate
882 * to have in the database?
884 static unsigned int zero_anonymity_count_estimate;
887 * Typical priorities we're seeing from other peers right now. Since
888 * most priorities will be zero, this value is the weighted average of
889 * non-zero priorities seen "recently". In order to ensure that new
890 * values do not dramatically change the ratio, values are first
891 * "capped" to a reasonable range (+N of the current value) and then
892 * averaged into the existing value by a ratio of 1:N. Hence
893 * receiving the largest possible priority can still only raise our
894 * "current_priorities" by at most 1.
896 static double current_priorities;
899 * Datastore 'GET' load tracking.
901 static struct GNUNET_LOAD_Value *datastore_get_load;
904 * Datastore 'PUT' load tracking.
906 static struct GNUNET_LOAD_Value *datastore_put_load;
909 * How long do requests typically stay in the routing table?
911 static struct GNUNET_LOAD_Value *rt_entry_lifetime;
914 * We've just now completed a datastore request. Update our
915 * datastore load calculations.
917 * @param start time when the datastore request was issued
920 update_datastore_delays (struct GNUNET_TIME_Absolute start)
922 struct GNUNET_TIME_Relative delay;
924 delay = GNUNET_TIME_absolute_get_duration (start);
925 GNUNET_LOAD_update (datastore_get_load,
931 * Get the filename under which we would store the GNUNET_HELLO_Message
932 * for the given host and protocol.
933 * @return filename of the form DIRECTORY/HOSTID
936 get_trust_filename (const struct GNUNET_PeerIdentity *id)
938 struct GNUNET_CRYPTO_HashAsciiEncoded fil;
941 GNUNET_CRYPTO_hash_to_enc (&id->hashPubKey, &fil);
942 GNUNET_asprintf (&fn, "%s%s%s", trustDirectory, DIR_SEPARATOR_STR, &fil);
949 * Transmit messages by copying it to the target buffer
950 * "buf". "buf" will be NULL and "size" zero if the socket was closed
951 * for writing in the meantime. In that case, do nothing
952 * (the disconnect or shutdown handler will take care of the rest).
953 * If we were able to transmit messages and there are still more
954 * pending, ask core again for further calls to this function.
956 * @param cls closure, pointer to the 'struct ConnectedPeer*'
957 * @param size number of bytes available in buf
958 * @param buf where the callee should write the message
959 * @return number of bytes written to buf
962 transmit_to_peer (void *cls,
963 size_t size, void *buf);
966 /* ******************* clean up functions ************************ */
969 * Delete the given migration block.
971 * @param mb block to delete
974 delete_migration_block (struct MigrationReadyBlock *mb)
976 GNUNET_CONTAINER_DLL_remove (mig_head,
979 GNUNET_PEER_decrement_rcs (mb->target_list,
980 MIGRATION_LIST_SIZE);
987 * Compare the distance of two peers to a key.
990 * @param p1 first peer
991 * @param p2 second peer
992 * @return GNUNET_YES if P1 is closer to key than P2
995 is_closer (const GNUNET_HashCode *key,
996 const struct GNUNET_PeerIdentity *p1,
997 const struct GNUNET_PeerIdentity *p2)
999 return GNUNET_CRYPTO_hash_xorcmp (&p1->hashPubKey,
1006 * Consider migrating content to a given peer.
1008 * @param cls 'struct MigrationReadyBlock*' to select
1009 * targets for (or NULL for none)
1010 * @param key ID of the peer
1011 * @param value 'struct ConnectedPeer' of the peer
1012 * @return GNUNET_YES (always continue iteration)
1015 consider_migration (void *cls,
1016 const GNUNET_HashCode *key,
1019 struct MigrationReadyBlock *mb = cls;
1020 struct ConnectedPeer *cp = value;
1021 struct MigrationReadyBlock *pos;
1022 struct GNUNET_PeerIdentity cppid;
1023 struct GNUNET_PeerIdentity otherpid;
1024 struct GNUNET_PeerIdentity worstpid;
1029 /* consider 'cp' as a migration target for mb */
1030 if (GNUNET_TIME_absolute_get_remaining (cp->migration_blocked).rel_value > 0)
1031 return GNUNET_YES; /* peer has requested no migration! */
1034 GNUNET_PEER_resolve (cp->pid,
1036 repl = MIGRATION_LIST_SIZE;
1037 for (i=0;i<MIGRATION_LIST_SIZE;i++)
1039 if (mb->target_list[i] == 0)
1041 mb->target_list[i] = cp->pid;
1042 GNUNET_PEER_change_rc (mb->target_list[i], 1);
1043 repl = MIGRATION_LIST_SIZE;
1046 GNUNET_PEER_resolve (mb->target_list[i],
1048 if ( (repl == MIGRATION_LIST_SIZE) &&
1049 is_closer (&mb->query,
1054 worstpid = otherpid;
1056 else if ( (repl != MIGRATION_LIST_SIZE) &&
1057 (is_closer (&mb->query,
1062 worstpid = otherpid;
1065 if (repl != MIGRATION_LIST_SIZE)
1067 GNUNET_PEER_change_rc (mb->target_list[repl], -1);
1068 mb->target_list[repl] = cp->pid;
1069 GNUNET_PEER_change_rc (mb->target_list[repl], 1);
1073 /* consider scheduling transmission to cp for content migration */
1074 if (cp->cth != NULL)
1080 for (i=0;i<MIGRATION_LIST_SIZE;i++)
1082 if (cp->pid == pos->target_list[i])
1087 msize = GNUNET_MIN (msize,
1095 return GNUNET_YES; /* no content available */
1097 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1098 "Trying to migrate at least %u bytes to peer `%s'\n",
1102 if (cp->delayed_transmission_request_task != GNUNET_SCHEDULER_NO_TASK)
1104 GNUNET_SCHEDULER_cancel (cp->delayed_transmission_request_task);
1105 cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
1108 = GNUNET_CORE_notify_transmit_ready (core,
1109 0, GNUNET_TIME_UNIT_FOREVER_REL,
1110 (const struct GNUNET_PeerIdentity*) key,
1111 msize + sizeof (struct PutMessage),
1119 * Task that is run periodically to obtain blocks for content
1123 * @param tc scheduler context (also unused)
1126 gather_migration_blocks (void *cls,
1127 const struct GNUNET_SCHEDULER_TaskContext *tc);
1133 * Task that is run periodically to obtain blocks for DHT PUTs.
1135 * @param cls type of blocks to gather
1136 * @param tc scheduler context (unused)
1139 gather_dht_put_blocks (void *cls,
1140 const struct GNUNET_SCHEDULER_TaskContext *tc);
1144 * If the migration task is not currently running, consider
1145 * (re)scheduling it with the appropriate delay.
1148 consider_migration_gathering ()
1150 struct GNUNET_TIME_Relative delay;
1156 if (mig_task != GNUNET_SCHEDULER_NO_TASK)
1158 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
1160 delay = GNUNET_TIME_relative_divide (delay,
1161 MAX_MIGRATION_QUEUE);
1162 delay = GNUNET_TIME_relative_max (delay,
1163 min_migration_delay);
1164 mig_task = GNUNET_SCHEDULER_add_delayed (delay,
1165 &gather_migration_blocks,
1171 * If the DHT PUT gathering task is not currently running, consider
1172 * (re)scheduling it with the appropriate delay.
1175 consider_dht_put_gathering (void *cls)
1177 struct GNUNET_TIME_Relative delay;
1183 if (dht_task != GNUNET_SCHEDULER_NO_TASK)
1185 if (zero_anonymity_count_estimate > 0)
1187 delay = GNUNET_TIME_relative_divide (GNUNET_DHT_DEFAULT_REPUBLISH_FREQUENCY,
1188 zero_anonymity_count_estimate);
1189 delay = GNUNET_TIME_relative_min (delay,
1194 /* if we have NO zero-anonymity content yet, wait 5 minutes for some to
1195 (hopefully) appear */
1196 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5);
1198 dht_task = GNUNET_SCHEDULER_add_delayed (delay,
1199 &gather_dht_put_blocks,
1205 * Process content offered for migration.
1207 * @param cls closure
1208 * @param key key for the content
1209 * @param size number of bytes in data
1210 * @param data content stored
1211 * @param type type of the content
1212 * @param priority priority of the content
1213 * @param anonymity anonymity-level for the content
1214 * @param expiration expiration time for the content
1215 * @param uid unique identifier for the datum;
1216 * maybe 0 if no unique identifier is available
1219 process_migration_content (void *cls,
1220 const GNUNET_HashCode * key,
1223 enum GNUNET_BLOCK_Type type,
1226 struct GNUNET_TIME_Absolute
1227 expiration, uint64_t uid)
1229 struct MigrationReadyBlock *mb;
1234 if (mig_size < MAX_MIGRATION_QUEUE)
1235 consider_migration_gathering ();
1238 if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
1241 GNUNET_FS_handle_on_demand_block (key, size, data,
1242 type, priority, anonymity,
1244 &process_migration_content,
1247 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1252 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1253 "Retrieved block `%s' of type %u for migration\n",
1257 mb = GNUNET_malloc (sizeof (struct MigrationReadyBlock) + size);
1259 mb->expiration = expiration;
1262 memcpy (&mb[1], data, size);
1263 GNUNET_CONTAINER_DLL_insert_after (mig_head,
1268 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1269 &consider_migration,
1271 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1276 * Function called upon completion of the DHT PUT operation.
1279 dht_put_continuation (void *cls,
1280 const struct GNUNET_SCHEDULER_TaskContext *tc)
1282 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1287 * Store content in DHT.
1289 * @param cls closure
1290 * @param key key for the content
1291 * @param size number of bytes in data
1292 * @param data content stored
1293 * @param type type of the content
1294 * @param priority priority of the content
1295 * @param anonymity anonymity-level for the content
1296 * @param expiration expiration time for the content
1297 * @param uid unique identifier for the datum;
1298 * maybe 0 if no unique identifier is available
1301 process_dht_put_content (void *cls,
1302 const GNUNET_HashCode * key,
1305 enum GNUNET_BLOCK_Type type,
1308 struct GNUNET_TIME_Absolute
1309 expiration, uint64_t uid)
1311 static unsigned int counter;
1312 static GNUNET_HashCode last_vhash;
1313 static GNUNET_HashCode vhash;
1318 consider_dht_put_gathering (cls);
1321 /* slightly funky code to estimate the total number of values with zero
1322 anonymity from the maximum observed length of a monotonically increasing
1323 sequence of hashes over the contents */
1324 GNUNET_CRYPTO_hash (data, size, &vhash);
1325 if (GNUNET_CRYPTO_hash_cmp (&vhash, &last_vhash) <= 0)
1327 if (zero_anonymity_count_estimate > 0)
1328 zero_anonymity_count_estimate /= 2;
1334 if (zero_anonymity_count_estimate < (1 << counter))
1335 zero_anonymity_count_estimate = (1 << counter);
1337 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1338 "Retrieved block `%s' of type %u for DHT PUT\n",
1342 GNUNET_DHT_put (dht_handle,
1349 GNUNET_TIME_UNIT_FOREVER_REL,
1350 &dht_put_continuation,
1356 * Task that is run periodically to obtain blocks for content
1360 * @param tc scheduler context (also unused)
1363 gather_migration_blocks (void *cls,
1364 const struct GNUNET_SCHEDULER_TaskContext *tc)
1366 mig_task = GNUNET_SCHEDULER_NO_TASK;
1369 mig_qe = GNUNET_DATASTORE_get_random (dsh, 0, UINT_MAX,
1370 GNUNET_TIME_UNIT_FOREVER_REL,
1371 &process_migration_content, NULL);
1372 GNUNET_assert (mig_qe != NULL);
1378 * Task that is run periodically to obtain blocks for DHT PUTs.
1380 * @param cls type of blocks to gather
1381 * @param tc scheduler context (unused)
1384 gather_dht_put_blocks (void *cls,
1385 const struct GNUNET_SCHEDULER_TaskContext *tc)
1387 dht_task = GNUNET_SCHEDULER_NO_TASK;
1390 if (dht_put_type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
1391 dht_put_type = GNUNET_BLOCK_TYPE_FS_KBLOCK;
1392 dht_qe = GNUNET_DATASTORE_get_zero_anonymity (dsh, 0, UINT_MAX,
1393 GNUNET_TIME_UNIT_FOREVER_REL,
1395 &process_dht_put_content, NULL);
1396 GNUNET_assert (dht_qe != NULL);
1402 * We're done with a particular message list entry.
1403 * Free all associated resources.
1405 * @param pml entry to destroy
1408 destroy_pending_message_list_entry (struct PendingMessageList *pml)
1410 GNUNET_CONTAINER_DLL_remove (pml->req->pending_head,
1411 pml->req->pending_tail,
1413 GNUNET_CONTAINER_DLL_remove (pml->target->pending_messages_head,
1414 pml->target->pending_messages_tail,
1416 pml->target->pending_requests--;
1417 GNUNET_free (pml->pm);
1423 * Destroy the given pending message (and call the respective
1426 * @param pm message to destroy
1427 * @param tpid id of peer that the message was delivered to, or 0 for none
1430 destroy_pending_message (struct PendingMessage *pm,
1431 GNUNET_PEER_Id tpid)
1433 struct PendingMessageList *pml = pm->pml;
1434 TransmissionContinuation cont;
1438 cont_cls = pm->cont_cls;
1441 GNUNET_assert (pml->pm == pm);
1442 GNUNET_assert ( (tpid == 0) || (tpid == pml->target->pid) );
1443 destroy_pending_message_list_entry (pml);
1450 cont (cont_cls, tpid);
1455 * We're done processing a particular request.
1456 * Free all associated resources.
1458 * @param pr request to destroy
1461 destroy_pending_request (struct PendingRequest *pr)
1463 struct GNUNET_PeerIdentity pid;
1466 if (pr->hnode != NULL)
1468 GNUNET_CONTAINER_heap_remove_node (requests_by_expiration_heap,
1472 if (NULL == pr->client_request_list)
1474 GNUNET_STATISTICS_update (stats,
1475 gettext_noop ("# P2P searches active"),
1481 GNUNET_STATISTICS_update (stats,
1482 gettext_noop ("# client searches active"),
1487 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
1491 GNUNET_LOAD_update (rt_entry_lifetime,
1492 GNUNET_TIME_absolute_get_duration (pr->start_time).rel_value);
1496 GNUNET_DATASTORE_cancel (pr->qe);
1499 if (pr->dht_get != NULL)
1501 GNUNET_DHT_get_stop (pr->dht_get);
1504 if (pr->client_request_list != NULL)
1506 GNUNET_CONTAINER_DLL_remove (pr->client_request_list->client_list->rl_head,
1507 pr->client_request_list->client_list->rl_tail,
1508 pr->client_request_list);
1509 GNUNET_free (pr->client_request_list);
1510 pr->client_request_list = NULL;
1514 GNUNET_PEER_resolve (pr->cp->pid,
1516 (void) GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
1523 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
1526 if (pr->irc != NULL)
1528 GNUNET_CORE_peer_change_preference_cancel (pr->irc);
1531 if (pr->replies_seen != NULL)
1533 GNUNET_free (pr->replies_seen);
1534 pr->replies_seen = NULL;
1536 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
1538 GNUNET_SCHEDULER_cancel (pr->task);
1539 pr->task = GNUNET_SCHEDULER_NO_TASK;
1541 while (NULL != pr->pending_head)
1542 destroy_pending_message_list_entry (pr->pending_head);
1543 GNUNET_PEER_change_rc (pr->target_pid, -1);
1544 if (pr->used_targets != NULL)
1546 for (i=0;i<pr->used_targets_off;i++)
1547 GNUNET_PEER_change_rc (pr->used_targets[i].pid, -1);
1548 GNUNET_free (pr->used_targets);
1549 pr->used_targets_off = 0;
1550 pr->used_targets_size = 0;
1551 pr->used_targets = NULL;
1558 * Method called whenever a given peer connects.
1560 * @param cls closure, not used
1561 * @param peer peer identity this notification is about
1562 * @param latency reported latency of the connection with 'other'
1563 * @param distance reported distance (DV) to 'other'
1566 peer_connect_handler (void *cls,
1568 GNUNET_PeerIdentity * peer,
1569 struct GNUNET_TIME_Relative latency,
1572 struct ConnectedPeer *cp;
1573 struct MigrationReadyBlock *pos;
1577 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1584 cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
1585 cp->transmission_delay = GNUNET_LOAD_value_init (latency);
1586 cp->pid = GNUNET_PEER_intern (peer);
1588 fn = get_trust_filename (peer);
1589 if ((GNUNET_DISK_file_test (fn) == GNUNET_YES) &&
1590 (sizeof (trust) == GNUNET_DISK_fn_read (fn, &trust, sizeof (trust))))
1591 cp->disk_trust = cp->trust = ntohl (trust);
1594 GNUNET_break (GNUNET_OK ==
1595 GNUNET_CONTAINER_multihashmap_put (connected_peers,
1598 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1603 (void) consider_migration (pos, &peer->hashPubKey, cp);
1610 * Method called whenever a given peer has a status change.
1612 * @param cls closure
1613 * @param peer peer identity this notification is about
1614 * @param latency reported latency of the connection with 'other'
1615 * @param distance reported distance (DV) to 'other'
1616 * @param bandwidth_in available amount of inbound bandwidth
1617 * @param bandwidth_out available amount of outbound bandwidth
1618 * @param timeout absolute time when this peer will time out
1619 * unless we see some further activity from it
1622 peer_status_handler (void *cls,
1624 GNUNET_PeerIdentity * peer,
1625 struct GNUNET_TIME_Relative latency,
1627 struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
1628 struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
1629 struct GNUNET_TIME_Absolute timeout)
1631 struct ConnectedPeer *cp;
1633 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1640 GNUNET_LOAD_value_set_decline (cp->transmission_delay,
1647 * Increase the host credit by a value.
1649 * @param host which peer to change the trust value on
1650 * @param value is the int value by which the
1651 * host credit is to be increased or decreased
1652 * @returns the actual change in trust (positive or negative)
1655 change_host_trust (struct ConnectedPeer *host, int value)
1659 GNUNET_assert (host != NULL);
1662 if (host->trust + value < host->trust)
1664 value = UINT32_MAX - host->trust;
1665 host->trust = UINT32_MAX;
1668 host->trust += value;
1672 if (host->trust < -value)
1674 value = -host->trust;
1678 host->trust += value;
1685 * Write host-trust information to a file - flush the buffer entry!
1688 flush_trust (void *cls,
1689 const GNUNET_HashCode *key,
1692 struct ConnectedPeer *host = value;
1695 struct GNUNET_PeerIdentity pid;
1697 if (host->trust == host->disk_trust)
1698 return GNUNET_OK; /* unchanged */
1699 GNUNET_PEER_resolve (host->pid,
1701 fn = get_trust_filename (&pid);
1702 if (host->trust == 0)
1704 if ((0 != UNLINK (fn)) && (errno != ENOENT))
1705 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
1706 GNUNET_ERROR_TYPE_BULK, "unlink", fn);
1710 trust = htonl (host->trust);
1711 if (sizeof(uint32_t) == GNUNET_DISK_fn_write (fn, &trust,
1713 GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE
1714 | GNUNET_DISK_PERM_GROUP_READ | GNUNET_DISK_PERM_OTHER_READ))
1715 host->disk_trust = host->trust;
1722 * Call this method periodically to scan data/hosts for new hosts.
1725 cron_flush_trust (void *cls,
1726 const struct GNUNET_SCHEDULER_TaskContext *tc)
1729 if (NULL == connected_peers)
1731 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1736 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1738 GNUNET_SCHEDULER_add_delayed (TRUST_FLUSH_FREQ, &cron_flush_trust, NULL);
1743 * Free (each) request made by the peer.
1745 * @param cls closure, points to peer that the request belongs to
1746 * @param key current key code
1747 * @param value value in the hash map
1748 * @return GNUNET_YES (we should continue to iterate)
1751 destroy_request (void *cls,
1752 const GNUNET_HashCode * key,
1755 const struct GNUNET_PeerIdentity * peer = cls;
1756 struct PendingRequest *pr = value;
1758 GNUNET_break (GNUNET_YES ==
1759 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
1762 destroy_pending_request (pr);
1768 * Method called whenever a peer disconnects.
1770 * @param cls closure, not used
1771 * @param peer peer identity this notification is about
1774 peer_disconnect_handler (void *cls,
1776 GNUNET_PeerIdentity * peer)
1778 struct ConnectedPeer *cp;
1779 struct PendingMessage *pm;
1781 struct MigrationReadyBlock *pos;
1782 struct MigrationReadyBlock *next;
1784 GNUNET_CONTAINER_multihashmap_get_multiple (peer_request_map,
1788 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1792 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1794 if (NULL != cp->last_client_replies[i])
1796 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1797 cp->last_client_replies[i] = NULL;
1800 GNUNET_break (GNUNET_YES ==
1801 GNUNET_CONTAINER_multihashmap_remove (connected_peers,
1804 /* remove this peer from migration considerations; schedule
1807 while (NULL != (pos = next))
1810 for (i=0;i<MIGRATION_LIST_SIZE;i++)
1812 if (pos->target_list[i] == cp->pid)
1814 GNUNET_PEER_change_rc (pos->target_list[i], -1);
1815 pos->target_list[i] = 0;
1818 if (pos->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers))
1820 delete_migration_block (pos);
1821 consider_migration_gathering ();
1824 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1825 &consider_migration,
1828 GNUNET_PEER_change_rc (cp->pid, -1);
1829 GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
1830 if (NULL != cp->cth)
1832 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
1835 if (cp->delayed_transmission_request_task != GNUNET_SCHEDULER_NO_TASK)
1837 GNUNET_SCHEDULER_cancel (cp->delayed_transmission_request_task);
1838 cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
1840 while (NULL != (pm = cp->pending_messages_head))
1841 destroy_pending_message (pm, 0 /* delivery failed */);
1842 GNUNET_LOAD_value_free (cp->transmission_delay);
1843 GNUNET_break (0 == cp->pending_requests);
1849 * Iterator over hash map entries that removes all occurences
1850 * of the given 'client' from the 'last_client_replies' of the
1851 * given connected peer.
1853 * @param cls closure, the 'struct GNUNET_SERVER_Client*' to remove
1854 * @param key current key code (unused)
1855 * @param value value in the hash map (the 'struct ConnectedPeer*' to change)
1856 * @return GNUNET_YES (we should continue to iterate)
1859 remove_client_from_last_client_replies (void *cls,
1860 const GNUNET_HashCode * key,
1863 struct GNUNET_SERVER_Client *client = cls;
1864 struct ConnectedPeer *cp = value;
1867 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1869 if (cp->last_client_replies[i] == client)
1871 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1872 cp->last_client_replies[i] = NULL;
1880 * A client disconnected. Remove all of its pending queries.
1882 * @param cls closure, NULL
1883 * @param client identification of the client
1886 handle_client_disconnect (void *cls,
1887 struct GNUNET_SERVER_Client
1890 struct ClientList *pos;
1891 struct ClientList *prev;
1892 struct ClientRequestList *rcl;
1893 struct ClientResponseMessage *creply;
1899 while ( (NULL != pos) &&
1900 (pos->client != client) )
1906 return; /* no requests pending for this client */
1907 while (NULL != (rcl = pos->rl_head))
1909 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1910 "Destroying pending request `%s' on disconnect\n",
1911 GNUNET_h2s (&rcl->req->query));
1912 destroy_pending_request (rcl->req);
1915 client_list = pos->next;
1917 prev->next = pos->next;
1918 if (pos->th != NULL)
1920 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
1923 while (NULL != (creply = pos->res_head))
1925 GNUNET_CONTAINER_DLL_remove (pos->res_head,
1928 GNUNET_free (creply);
1930 GNUNET_SERVER_client_drop (pos->client);
1932 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1933 &remove_client_from_last_client_replies,
1939 * Iterator to free peer entries.
1941 * @param cls closure, unused
1942 * @param key current key code
1943 * @param value value in the hash map (peer entry)
1944 * @return GNUNET_YES (we should continue to iterate)
1947 clean_peer (void *cls,
1948 const GNUNET_HashCode * key,
1951 peer_disconnect_handler (NULL, (const struct GNUNET_PeerIdentity*) key);
1957 * Task run during shutdown.
1963 shutdown_task (void *cls,
1964 const struct GNUNET_SCHEDULER_TaskContext *tc)
1968 GNUNET_DATASTORE_cancel (mig_qe);
1973 GNUNET_DATASTORE_cancel (dht_qe);
1976 if (GNUNET_SCHEDULER_NO_TASK != mig_task)
1978 GNUNET_SCHEDULER_cancel (mig_task);
1979 mig_task = GNUNET_SCHEDULER_NO_TASK;
1981 if (GNUNET_SCHEDULER_NO_TASK != dht_task)
1983 GNUNET_SCHEDULER_cancel (dht_task);
1984 dht_task = GNUNET_SCHEDULER_NO_TASK;
1986 while (client_list != NULL)
1987 handle_client_disconnect (NULL,
1988 client_list->client);
1989 cron_flush_trust (NULL, NULL);
1990 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1993 GNUNET_break (0 == GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap));
1994 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
1995 requests_by_expiration_heap = 0;
1996 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
1997 connected_peers = NULL;
1998 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (query_request_map));
1999 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
2000 query_request_map = NULL;
2001 GNUNET_LOAD_value_free (rt_entry_lifetime);
2002 rt_entry_lifetime = NULL;
2003 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (peer_request_map));
2004 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
2005 peer_request_map = NULL;
2006 GNUNET_assert (NULL != core);
2007 GNUNET_CORE_disconnect (core);
2011 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
2016 GNUNET_DATASTORE_disconnect (dsh,
2020 while (mig_head != NULL)
2021 delete_migration_block (mig_head);
2022 GNUNET_assert (0 == mig_size);
2023 GNUNET_DHT_disconnect (dht_handle);
2025 GNUNET_LOAD_value_free (datastore_get_load);
2026 datastore_get_load = NULL;
2027 GNUNET_LOAD_value_free (datastore_put_load);
2028 datastore_put_load = NULL;
2029 GNUNET_BLOCK_context_destroy (block_ctx);
2031 GNUNET_CONFIGURATION_destroy (block_cfg);
2034 GNUNET_free_non_null (trustDirectory);
2035 trustDirectory = NULL;
2039 /* ******************* Utility functions ******************** */
2043 * We've had to delay a request for transmission to core, but now
2044 * we should be ready. Run it.
2046 * @param cls the 'struct ConnectedPeer' for which a request was delayed
2047 * @param tc task context (unused)
2050 delayed_transmission_request (void *cls,
2051 const struct GNUNET_SCHEDULER_TaskContext *tc)
2053 struct ConnectedPeer *cp = cls;
2054 struct GNUNET_PeerIdentity pid;
2055 struct PendingMessage *pm;
2057 pm = cp->pending_messages_head;
2058 cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
2059 GNUNET_assert (cp->cth == NULL);
2062 GNUNET_PEER_resolve (cp->pid,
2064 cp->last_transmission_request_start = GNUNET_TIME_absolute_get ();
2065 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
2067 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
2076 * Transmit messages by copying it to the target buffer
2077 * "buf". "buf" will be NULL and "size" zero if the socket was closed
2078 * for writing in the meantime. In that case, do nothing
2079 * (the disconnect or shutdown handler will take care of the rest).
2080 * If we were able to transmit messages and there are still more
2081 * pending, ask core again for further calls to this function.
2083 * @param cls closure, pointer to the 'struct ConnectedPeer*'
2084 * @param size number of bytes available in buf
2085 * @param buf where the callee should write the message
2086 * @return number of bytes written to buf
2089 transmit_to_peer (void *cls,
2090 size_t size, void *buf)
2092 struct ConnectedPeer *cp = cls;
2094 struct PendingMessage *pm;
2095 struct PendingMessage *next_pm;
2096 struct GNUNET_TIME_Absolute now;
2097 struct GNUNET_TIME_Relative min_delay;
2098 struct MigrationReadyBlock *mb;
2099 struct MigrationReadyBlock *next;
2100 struct PutMessage migm;
2103 struct GNUNET_PeerIdentity pid;
2109 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2110 "Dropping message, core too busy.\n");
2112 GNUNET_LOAD_update (cp->transmission_delay,
2116 GNUNET_LOAD_update (cp->transmission_delay,
2117 GNUNET_TIME_absolute_get_duration (cp->last_transmission_request_start).rel_value);
2118 now = GNUNET_TIME_absolute_get ();
2120 min_delay = GNUNET_TIME_UNIT_FOREVER_REL;
2121 next_pm = cp->pending_messages_head;
2122 while ( (NULL != (pm = next_pm) ) &&
2123 (pm->msize <= size) )
2126 if (pm->delay_until.abs_value > now.abs_value)
2128 min_delay = GNUNET_TIME_relative_min (min_delay,
2129 GNUNET_TIME_absolute_get_remaining (pm->delay_until));
2132 memcpy (&cbuf[msize], &pm[1], pm->msize);
2135 if (NULL == pm->pml)
2137 GNUNET_CONTAINER_DLL_remove (cp->pending_messages_head,
2138 cp->pending_messages_tail,
2140 cp->pending_requests--;
2142 destroy_pending_message (pm, cp->pid);
2145 min_delay = GNUNET_TIME_UNIT_ZERO;
2146 if (NULL != cp->pending_messages_head)
2148 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == cp->delayed_transmission_request_task);
2149 cp->delayed_transmission_request_task
2150 = GNUNET_SCHEDULER_add_delayed (min_delay,
2151 &delayed_transmission_request,
2156 GNUNET_PEER_resolve (cp->pid,
2159 while (NULL != (mb = next))
2162 for (i=0;i<MIGRATION_LIST_SIZE;i++)
2164 if ( (cp->pid == mb->target_list[i]) &&
2165 (mb->size + sizeof (migm) <= size) )
2167 GNUNET_PEER_change_rc (mb->target_list[i], -1);
2168 mb->target_list[i] = 0;
2170 memset (&migm, 0, sizeof (migm));
2171 migm.header.size = htons (sizeof (migm) + mb->size);
2172 migm.header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2173 migm.type = htonl (mb->type);
2174 migm.expiration = GNUNET_TIME_absolute_hton (mb->expiration);
2175 memcpy (&cbuf[msize], &migm, sizeof (migm));
2176 msize += sizeof (migm);
2177 size -= sizeof (migm);
2178 memcpy (&cbuf[msize], &mb[1], mb->size);
2182 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2183 "Pushing migration block `%s' (%u bytes) to `%s'\n",
2184 GNUNET_h2s (&mb->query),
2185 (unsigned int) mb->size,
2193 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2194 "Migration block `%s' (%u bytes) is not on migration list for peer `%s'\n",
2195 GNUNET_h2s (&mb->query),
2196 (unsigned int) mb->size,
2201 if ( (mb->used_targets >= MIGRATION_TARGET_COUNT) ||
2202 (mb->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers)) )
2204 delete_migration_block (mb);
2205 consider_migration_gathering ();
2208 consider_migration (NULL,
2213 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2214 "Transmitting %u bytes to peer with PID %u\n",
2215 (unsigned int) msize,
2216 (unsigned int) cp->pid);
2223 * Add a message to the set of pending messages for the given peer.
2225 * @param cp peer to send message to
2226 * @param pm message to queue
2227 * @param pr request on which behalf this message is being queued
2230 add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
2231 struct PendingMessage *pm,
2232 struct PendingRequest *pr)
2234 struct PendingMessage *pos;
2235 struct PendingMessageList *pml;
2236 struct GNUNET_PeerIdentity pid;
2238 GNUNET_assert (pm->next == NULL);
2239 GNUNET_assert (pm->pml == NULL);
2242 pml = GNUNET_malloc (sizeof (struct PendingMessageList));
2247 GNUNET_CONTAINER_DLL_insert (pr->pending_head,
2251 pos = cp->pending_messages_head;
2252 while ( (pos != NULL) &&
2253 (pm->priority < pos->priority) )
2255 GNUNET_CONTAINER_DLL_insert_after (cp->pending_messages_head,
2256 cp->pending_messages_tail,
2259 cp->pending_requests++;
2260 if (cp->pending_requests > MAX_QUEUE_PER_PEER)
2262 GNUNET_STATISTICS_update (stats,
2263 gettext_noop ("# P2P searches discarded (queue length bound)"),
2266 destroy_pending_message (cp->pending_messages_tail, 0);
2268 GNUNET_PEER_resolve (cp->pid, &pid);
2269 if (NULL != cp->cth)
2271 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
2274 if (cp->delayed_transmission_request_task != GNUNET_SCHEDULER_NO_TASK)
2276 GNUNET_SCHEDULER_cancel (cp->delayed_transmission_request_task);
2277 cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
2279 /* need to schedule transmission */
2280 cp->last_transmission_request_start = GNUNET_TIME_absolute_get ();
2281 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
2282 cp->pending_messages_head->priority,
2285 cp->pending_messages_head->msize,
2288 if (cp->cth == NULL)
2291 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2292 "Failed to schedule transmission with core!\n");
2294 GNUNET_STATISTICS_update (stats,
2295 gettext_noop ("# CORE transmission failures"),
2303 * Test if the DATABASE (GET) load on this peer is too high
2304 * to even consider processing the query at
2307 * @return GNUNET_YES if the load is too high to do anything (load high)
2308 * GNUNET_NO to process normally (load normal)
2309 * GNUNET_SYSERR to process for free (load low)
2312 test_get_load_too_high (uint32_t priority)
2316 ld = GNUNET_LOAD_get_load (datastore_get_load);
2318 return GNUNET_SYSERR;
2328 * Test if the DATABASE (PUT) load on this peer is too high
2329 * to even consider processing the query at
2332 * @return GNUNET_YES if the load is too high to do anything (load high)
2333 * GNUNET_NO to process normally (load normal or low)
2336 test_put_load_too_high (uint32_t priority)
2340 if (GNUNET_LOAD_get_average (datastore_put_load) < 50)
2341 return GNUNET_NO; /* very fast */
2342 ld = GNUNET_LOAD_get_load (datastore_put_load);
2343 if (ld < 2.0 * (1 + priority))
2345 GNUNET_STATISTICS_update (stats,
2346 gettext_noop ("# storage requests dropped due to high load"),
2353 /* ******************* Pending Request Refresh Task ******************** */
2358 * We use a random delay to make the timing of requests less
2359 * predictable. This function returns such a random delay. We add a base
2360 * delay of MAX_CORK_DELAY (1s).
2362 * FIXME: make schedule dependent on the specifics of the request?
2363 * Or bandwidth and number of connected peers and load?
2365 * @return random delay to use for some request, between 1s and 1000+TTL_DECREMENT ms
2367 static struct GNUNET_TIME_Relative
2368 get_processing_delay ()
2371 GNUNET_TIME_relative_add (GNUNET_CONSTANTS_MAX_CORK_DELAY,
2372 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
2373 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2379 * We're processing a GET request from another peer and have decided
2380 * to forward it to other peers. This function is called periodically
2381 * and should forward the request to other peers until we have all
2382 * possible replies. If we have transmitted the *only* reply to
2383 * the initiator we should destroy the pending request. If we have
2384 * many replies in the queue to the initiator, we should delay sending
2385 * out more queries until the reply queue has shrunk some.
2387 * @param cls our "struct ProcessGetContext *"
2391 forward_request_task (void *cls,
2392 const struct GNUNET_SCHEDULER_TaskContext *tc);
2396 * Function called after we either failed or succeeded
2397 * at transmitting a query to a peer.
2399 * @param cls the requests "struct PendingRequest*"
2400 * @param tpid ID of receiving peer, 0 on transmission error
2403 transmit_query_continuation (void *cls,
2404 GNUNET_PEER_Id tpid)
2406 struct PendingRequest *pr = cls;
2409 GNUNET_STATISTICS_update (stats,
2410 gettext_noop ("# queries scheduled for forwarding"),
2416 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2417 "Transmission of request failed, will try again later.\n");
2419 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2420 pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2421 &forward_request_task,
2426 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2427 "Transmitted query `%s'\n",
2428 GNUNET_h2s (&pr->query));
2430 GNUNET_STATISTICS_update (stats,
2431 gettext_noop ("# queries forwarded"),
2434 for (i=0;i<pr->used_targets_off;i++)
2435 if (pr->used_targets[i].pid == tpid)
2436 break; /* found match! */
2437 if (i == pr->used_targets_off)
2439 /* need to create new entry */
2440 if (pr->used_targets_off == pr->used_targets_size)
2441 GNUNET_array_grow (pr->used_targets,
2442 pr->used_targets_size,
2443 pr->used_targets_size * 2 + 2);
2444 GNUNET_PEER_change_rc (tpid, 1);
2445 pr->used_targets[pr->used_targets_off].pid = tpid;
2446 pr->used_targets[pr->used_targets_off].num_requests = 0;
2447 i = pr->used_targets_off++;
2449 pr->used_targets[i].last_request_time = GNUNET_TIME_absolute_get ();
2450 pr->used_targets[i].num_requests++;
2451 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2452 pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2453 &forward_request_task,
2459 * How many bytes should a bloomfilter be if we have already seen
2460 * entry_count responses? Note that BLOOMFILTER_K gives us the number
2461 * of bits set per entry. Furthermore, we should not re-size the
2462 * filter too often (to keep it cheap).
2464 * Since other peers will also add entries but not resize the filter,
2465 * we should generally pick a slightly larger size than what the
2466 * strict math would suggest.
2468 * @return must be a power of two and smaller or equal to 2^15.
2471 compute_bloomfilter_size (unsigned int entry_count)
2474 unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
2475 uint16_t max = 1 << 15;
2477 if (entry_count > max)
2480 while ((size < max) && (size < ideal))
2489 * Recalculate our bloom filter for filtering replies. This function
2490 * will create a new bloom filter from scratch, so it should only be
2491 * called if we have no bloomfilter at all (and hence can create a
2492 * fresh one of minimal size without problems) OR if our peer is the
2493 * initiator (in which case we may resize to larger than mimimum size).
2495 * @param pr request for which the BF is to be recomputed
2498 refresh_bloomfilter (struct PendingRequest *pr)
2502 GNUNET_HashCode mhash;
2504 nsize = compute_bloomfilter_size (pr->replies_seen_off);
2505 if (nsize == pr->bf_size)
2506 return; /* size not changed */
2508 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
2509 pr->bf_size = nsize;
2510 pr->mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
2511 pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
2514 for (i=0;i<pr->replies_seen_off;i++)
2516 GNUNET_BLOCK_mingle_hash (&pr->replies_seen[i],
2519 GNUNET_CONTAINER_bloomfilter_add (pr->bf, &mhash);
2525 * Function called after we've tried to reserve a certain amount of
2526 * bandwidth for a reply. Check if we succeeded and if so send our
2529 * @param cls the requests "struct PendingRequest*"
2530 * @param peer identifies the peer
2531 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
2532 * @param bpm_out set to the current bandwidth limit (sending) for this peer
2533 * @param amount set to the amount that was actually reserved or unreserved
2534 * @param preference current traffic preference for the given peer
2537 target_reservation_cb (void *cls,
2539 GNUNET_PeerIdentity * peer,
2540 struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
2541 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
2543 uint64_t preference)
2545 struct PendingRequest *pr = cls;
2546 struct ConnectedPeer *cp;
2547 struct PendingMessage *pm;
2548 struct GetMessage *gm;
2549 GNUNET_HashCode *ext;
2560 /* error in communication with core, try again later */
2561 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2562 pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2563 &forward_request_task,
2567 /* (3) transmit, update ttl/priority */
2568 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2572 /* Peer must have just left */
2574 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2575 "Selected peer disconnected!\n");
2577 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2578 pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2579 &forward_request_task,
2583 no_route = GNUNET_NO;
2589 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2590 "Failed to reserve bandwidth for reply (got %d/%u bytes only)!\n",
2594 GNUNET_STATISTICS_update (stats,
2595 gettext_noop ("# reply bandwidth reservation requests failed"),
2598 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2599 pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2600 &forward_request_task,
2602 return; /* this target round failed */
2604 no_route = GNUNET_YES;
2607 GNUNET_STATISTICS_update (stats,
2608 gettext_noop ("# queries scheduled for forwarding"),
2611 for (i=0;i<pr->used_targets_off;i++)
2612 if (pr->used_targets[i].pid == cp->pid)
2614 GNUNET_STATISTICS_update (stats,
2615 gettext_noop ("# queries retransmitted to same target"),
2621 /* build message and insert message into priority queue */
2623 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2624 "Forwarding request `%s' to `%4s'!\n",
2625 GNUNET_h2s (&pr->query),
2630 if (GNUNET_YES == no_route)
2632 bm |= GET_MESSAGE_BIT_RETURN_TO;
2635 if (pr->namespace != NULL)
2637 bm |= GET_MESSAGE_BIT_SKS_NAMESPACE;
2640 if (pr->target_pid != 0)
2642 bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
2645 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
2646 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
2647 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
2649 gm = (struct GetMessage*) &pm[1];
2650 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
2651 gm->header.size = htons (msize);
2652 gm->type = htonl (pr->type);
2653 pr->remaining_priority /= 2;
2654 gm->priority = htonl (pr->remaining_priority);
2655 gm->ttl = htonl (pr->ttl);
2656 gm->filter_mutator = htonl(pr->mingle);
2657 gm->hash_bitmap = htonl (bm);
2658 gm->query = pr->query;
2659 ext = (GNUNET_HashCode*) &gm[1];
2661 if (GNUNET_YES == no_route)
2662 GNUNET_PEER_resolve (pr->cp->pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
2663 if (pr->namespace != NULL)
2664 memcpy (&ext[k++], pr->namespace, sizeof (GNUNET_HashCode));
2665 if (pr->target_pid != 0)
2666 GNUNET_PEER_resolve (pr->target_pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
2667 bfdata = (char *) &ext[k];
2669 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
2672 pm->cont = &transmit_query_continuation;
2674 cp->last_request_times[(cp->last_request_times_off++) % MAX_QUEUE_PER_PEER] = GNUNET_TIME_absolute_get ();
2675 add_to_pending_messages_for_peer (cp, pm, pr);
2680 * Closure used for "target_peer_select_cb".
2682 struct PeerSelectionContext
2685 * The request for which we are selecting
2688 struct PendingRequest *pr;
2691 * Current "prime" target.
2693 struct GNUNET_PeerIdentity target;
2696 * How much do we like this target?
2698 double target_score;
2704 * Function called for each connected peer to determine
2705 * which one(s) would make good targets for forwarding.
2707 * @param cls closure (struct PeerSelectionContext)
2708 * @param key current key code (peer identity)
2709 * @param value value in the hash map (struct ConnectedPeer)
2710 * @return GNUNET_YES if we should continue to
2715 target_peer_select_cb (void *cls,
2716 const GNUNET_HashCode * key,
2719 struct PeerSelectionContext *psc = cls;
2720 struct ConnectedPeer *cp = value;
2721 struct PendingRequest *pr = psc->pr;
2722 struct GNUNET_TIME_Relative delay;
2727 /* 1) check that this peer is not the initiator */
2731 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2732 "Skipping initiator in forwarding selection\n");
2734 return GNUNET_YES; /* skip */
2737 /* 2) check if we have already (recently) forwarded to this peer */
2738 /* 2a) this particular request */
2740 for (i=0;i<pr->used_targets_off;i++)
2741 if (pr->used_targets[i].pid == cp->pid)
2743 pc = pr->used_targets[i].num_requests;
2744 GNUNET_assert (pc > 0);
2745 if (0 != GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2746 RETRY_PROBABILITY_INV * pc))
2749 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2750 "NOT re-trying query that was previously transmitted %u times\n",
2753 return GNUNET_YES; /* skip */
2760 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2761 "Re-trying query that was previously transmitted %u times to this peer\n",
2765 /* 2b) many other requests to this peer */
2766 delay = GNUNET_TIME_absolute_get_duration (cp->last_request_times[cp->last_request_times_off % MAX_QUEUE_PER_PEER]);
2767 if (delay.rel_value <= cp->avg_delay.rel_value)
2770 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2771 "NOT sending query since we send %u others to this peer in the last %llums\n",
2773 cp->avg_delay.rel_value);
2775 return GNUNET_YES; /* skip */
2778 /* 3) calculate how much we'd like to forward to this peer,
2779 starting with a random value that is strong enough
2780 to at least give any peer a chance sometimes
2781 (compared to the other factors that come later) */
2782 /* 3a) count successful (recent) routes from cp for same source */
2785 score = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2786 P2P_SUCCESS_LIST_SIZE);
2787 for (i=0;i<P2P_SUCCESS_LIST_SIZE;i++)
2788 if (cp->last_p2p_replies[i] == pr->cp->pid)
2789 score += 1.0; /* likely successful based on hot path */
2793 score = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2794 CS2P_SUCCESS_LIST_SIZE);
2795 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
2796 if (cp->last_client_replies[i] == pr->client_request_list->client_list->client)
2797 score += 1.0; /* likely successful based on hot path */
2799 /* 3b) include latency */
2800 if (cp->avg_delay.rel_value < 4 * TTL_DECREMENT)
2801 score += 1.0; /* likely fast based on latency */
2802 /* 3c) include priorities */
2803 if (cp->avg_priority <= pr->remaining_priority / 2.0)
2804 score += 1.0; /* likely successful based on priorities */
2805 /* 3d) penalize for queue size */
2806 score -= (2.0 * cp->pending_requests / (double) MAX_QUEUE_PER_PEER);
2807 /* 3e) include peer proximity */
2808 score -= (2.0 * (GNUNET_CRYPTO_hash_distance_u32 (key,
2809 &pr->query)) / (double) UINT32_MAX);
2810 /* 4) super-bonus for being the known target */
2811 if (pr->target_pid == cp->pid)
2813 /* store best-fit in closure */
2815 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2816 "Peer `%s' gets score %f for forwarding query, max is %f\n",
2821 score++; /* avoid zero */
2822 if (score > psc->target_score)
2824 psc->target_score = score;
2825 psc->target.hashPubKey = *key;
2832 * The priority level imposes a bound on the maximum
2833 * value for the ttl that can be requested.
2835 * @param ttl_in requested ttl
2836 * @param prio given priority
2837 * @return ttl_in if ttl_in is below the limit,
2838 * otherwise the ttl-limit for the given priority
2841 bound_ttl (int32_t ttl_in, uint32_t prio)
2843 unsigned long long allowed;
2847 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
2848 if (ttl_in > allowed)
2850 if (allowed >= (1 << 30))
2859 * Iterator called on each result obtained for a DHT
2860 * operation that expects a reply
2862 * @param cls closure
2863 * @param exp when will this value expire
2864 * @param key key of the result
2865 * @param get_path NULL-terminated array of pointers
2866 * to the peers on reverse GET path (or NULL if not recorded)
2867 * @param put_path NULL-terminated array of pointers
2868 * to the peers on the PUT path (or NULL if not recorded)
2869 * @param type type of the result
2870 * @param size number of bytes in data
2871 * @param data pointer to the result data
2874 process_dht_reply (void *cls,
2875 struct GNUNET_TIME_Absolute exp,
2876 const GNUNET_HashCode * key,
2877 const struct GNUNET_PeerIdentity * const *get_path,
2878 const struct GNUNET_PeerIdentity * const *put_path,
2879 enum GNUNET_BLOCK_Type type,
2885 * We're processing a GET request and have decided
2886 * to forward it to other peers. This function is called periodically
2887 * and should forward the request to other peers until we have all
2888 * possible replies. If we have transmitted the *only* reply to
2889 * the initiator we should destroy the pending request. If we have
2890 * many replies in the queue to the initiator, we should delay sending
2891 * out more queries until the reply queue has shrunk some.
2893 * @param cls our "struct ProcessGetContext *"
2897 forward_request_task (void *cls,
2898 const struct GNUNET_SCHEDULER_TaskContext *tc)
2900 struct PendingRequest *pr = cls;
2901 struct PeerSelectionContext psc;
2902 struct ConnectedPeer *cp;
2903 struct GNUNET_TIME_Relative delay;
2905 pr->task = GNUNET_SCHEDULER_NO_TASK;
2906 if (pr->irc != NULL)
2909 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2910 "Forwarding of query `%s' not attempted due to pending local lookup!\n",
2911 GNUNET_h2s (&pr->query));
2913 return; /* already pending */
2915 if (GNUNET_YES == pr->local_only)
2916 return; /* configured to not do P2P search */
2918 if ( (0 == pr->anonymity_level) &&
2919 (GNUNET_YES != pr->forward_only) &&
2920 (pr->type != GNUNET_BLOCK_TYPE_FS_DBLOCK) &&
2921 (pr->type != GNUNET_BLOCK_TYPE_FS_IBLOCK) )
2923 pr->dht_get = GNUNET_DHT_get_start (dht_handle,
2924 GNUNET_TIME_UNIT_FOREVER_REL,
2931 (pr->namespace != NULL) ? sizeof (GNUNET_HashCode) : 0,
2935 /* (1) select target */
2937 psc.target_score = -DBL_MAX;
2938 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
2939 &target_peer_select_cb,
2941 if (psc.target_score == -DBL_MAX)
2943 delay = get_processing_delay ();
2945 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2946 "No peer selected for forwarding of query `%s', will try again in %llu ms!\n",
2947 GNUNET_h2s (&pr->query),
2950 pr->task = GNUNET_SCHEDULER_add_delayed (delay,
2951 &forward_request_task,
2953 return; /* nobody selected */
2955 /* (3) update TTL/priority */
2956 if (pr->client_request_list != NULL)
2958 /* FIXME: use better algorithm!? */
2959 if (0 == GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2962 /* bound priority we use by priorities we see from other peers
2963 rounded up (must round up so that we can see non-zero
2964 priorities, but round up as little as possible to make it
2965 plausible that we forwarded another peers request) */
2966 if (pr->priority > current_priorities + 1.0)
2967 pr->priority = (uint32_t) current_priorities + 1.0;
2968 pr->ttl = bound_ttl (pr->ttl + TTL_DECREMENT * 2,
2971 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2972 "Trying query `%s' with priority %u and TTL %d.\n",
2973 GNUNET_h2s (&pr->query),
2979 /* (3) reserve reply bandwidth */
2980 if (GNUNET_NO == pr->forward_only)
2982 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2983 &psc.target.hashPubKey);
2984 GNUNET_assert (NULL != cp);
2985 pr->irc = GNUNET_CORE_peer_change_preference (cfg,
2987 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
2988 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
2991 &target_reservation_cb,
2993 cp->inc_preference = 0;
2997 /* force forwarding */
2998 static struct GNUNET_BANDWIDTH_Value32NBO zerobw;
2999 target_reservation_cb (pr, &psc.target,
3000 zerobw, zerobw, 0, 0.0);
3005 /* **************************** P2P PUT Handling ************************ */
3009 * Function called after we either failed or succeeded
3010 * at transmitting a reply to a peer.
3012 * @param cls the requests "struct PendingRequest*"
3013 * @param tpid ID of receiving peer, 0 on transmission error
3016 transmit_reply_continuation (void *cls,
3017 GNUNET_PEER_Id tpid)
3019 struct PendingRequest *pr = cls;
3023 case GNUNET_BLOCK_TYPE_FS_DBLOCK:
3024 case GNUNET_BLOCK_TYPE_FS_IBLOCK:
3025 /* only one reply expected, done with the request! */
3026 destroy_pending_request (pr);
3028 case GNUNET_BLOCK_TYPE_ANY:
3029 case GNUNET_BLOCK_TYPE_FS_KBLOCK:
3030 case GNUNET_BLOCK_TYPE_FS_SBLOCK:
3040 * Transmit the given message by copying it to the target buffer
3041 * "buf". "buf" will be NULL and "size" zero if the socket was closed
3042 * for writing in the meantime. In that case, do nothing
3043 * (the disconnect or shutdown handler will take care of the rest).
3044 * If we were able to transmit messages and there are still more
3045 * pending, ask core again for further calls to this function.
3047 * @param cls closure, pointer to the 'struct ClientList*'
3048 * @param size number of bytes available in buf
3049 * @param buf where the callee should write the message
3050 * @return number of bytes written to buf
3053 transmit_to_client (void *cls,
3054 size_t size, void *buf)
3056 struct ClientList *cl = cls;
3058 struct ClientResponseMessage *creply;
3065 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3066 "Not sending reply, client communication problem.\n");
3071 while ( (NULL != (creply = cl->res_head) ) &&
3072 (creply->msize <= size) )
3074 memcpy (&cbuf[msize], &creply[1], creply->msize);
3075 msize += creply->msize;
3076 size -= creply->msize;
3077 GNUNET_CONTAINER_DLL_remove (cl->res_head,
3080 GNUNET_free (creply);
3083 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
3085 GNUNET_TIME_UNIT_FOREVER_REL,
3086 &transmit_to_client,
3089 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3090 "Transmitted %u bytes to client\n",
3091 (unsigned int) msize);
3098 * Closure for "process_reply" function.
3100 struct ProcessReplyClosure
3103 * The data for the reply.
3108 * Who gave us this reply? NULL for local host (or DHT)
3110 struct ConnectedPeer *sender;
3113 * When the reply expires.
3115 struct GNUNET_TIME_Absolute expiration;
3123 * Type of the block.
3125 enum GNUNET_BLOCK_Type type;
3128 * How much was this reply worth to us?
3133 * Evaluation result (returned).
3135 enum GNUNET_BLOCK_EvaluationResult eval;
3138 * Did we finish processing the associated request?
3143 * Did we find a matching request?
3150 * We have received a reply; handle it!
3152 * @param cls response (struct ProcessReplyClosure)
3153 * @param key our query
3154 * @param value value in the hash map (info about the query)
3155 * @return GNUNET_YES (we should continue to iterate)
3158 process_reply (void *cls,
3159 const GNUNET_HashCode * key,
3162 struct ProcessReplyClosure *prq = cls;
3163 struct PendingRequest *pr = value;
3164 struct PendingMessage *reply;
3165 struct ClientResponseMessage *creply;
3166 struct ClientList *cl;
3167 struct PutMessage *pm;
3168 struct ConnectedPeer *cp;
3169 struct GNUNET_TIME_Relative cur_delay;
3171 struct GNUNET_TIME_Relative art_delay;
3177 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3178 "Matched result (type %u) for query `%s' with pending request\n",
3179 (unsigned int) prq->type,
3182 GNUNET_STATISTICS_update (stats,
3183 gettext_noop ("# replies received and matched"),
3186 if (prq->sender != NULL)
3188 for (i=0;i<pr->used_targets_off;i++)
3189 if (pr->used_targets[i].pid == prq->sender->pid)
3191 if (i < pr->used_targets_off)
3193 cur_delay = GNUNET_TIME_absolute_get_duration (pr->used_targets[i].last_request_time);
3194 prq->sender->avg_delay.rel_value
3195 = (prq->sender->avg_delay.rel_value *
3196 (RUNAVG_DELAY_N - 1) + cur_delay.rel_value) / RUNAVG_DELAY_N;
3197 prq->sender->avg_priority
3198 = (prq->sender->avg_priority *
3199 (RUNAVG_DELAY_N - 1) + pr->priority) / (double) RUNAVG_DELAY_N;
3203 GNUNET_PEER_change_rc (prq->sender->last_p2p_replies
3204 [prq->sender->last_p2p_replies_woff % P2P_SUCCESS_LIST_SIZE],
3206 GNUNET_PEER_change_rc (pr->cp->pid, 1);
3207 prq->sender->last_p2p_replies
3208 [(prq->sender->last_p2p_replies_woff++) % P2P_SUCCESS_LIST_SIZE]
3213 if (NULL != prq->sender->last_client_replies
3214 [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE])
3215 GNUNET_SERVER_client_drop (prq->sender->last_client_replies
3216 [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE]);
3217 prq->sender->last_client_replies
3218 [(prq->sender->last_client_replies_woff++) % CS2P_SUCCESS_LIST_SIZE]
3219 = pr->client_request_list->client_list->client;
3220 GNUNET_SERVER_client_keep (pr->client_request_list->client_list->client);
3223 prq->eval = GNUNET_BLOCK_evaluate (block_ctx,
3228 pr->namespace, (pr->namespace != NULL) ? sizeof (GNUNET_HashCode) : 0,
3233 case GNUNET_BLOCK_EVALUATION_OK_MORE:
3235 case GNUNET_BLOCK_EVALUATION_OK_LAST:
3236 while (NULL != pr->pending_head)
3237 destroy_pending_message_list_entry (pr->pending_head);
3240 if (pr->client_request_list != NULL)
3241 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
3243 GNUNET_DATASTORE_cancel (pr->qe);
3246 pr->do_remove = GNUNET_YES;
3247 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
3249 GNUNET_SCHEDULER_cancel (pr->task);
3250 pr->task = GNUNET_SCHEDULER_NO_TASK;
3252 GNUNET_break (GNUNET_YES ==
3253 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
3256 GNUNET_LOAD_update (rt_entry_lifetime,
3257 GNUNET_TIME_absolute_get_duration (pr->start_time).rel_value);
3259 case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
3260 GNUNET_STATISTICS_update (stats,
3261 gettext_noop ("# duplicate replies discarded (bloomfilter)"),
3265 /* GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3266 "Duplicate response `%s', discarding.\n",
3267 GNUNET_h2s (&mhash));*/
3269 return GNUNET_YES; /* duplicate */
3270 case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
3271 return GNUNET_YES; /* wrong namespace */
3272 case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
3275 case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
3278 case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
3279 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3280 _("Unsupported block type %u\n"),
3284 if (pr->client_request_list != NULL)
3286 if (pr->replies_seen_size == pr->replies_seen_off)
3287 GNUNET_array_grow (pr->replies_seen,
3288 pr->replies_seen_size,
3289 pr->replies_seen_size * 2 + 4);
3290 GNUNET_CRYPTO_hash (prq->data,
3292 &pr->replies_seen[pr->replies_seen_off++]);
3293 refresh_bloomfilter (pr);
3295 if (NULL == prq->sender)
3298 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3299 "Found result for query `%s' in local datastore\n",
3302 GNUNET_STATISTICS_update (stats,
3303 gettext_noop ("# results found locally"),
3307 prq->priority += pr->remaining_priority;
3308 pr->remaining_priority = 0;
3309 pr->results_found++;
3310 prq->request_found = GNUNET_YES;
3311 if (NULL != pr->client_request_list)
3313 GNUNET_STATISTICS_update (stats,
3314 gettext_noop ("# replies received for local clients"),
3317 cl = pr->client_request_list->client_list;
3318 msize = sizeof (struct PutMessage) + prq->size;
3319 creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
3320 creply->msize = msize;
3321 creply->client_list = cl;
3322 GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
3326 pm = (struct PutMessage*) &creply[1];
3327 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
3328 pm->header.size = htons (msize);
3329 pm->type = htonl (prq->type);
3330 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
3331 memcpy (&pm[1], prq->data, prq->size);
3335 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3336 "Transmitting result for query `%s' to client\n",
3339 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
3341 GNUNET_TIME_UNIT_FOREVER_REL,
3342 &transmit_to_client,
3345 GNUNET_break (cl->th != NULL);
3348 prq->finished = GNUNET_YES;
3349 destroy_pending_request (pr);
3356 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3357 "Transmitting result for query `%s' to other peer (PID=%u)\n",
3359 (unsigned int) cp->pid);
3361 GNUNET_STATISTICS_update (stats,
3362 gettext_noop ("# replies received for other peers"),
3365 msize = sizeof (struct PutMessage) + prq->size;
3366 reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
3367 reply->cont = &transmit_reply_continuation;
3368 reply->cont_cls = pr;
3370 art_delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
3371 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3374 = GNUNET_TIME_relative_to_absolute (art_delay);
3375 GNUNET_STATISTICS_update (stats,
3376 gettext_noop ("cummulative artificial delay introduced (ms)"),
3377 art_delay.abs_value,
3380 reply->msize = msize;
3381 reply->priority = UINT32_MAX; /* send replies first! */
3382 pm = (struct PutMessage*) &reply[1];
3383 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
3384 pm->header.size = htons (msize);
3385 pm->type = htonl (prq->type);
3386 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
3387 memcpy (&pm[1], prq->data, prq->size);
3388 add_to_pending_messages_for_peer (cp, reply, pr);
3395 * Iterator called on each result obtained for a DHT
3396 * operation that expects a reply
3398 * @param cls closure
3399 * @param exp when will this value expire
3400 * @param key key of the result
3401 * @param get_path NULL-terminated array of pointers
3402 * to the peers on reverse GET path (or NULL if not recorded)
3403 * @param put_path NULL-terminated array of pointers
3404 * to the peers on the PUT path (or NULL if not recorded)
3405 * @param type type of the result
3406 * @param size number of bytes in data
3407 * @param data pointer to the result data
3410 process_dht_reply (void *cls,
3411 struct GNUNET_TIME_Absolute exp,
3412 const GNUNET_HashCode * key,
3413 const struct GNUNET_PeerIdentity * const *get_path,
3414 const struct GNUNET_PeerIdentity * const *put_path,
3415 enum GNUNET_BLOCK_Type type,
3419 struct PendingRequest *pr = cls;
3420 struct ProcessReplyClosure prq;
3422 memset (&prq, 0, sizeof (prq));
3424 prq.expiration = exp;
3427 process_reply (&prq, key, pr);
3433 * Continuation called to notify client about result of the
3436 * @param cls closure
3437 * @param success GNUNET_SYSERR on failure
3438 * @param msg NULL on success, otherwise an error message
3441 put_migration_continuation (void *cls,
3445 struct GNUNET_TIME_Absolute *start = cls;
3446 struct GNUNET_TIME_Relative delay;
3448 delay = GNUNET_TIME_absolute_get_duration (*start);
3449 GNUNET_free (start);
3450 GNUNET_LOAD_update (datastore_put_load,
3452 if (GNUNET_OK == success)
3454 GNUNET_STATISTICS_update (stats,
3455 gettext_noop ("# datastore 'put' failures"),
3462 * Handle P2P "PUT" message.
3464 * @param cls closure, always NULL
3465 * @param other the other peer involved (sender or receiver, NULL
3466 * for loopback messages where we are both sender and receiver)
3467 * @param message the actual message
3468 * @param latency reported latency of the connection with 'other'
3469 * @param distance reported distance (DV) to 'other'
3470 * @return GNUNET_OK to keep the connection open,
3471 * GNUNET_SYSERR to close it (signal serious error)
3474 handle_p2p_put (void *cls,
3475 const struct GNUNET_PeerIdentity *other,
3476 const struct GNUNET_MessageHeader *message,
3477 struct GNUNET_TIME_Relative latency,
3480 const struct PutMessage *put;
3483 enum GNUNET_BLOCK_Type type;
3484 struct GNUNET_TIME_Absolute expiration;
3485 GNUNET_HashCode query;
3486 struct ProcessReplyClosure prq;
3487 struct GNUNET_TIME_Absolute *start;
3488 struct GNUNET_TIME_Relative block_time;
3490 struct ConnectedPeer *cp;
3491 struct PendingMessage *pm;
3492 struct MigrationStopMessage *msm;
3494 msize = ntohs (message->size);
3495 if (msize < sizeof (struct PutMessage))
3498 return GNUNET_SYSERR;
3500 put = (const struct PutMessage*) message;
3501 dsize = msize - sizeof (struct PutMessage);
3502 type = ntohl (put->type);
3503 expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
3505 if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
3506 return GNUNET_SYSERR;
3508 GNUNET_BLOCK_get_key (block_ctx,
3514 GNUNET_break_op (0);
3515 return GNUNET_SYSERR;
3518 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3519 "Received result for query `%s' from peer `%4s'\n",
3520 GNUNET_h2s (&query),
3521 GNUNET_i2s (other));
3523 GNUNET_STATISTICS_update (stats,
3524 gettext_noop ("# replies received (overall)"),
3527 /* now, lookup 'query' */
3528 prq.data = (const void*) &put[1];
3530 prq.sender = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3531 &other->hashPubKey);
3536 prq.expiration = expiration;
3538 prq.finished = GNUNET_NO;
3539 prq.request_found = GNUNET_NO;
3540 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
3544 if (prq.sender != NULL)
3546 prq.sender->inc_preference += CONTENT_BANDWIDTH_VALUE + 1000 * prq.priority;
3547 prq.sender->trust += prq.priority;
3549 if ( (GNUNET_YES == active_migration) &&
3550 (GNUNET_NO == test_put_load_too_high (prq.priority)) )
3553 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3554 "Replicating result for query `%s' with priority %u\n",
3555 GNUNET_h2s (&query),
3558 start = GNUNET_malloc (sizeof (struct GNUNET_TIME_Absolute));
3559 *start = GNUNET_TIME_absolute_get ();
3560 GNUNET_DATASTORE_put (dsh,
3561 0, &query, dsize, &put[1],
3562 type, prq.priority, 1 /* anonymity */,
3564 1 + prq.priority, MAX_DATASTORE_QUEUE,
3565 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
3566 &put_migration_continuation,
3569 putl = GNUNET_LOAD_get_load (datastore_put_load);
3570 if ( (GNUNET_NO == prq.request_found) &&
3571 ( (GNUNET_YES != active_migration) ||
3572 (putl > 2.5 * (1 + prq.priority)) ) )
3574 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3575 &other->hashPubKey);
3576 if (GNUNET_TIME_absolute_get_duration (cp->last_migration_block).rel_value < 5000)
3577 return GNUNET_OK; /* already blocked */
3578 /* We're too busy; send MigrationStop message! */
3579 if (GNUNET_YES != active_migration)
3580 putl = 1.0 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 5);
3581 block_time = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
3582 5000 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3583 (unsigned int) (60000 * putl * putl)));
3585 cp->last_migration_block = GNUNET_TIME_relative_to_absolute (block_time);
3586 pm = GNUNET_malloc (sizeof (struct PendingMessage) +
3587 sizeof (struct MigrationStopMessage));
3588 pm->msize = sizeof (struct MigrationStopMessage);
3589 pm->priority = UINT32_MAX;
3590 msm = (struct MigrationStopMessage*) &pm[1];
3591 msm->header.size = htons (sizeof (struct MigrationStopMessage));
3592 msm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP);
3593 msm->duration = GNUNET_TIME_relative_hton (block_time);
3594 add_to_pending_messages_for_peer (cp,
3603 * Handle P2P "MIGRATION_STOP" message.
3605 * @param cls closure, always NULL
3606 * @param other the other peer involved (sender or receiver, NULL
3607 * for loopback messages where we are both sender and receiver)
3608 * @param message the actual message
3609 * @param latency reported latency of the connection with 'other'
3610 * @param distance reported distance (DV) to 'other'
3611 * @return GNUNET_OK to keep the connection open,
3612 * GNUNET_SYSERR to close it (signal serious error)
3615 handle_p2p_migration_stop (void *cls,
3616 const struct GNUNET_PeerIdentity *other,
3617 const struct GNUNET_MessageHeader *message,
3618 struct GNUNET_TIME_Relative latency,
3621 struct ConnectedPeer *cp;
3622 const struct MigrationStopMessage *msm;
3624 msm = (const struct MigrationStopMessage*) message;
3625 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3626 &other->hashPubKey);
3632 cp->migration_blocked = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (msm->duration));
3638 /* **************************** P2P GET Handling ************************ */
3642 * Closure for 'check_duplicate_request_{peer,client}'.
3644 struct CheckDuplicateRequestClosure
3647 * The new request we should check if it already exists.
3649 const struct PendingRequest *pr;
3652 * Existing request found by the checker, NULL if none.
3654 struct PendingRequest *have;
3659 * Iterator over entries in the 'query_request_map' that
3660 * tries to see if we have the same request pending from
3661 * the same client already.
3663 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
3664 * @param key current key code (query, ignored, must match)
3665 * @param value value in the hash map (a 'struct PendingRequest'
3666 * that already exists)
3667 * @return GNUNET_YES if we should continue to
3668 * iterate (no match yet)
3669 * GNUNET_NO if not (match found).
3672 check_duplicate_request_client (void *cls,
3673 const GNUNET_HashCode * key,
3676 struct CheckDuplicateRequestClosure *cdc = cls;
3677 struct PendingRequest *have = value;
3679 if (have->client_request_list == NULL)
3681 if ( (cdc->pr->client_request_list->client_list->client == have->client_request_list->client_list->client) &&
3692 * We're processing (local) results for a search request
3693 * from another peer. Pass applicable results to the
3694 * peer and if we are done either clean up (operation
3695 * complete) or forward to other peers (more results possible).
3697 * @param cls our closure (struct LocalGetContext)
3698 * @param key key for the content
3699 * @param size number of bytes in data
3700 * @param data content stored
3701 * @param type type of the content
3702 * @param priority priority of the content
3703 * @param anonymity anonymity-level for the content
3704 * @param expiration expiration time for the content
3705 * @param uid unique identifier for the datum;
3706 * maybe 0 if no unique identifier is available
3709 process_local_reply (void *cls,
3710 const GNUNET_HashCode * key,
3713 enum GNUNET_BLOCK_Type type,
3716 struct GNUNET_TIME_Absolute
3720 struct PendingRequest *pr = cls;
3721 struct ProcessReplyClosure prq;
3722 struct CheckDuplicateRequestClosure cdrc;
3723 GNUNET_HashCode query;
3724 unsigned int old_rf;
3729 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3730 "Done processing local replies, forwarding request to other peers.\n");
3733 if (pr->client_request_list != NULL)
3735 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
3737 /* Figure out if this is a duplicate request and possibly
3738 merge 'struct PendingRequest' entries */
3741 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
3743 &check_duplicate_request_client,
3745 if (cdrc.have != NULL)
3748 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3749 "Received request for block `%s' twice from client, will only request once.\n",
3750 GNUNET_h2s (&pr->query));
3753 destroy_pending_request (pr);
3757 if (pr->local_only == GNUNET_YES)
3759 destroy_pending_request (pr);
3762 /* no more results */
3763 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
3764 pr->task = GNUNET_SCHEDULER_add_now (&forward_request_task,
3769 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3770 "New local response to `%s' of type %u.\n",
3774 if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
3777 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3778 "Found ONDEMAND block, performing on-demand encoding\n");
3780 GNUNET_STATISTICS_update (stats,
3781 gettext_noop ("# on-demand blocks matched requests"),
3785 GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
3786 anonymity, expiration, uid,
3787 &process_local_reply,
3791 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3795 old_rf = pr->results_found;
3796 memset (&prq, 0, sizeof (prq));
3798 prq.expiration = expiration;
3801 GNUNET_BLOCK_get_key (block_ctx,
3808 GNUNET_DATASTORE_remove (dsh,
3812 GNUNET_TIME_UNIT_FOREVER_REL,
3814 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3818 prq.priority = priority;
3819 prq.finished = GNUNET_NO;
3820 prq.request_found = GNUNET_NO;
3821 if ( (old_rf == 0) &&
3822 (pr->results_found == 0) )
3823 update_datastore_delays (pr->start_time);
3824 process_reply (&prq, key, pr);
3825 if (prq.finished == GNUNET_YES)
3828 return; /* done here */
3829 if (prq.eval == GNUNET_BLOCK_EVALUATION_OK_LAST)
3831 pr->local_only = GNUNET_YES; /* do not forward */
3832 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
3835 if ( (pr->client_request_list == NULL) &&
3836 ( (GNUNET_YES == test_get_load_too_high (0)) ||
3837 (pr->results_found > 5 + 2 * pr->priority) ) )
3840 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3841 "Load too high, done with request\n");
3843 GNUNET_STATISTICS_update (stats,
3844 gettext_noop ("# processing result set cut short due to load"),
3847 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
3850 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3855 * We've received a request with the specified priority. Bound it
3856 * according to how much we trust the given peer.
3858 * @param prio_in requested priority
3859 * @param cp the peer making the request
3860 * @return effective priority
3863 bound_priority (uint32_t prio_in,
3864 struct ConnectedPeer *cp)
3866 #define N ((double)128.0)
3871 ld = test_get_load_too_high (0);
3872 if (ld == GNUNET_SYSERR)
3874 GNUNET_STATISTICS_update (stats,
3875 gettext_noop ("# requests done for free (low load)"),
3878 return 0; /* excess resources */
3880 ret = change_host_trust (cp, prio_in);
3883 if (ret > current_priorities + N)
3884 rret = current_priorities + N;
3888 = (current_priorities * (N-1) + rret)/N;
3890 if ( (ld == GNUNET_YES) && (ret > 0) )
3892 /* try with charging */
3893 ld = test_get_load_too_high (ret);
3895 if (ld == GNUNET_YES)
3897 GNUNET_STATISTICS_update (stats,
3898 gettext_noop ("# request dropped, priority insufficient"),
3903 change_host_trust (cp, -ret);
3904 return -1; /* not enough resources */
3908 GNUNET_STATISTICS_update (stats,
3909 gettext_noop ("# requests done for a price (normal load)"),
3919 * Iterator over entries in the 'query_request_map' that
3920 * tries to see if we have the same request pending from
3921 * the same peer already.
3923 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
3924 * @param key current key code (query, ignored, must match)
3925 * @param value value in the hash map (a 'struct PendingRequest'
3926 * that already exists)
3927 * @return GNUNET_YES if we should continue to
3928 * iterate (no match yet)
3929 * GNUNET_NO if not (match found).
3932 check_duplicate_request_peer (void *cls,
3933 const GNUNET_HashCode * key,
3936 struct CheckDuplicateRequestClosure *cdc = cls;
3937 struct PendingRequest *have = value;
3939 if (cdc->pr->target_pid == have->target_pid)
3949 * Handle P2P "GET" request.
3951 * @param cls closure, always NULL
3952 * @param other the other peer involved (sender or receiver, NULL
3953 * for loopback messages where we are both sender and receiver)
3954 * @param message the actual message
3955 * @param latency reported latency of the connection with 'other'
3956 * @param distance reported distance (DV) to 'other'
3957 * @return GNUNET_OK to keep the connection open,
3958 * GNUNET_SYSERR to close it (signal serious error)
3961 handle_p2p_get (void *cls,
3962 const struct GNUNET_PeerIdentity *other,
3963 const struct GNUNET_MessageHeader *message,
3964 struct GNUNET_TIME_Relative latency,
3967 struct PendingRequest *pr;
3968 struct ConnectedPeer *cp;
3969 struct ConnectedPeer *cps;
3970 struct CheckDuplicateRequestClosure cdc;
3971 struct GNUNET_TIME_Relative timeout;
3973 const struct GetMessage *gm;
3975 const GNUNET_HashCode *opt;
3978 uint32_t ttl_decrement;
3980 enum GNUNET_BLOCK_Type type;
3983 msize = ntohs(message->size);
3984 if (msize < sizeof (struct GetMessage))
3986 GNUNET_break_op (0);
3987 return GNUNET_SYSERR;
3989 gm = (const struct GetMessage*) message;
3991 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3992 "Received request for `%s'\n",
3993 GNUNET_h2s (&gm->query));
3995 type = ntohl (gm->type);
3996 bm = ntohl (gm->hash_bitmap);
4004 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
4006 GNUNET_break_op (0);
4007 return GNUNET_SYSERR;
4009 opt = (const GNUNET_HashCode*) &gm[1];
4010 bfsize = msize - sizeof (struct GetMessage) - bits * sizeof (GNUNET_HashCode);
4011 /* bfsize must be power of 2, check! */
4012 if (0 != ( (bfsize - 1) & bfsize))
4014 GNUNET_break_op (0);
4015 return GNUNET_SYSERR;
4017 bm = ntohl (gm->hash_bitmap);
4019 cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
4020 &other->hashPubKey);
4023 /* peer must have just disconnected */
4024 GNUNET_STATISTICS_update (stats,
4025 gettext_noop ("# requests dropped due to initiator not being connected"),
4028 return GNUNET_SYSERR;
4030 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
4031 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
4038 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
4039 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4040 "Failed to find RETURN-TO peer `%4s' in connection set. Dropping query.\n",
4041 GNUNET_i2s ((const struct GNUNET_PeerIdentity*) &opt[bits-1]));
4044 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4045 "Failed to find peer `%4s' in connection set. Dropping query.\n",
4046 GNUNET_i2s (other));
4048 GNUNET_STATISTICS_update (stats,
4049 gettext_noop ("# requests dropped due to missing reverse route"),
4052 /* FIXME: try connect? */
4055 /* note that we can really only check load here since otherwise
4056 peers could find out that we are overloaded by not being
4057 disconnected after sending us a malformed query... */
4058 priority = bound_priority (ntohl (gm->priority), cps);
4062 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4063 "Dropping query from `%s', this peer is too busy.\n",
4064 GNUNET_i2s (other));
4069 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4070 "Received request for `%s' of type %u from peer `%4s' with flags %u\n",
4071 GNUNET_h2s (&gm->query),
4072 (unsigned int) type,
4076 have_ns = (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE));
4077 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
4078 (have_ns ? sizeof(GNUNET_HashCode) : 0));
4081 pr->namespace = (GNUNET_HashCode*) &pr[1];
4082 memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
4084 if ( (GNUNET_LOAD_get_load (cp->transmission_delay) > 3 * (1 + priority)) ||
4085 (GNUNET_LOAD_get_average (cp->transmission_delay) >
4086 GNUNET_CONSTANTS_MAX_CORK_DELAY.rel_value * 2 + GNUNET_LOAD_get_average (rt_entry_lifetime)) )
4088 /* don't have BW to send to peer, or would likely take longer than we have for it,
4089 so at best indirect the query */
4091 pr->forward_only = GNUNET_YES;
4094 pr->mingle = ntohl (gm->filter_mutator);
4095 if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
4096 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
4097 pr->anonymity_level = 1;
4098 pr->priority = (uint32_t) priority;
4099 pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
4100 pr->query = gm->query;
4101 /* decrement ttl (always) */
4102 ttl_decrement = 2 * TTL_DECREMENT +
4103 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
4105 if ( (pr->ttl < 0) &&
4106 (((int32_t)(pr->ttl - ttl_decrement)) > 0) )
4109 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4110 "Dropping query from `%s' due to TTL underflow (%d - %u).\n",
4115 GNUNET_STATISTICS_update (stats,
4116 gettext_noop ("# requests dropped due TTL underflow"),
4119 /* integer underflow => drop (should be very rare)! */
4123 pr->ttl -= ttl_decrement;
4124 pr->start_time = GNUNET_TIME_absolute_get ();
4126 /* get bloom filter */
4129 pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
4132 pr->bf_size = bfsize;
4136 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
4138 &check_duplicate_request_peer,
4140 if (cdc.have != NULL)
4142 if (cdc.have->start_time.abs_value + cdc.have->ttl >=
4143 pr->start_time.abs_value + pr->ttl)
4145 /* existing request has higher TTL, drop new one! */
4146 cdc.have->priority += pr->priority;
4147 destroy_pending_request (pr);
4149 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4150 "Have existing request with higher TTL, dropping new request.\n",
4151 GNUNET_i2s (other));
4153 GNUNET_STATISTICS_update (stats,
4154 gettext_noop ("# requests dropped due to higher-TTL request"),
4161 /* existing request has lower TTL, drop old one! */
4162 pr->priority += cdc.have->priority;
4163 /* Possible optimization: if we have applicable pending
4164 replies in 'cdc.have', we might want to move those over
4165 (this is a really rare special-case, so it is not clear
4166 that this would be worth it) */
4167 destroy_pending_request (cdc.have);
4168 /* keep processing 'pr'! */
4173 GNUNET_break (GNUNET_OK ==
4174 GNUNET_CONTAINER_multihashmap_put (query_request_map,
4177 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
4178 GNUNET_break (GNUNET_OK ==
4179 GNUNET_CONTAINER_multihashmap_put (peer_request_map,
4182 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
4184 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
4186 pr->start_time.abs_value + pr->ttl);
4188 GNUNET_STATISTICS_update (stats,
4189 gettext_noop ("# P2P searches received"),
4192 GNUNET_STATISTICS_update (stats,
4193 gettext_noop ("# P2P searches active"),
4197 /* calculate change in traffic preference */
4198 cps->inc_preference += pr->priority * 1000 + QUERY_BANDWIDTH_VALUE;
4199 /* process locally */
4200 if (type == GNUNET_BLOCK_TYPE_FS_DBLOCK)
4201 type = GNUNET_BLOCK_TYPE_ANY; /* to get on-demand as well */
4202 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
4203 (pr->priority + 1));
4204 if (GNUNET_YES != pr->forward_only)
4207 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4208 "Handing request for `%s' to datastore\n",
4209 GNUNET_h2s (&gm->query));
4211 pr->qe = GNUNET_DATASTORE_get (dsh,
4215 MAX_DATASTORE_QUEUE,
4217 &process_local_reply,
4221 GNUNET_STATISTICS_update (stats,
4222 gettext_noop ("# requests dropped by datastore (queue length limit)"),
4229 GNUNET_STATISTICS_update (stats,
4230 gettext_noop ("# requests forwarded due to high load"),
4235 /* Are multiple results possible (and did we look locally)? If so, start processing remotely now! */
4238 case GNUNET_BLOCK_TYPE_FS_DBLOCK:
4239 case GNUNET_BLOCK_TYPE_FS_IBLOCK:
4240 /* only one result, wait for datastore */
4241 if (GNUNET_YES != pr->forward_only)
4243 GNUNET_STATISTICS_update (stats,
4244 gettext_noop ("# requests not instantly forwarded (waiting for datastore)"),
4250 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
4251 pr->task = GNUNET_SCHEDULER_add_now (&forward_request_task,
4255 /* make sure we don't track too many requests */
4256 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
4258 pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
4259 GNUNET_assert (pr != NULL);
4260 destroy_pending_request (pr);
4266 /* **************************** CS GET Handling ************************ */
4270 * Handle START_SEARCH-message (search request from client).
4272 * @param cls closure
4273 * @param client identification of the client
4274 * @param message the actual message
4277 handle_start_search (void *cls,
4278 struct GNUNET_SERVER_Client *client,
4279 const struct GNUNET_MessageHeader *message)
4281 static GNUNET_HashCode all_zeros;
4282 const struct SearchMessage *sm;
4283 struct ClientList *cl;
4284 struct ClientRequestList *crl;
4285 struct PendingRequest *pr;
4288 enum GNUNET_BLOCK_Type type;
4290 msize = ntohs (message->size);
4291 if ( (msize < sizeof (struct SearchMessage)) ||
4292 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
4295 GNUNET_SERVER_receive_done (client,
4299 GNUNET_STATISTICS_update (stats,
4300 gettext_noop ("# client searches received"),
4303 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
4304 sm = (const struct SearchMessage*) message;
4305 type = ntohl (sm->type);
4307 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4308 "Received request for `%s' of type %u from local client\n",
4309 GNUNET_h2s (&sm->query),
4310 (unsigned int) type);
4313 while ( (cl != NULL) &&
4314 (cl->client != client) )
4318 cl = GNUNET_malloc (sizeof (struct ClientList));
4319 cl->client = client;
4320 GNUNET_SERVER_client_keep (client);
4321 cl->next = client_list;
4324 /* detect duplicate KBLOCK requests */
4325 if ( (type == GNUNET_BLOCK_TYPE_FS_KBLOCK) ||
4326 (type == GNUNET_BLOCK_TYPE_FS_NBLOCK) ||
4327 (type == GNUNET_BLOCK_TYPE_ANY) )
4330 while ( (crl != NULL) &&
4331 ( (0 != memcmp (&crl->req->query,
4333 sizeof (GNUNET_HashCode))) ||
4334 (crl->req->type != type) ) )
4339 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4340 "Have existing request, merging content-seen lists.\n");
4343 /* Duplicate request (used to send long list of
4344 known/blocked results); merge 'pr->replies_seen'
4345 and update bloom filter */
4346 GNUNET_array_grow (pr->replies_seen,
4347 pr->replies_seen_size,
4348 pr->replies_seen_off + sc);
4349 memcpy (&pr->replies_seen[pr->replies_seen_off],
4351 sc * sizeof (GNUNET_HashCode));
4352 pr->replies_seen_off += sc;
4353 refresh_bloomfilter (pr);
4354 GNUNET_STATISTICS_update (stats,
4355 gettext_noop ("# client searches updated (merged content seen list)"),
4358 GNUNET_SERVER_receive_done (client,
4363 GNUNET_STATISTICS_update (stats,
4364 gettext_noop ("# client searches active"),
4367 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
4368 ((type == GNUNET_BLOCK_TYPE_FS_SBLOCK) ? sizeof(GNUNET_HashCode) : 0));
4369 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
4370 memset (crl, 0, sizeof (struct ClientRequestList));
4371 crl->client_list = cl;
4372 GNUNET_CONTAINER_DLL_insert (cl->rl_head,
4377 pr->client_request_list = crl;
4378 GNUNET_array_grow (pr->replies_seen,
4379 pr->replies_seen_size,
4381 memcpy (pr->replies_seen,
4383 sc * sizeof (GNUNET_HashCode));
4384 pr->replies_seen_off = sc;
4385 pr->anonymity_level = ntohl (sm->anonymity_level);
4386 pr->start_time = GNUNET_TIME_absolute_get ();
4387 refresh_bloomfilter (pr);
4388 pr->query = sm->query;
4389 if (0 == (1 & ntohl (sm->options)))
4390 pr->local_only = GNUNET_NO;
4392 pr->local_only = GNUNET_YES;
4395 case GNUNET_BLOCK_TYPE_FS_DBLOCK:
4396 case GNUNET_BLOCK_TYPE_FS_IBLOCK:
4397 if (0 != memcmp (&sm->target,
4399 sizeof (GNUNET_HashCode)))
4400 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
4402 case GNUNET_BLOCK_TYPE_FS_SBLOCK:
4403 pr->namespace = (GNUNET_HashCode*) &pr[1];
4404 memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
4409 GNUNET_break (GNUNET_OK ==
4410 GNUNET_CONTAINER_multihashmap_put (query_request_map,
4413 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
4414 if (type == GNUNET_BLOCK_TYPE_FS_DBLOCK)
4415 type = GNUNET_BLOCK_TYPE_ANY; /* get on-demand blocks too! */
4416 pr->qe = GNUNET_DATASTORE_get (dsh,
4420 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
4421 &process_local_reply,
4426 /* **************************** Startup ************************ */
4429 * Process fs requests.
4431 * @param server the initialized server
4432 * @param c configuration to use
4435 main_init (struct GNUNET_SERVER_Handle *server,
4436 const struct GNUNET_CONFIGURATION_Handle *c)
4438 static const struct GNUNET_CORE_MessageHandler p2p_handlers[] =
4441 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
4443 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
4444 { &handle_p2p_migration_stop,
4445 GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP,
4446 sizeof (struct MigrationStopMessage) },
4449 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
4450 {&GNUNET_FS_handle_index_start, NULL,
4451 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
4452 {&GNUNET_FS_handle_index_list_get, NULL,
4453 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
4454 {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
4455 sizeof (struct UnindexMessage) },
4456 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
4460 unsigned long long enc = 128;
4463 stats = GNUNET_STATISTICS_create ("fs", cfg);
4464 min_migration_delay = GNUNET_TIME_UNIT_SECONDS;
4466 GNUNET_CONFIGURATION_get_value_number (cfg,
4468 "MAX_PENDING_REQUESTS",
4469 &max_pending_requests)) ||
4471 GNUNET_CONFIGURATION_get_value_number (cfg,
4473 "EXPECTED_NEIGHBOUR_COUNT",
4476 GNUNET_CONFIGURATION_get_value_time (cfg,
4478 "MIN_MIGRATION_DELAY",
4479 &min_migration_delay)) )
4481 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4482 _("Configuration fails to specify certain parameters, assuming default values."));
4484 connected_peers = GNUNET_CONTAINER_multihashmap_create (enc);
4485 query_request_map = GNUNET_CONTAINER_multihashmap_create (max_pending_requests);
4486 rt_entry_lifetime = GNUNET_LOAD_value_init (GNUNET_TIME_UNIT_FOREVER_REL);
4487 peer_request_map = GNUNET_CONTAINER_multihashmap_create (enc);
4488 requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
4489 core = GNUNET_CORE_connect (cfg,
4490 GNUNET_TIME_UNIT_FOREVER_REL,
4493 &peer_connect_handler,
4494 &peer_disconnect_handler,
4495 &peer_status_handler,
4501 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4502 _("Failed to connect to `%s' service.\n"),
4504 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
4505 connected_peers = NULL;
4506 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
4507 query_request_map = NULL;
4508 GNUNET_LOAD_value_free (rt_entry_lifetime);
4509 rt_entry_lifetime = NULL;
4510 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
4511 requests_by_expiration_heap = NULL;
4512 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
4513 peer_request_map = NULL;
4516 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
4519 return GNUNET_SYSERR;
4521 /* FIXME: distinguish between sending and storing in options? */
4522 if (active_migration)
4524 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4525 _("Content migration is enabled, will start to gather data\n"));
4526 consider_migration_gathering ();
4528 consider_dht_put_gathering (NULL);
4529 GNUNET_SERVER_disconnect_notify (server,
4530 &handle_client_disconnect,
4532 GNUNET_assert (GNUNET_OK ==
4533 GNUNET_CONFIGURATION_get_value_filename (cfg,
4537 GNUNET_DISK_directory_create (trustDirectory);
4538 GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_HIGH,
4539 &cron_flush_trust, NULL);
4542 GNUNET_SERVER_add_handlers (server, handlers);
4543 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4551 * Process fs requests.
4553 * @param cls closure
4554 * @param server the initialized server
4555 * @param cfg configuration to use
4559 struct GNUNET_SERVER_Handle *server,
4560 const struct GNUNET_CONFIGURATION_Handle *cfg)
4562 active_migration = GNUNET_CONFIGURATION_get_value_yesno (cfg,
4565 dsh = GNUNET_DATASTORE_connect (cfg);
4568 GNUNET_SCHEDULER_shutdown ();
4571 datastore_get_load = GNUNET_LOAD_value_init (DATASTORE_LOAD_AUTODECLINE);
4572 datastore_put_load = GNUNET_LOAD_value_init (DATASTORE_LOAD_AUTODECLINE);
4573 block_cfg = GNUNET_CONFIGURATION_create ();
4574 GNUNET_CONFIGURATION_set_value_string (block_cfg,
4578 block_ctx = GNUNET_BLOCK_context_create (block_cfg);
4579 GNUNET_assert (NULL != block_ctx);
4580 dht_handle = GNUNET_DHT_connect (cfg,
4582 if ( (GNUNET_OK != GNUNET_FS_indexing_init (cfg, dsh)) ||
4583 (GNUNET_OK != main_init (server, cfg)) )
4585 GNUNET_SCHEDULER_shutdown ();
4586 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
4588 GNUNET_DHT_disconnect (dht_handle);
4590 GNUNET_BLOCK_context_destroy (block_ctx);
4592 GNUNET_CONFIGURATION_destroy (block_cfg);
4594 GNUNET_LOAD_value_free (datastore_get_load);
4595 datastore_get_load = NULL;
4596 GNUNET_LOAD_value_free (datastore_put_load);
4597 datastore_put_load = NULL;
4604 * The main function for the fs service.
4606 * @param argc number of arguments from the command line
4607 * @param argv command line arguments
4608 * @return 0 ok, 1 on error
4611 main (int argc, char *const *argv)
4613 return (GNUNET_OK ==
4614 GNUNET_SERVICE_run (argc,
4617 GNUNET_SERVICE_OPTION_NONE,
4618 &run, NULL)) ? 0 : 1;
4621 /* end of gnunet-service-fs.c */