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,
1344 DEFAULT_PUT_REPLICATION,
1350 GNUNET_TIME_UNIT_FOREVER_REL,
1351 &dht_put_continuation,
1357 * Task that is run periodically to obtain blocks for content
1361 * @param tc scheduler context (also unused)
1364 gather_migration_blocks (void *cls,
1365 const struct GNUNET_SCHEDULER_TaskContext *tc)
1367 mig_task = GNUNET_SCHEDULER_NO_TASK;
1370 mig_qe = GNUNET_DATASTORE_get_random (dsh, 0, UINT_MAX,
1371 GNUNET_TIME_UNIT_FOREVER_REL,
1372 &process_migration_content, NULL);
1373 GNUNET_assert (mig_qe != NULL);
1379 * Task that is run periodically to obtain blocks for DHT PUTs.
1381 * @param cls type of blocks to gather
1382 * @param tc scheduler context (unused)
1385 gather_dht_put_blocks (void *cls,
1386 const struct GNUNET_SCHEDULER_TaskContext *tc)
1388 dht_task = GNUNET_SCHEDULER_NO_TASK;
1391 if (dht_put_type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
1392 dht_put_type = GNUNET_BLOCK_TYPE_FS_KBLOCK;
1393 dht_qe = GNUNET_DATASTORE_get_zero_anonymity (dsh, 0, UINT_MAX,
1394 GNUNET_TIME_UNIT_FOREVER_REL,
1396 &process_dht_put_content, NULL);
1397 GNUNET_assert (dht_qe != NULL);
1403 * We're done with a particular message list entry.
1404 * Free all associated resources.
1406 * @param pml entry to destroy
1409 destroy_pending_message_list_entry (struct PendingMessageList *pml)
1411 GNUNET_CONTAINER_DLL_remove (pml->req->pending_head,
1412 pml->req->pending_tail,
1414 GNUNET_CONTAINER_DLL_remove (pml->target->pending_messages_head,
1415 pml->target->pending_messages_tail,
1417 pml->target->pending_requests--;
1418 GNUNET_free (pml->pm);
1424 * Destroy the given pending message (and call the respective
1427 * @param pm message to destroy
1428 * @param tpid id of peer that the message was delivered to, or 0 for none
1431 destroy_pending_message (struct PendingMessage *pm,
1432 GNUNET_PEER_Id tpid)
1434 struct PendingMessageList *pml = pm->pml;
1435 TransmissionContinuation cont;
1439 cont_cls = pm->cont_cls;
1442 GNUNET_assert (pml->pm == pm);
1443 GNUNET_assert ( (tpid == 0) || (tpid == pml->target->pid) );
1444 destroy_pending_message_list_entry (pml);
1451 cont (cont_cls, tpid);
1456 * We're done processing a particular request.
1457 * Free all associated resources.
1459 * @param pr request to destroy
1462 destroy_pending_request (struct PendingRequest *pr)
1464 struct GNUNET_PeerIdentity pid;
1467 if (pr->hnode != NULL)
1469 GNUNET_CONTAINER_heap_remove_node (requests_by_expiration_heap,
1473 if (NULL == pr->client_request_list)
1475 GNUNET_STATISTICS_update (stats,
1476 gettext_noop ("# P2P searches active"),
1482 GNUNET_STATISTICS_update (stats,
1483 gettext_noop ("# client searches active"),
1488 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
1492 GNUNET_LOAD_update (rt_entry_lifetime,
1493 GNUNET_TIME_absolute_get_duration (pr->start_time).rel_value);
1497 GNUNET_DATASTORE_cancel (pr->qe);
1500 if (pr->dht_get != NULL)
1502 GNUNET_DHT_get_stop (pr->dht_get);
1505 if (pr->client_request_list != NULL)
1507 GNUNET_CONTAINER_DLL_remove (pr->client_request_list->client_list->rl_head,
1508 pr->client_request_list->client_list->rl_tail,
1509 pr->client_request_list);
1510 GNUNET_free (pr->client_request_list);
1511 pr->client_request_list = NULL;
1515 GNUNET_PEER_resolve (pr->cp->pid,
1517 (void) GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
1524 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
1527 if (pr->irc != NULL)
1529 GNUNET_CORE_peer_change_preference_cancel (pr->irc);
1532 if (pr->replies_seen != NULL)
1534 GNUNET_free (pr->replies_seen);
1535 pr->replies_seen = NULL;
1537 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
1539 GNUNET_SCHEDULER_cancel (pr->task);
1540 pr->task = GNUNET_SCHEDULER_NO_TASK;
1542 while (NULL != pr->pending_head)
1543 destroy_pending_message_list_entry (pr->pending_head);
1544 GNUNET_PEER_change_rc (pr->target_pid, -1);
1545 if (pr->used_targets != NULL)
1547 for (i=0;i<pr->used_targets_off;i++)
1548 GNUNET_PEER_change_rc (pr->used_targets[i].pid, -1);
1549 GNUNET_free (pr->used_targets);
1550 pr->used_targets_off = 0;
1551 pr->used_targets_size = 0;
1552 pr->used_targets = NULL;
1559 * Find latency information in 'atsi'.
1561 * @param atsi performance data
1562 * @return connection latency
1564 static struct GNUNET_TIME_Relative
1565 get_latency (const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1567 /* FIXME: extract latency data from 'atsi' */
1568 return GNUNET_TIME_UNIT_SECONDS;
1573 * Method called whenever a given peer connects.
1575 * @param cls closure, not used
1576 * @param peer peer identity this notification is about
1577 * @param atsi performance information
1580 peer_connect_handler (void *cls,
1582 GNUNET_PeerIdentity * peer,
1583 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1585 struct ConnectedPeer *cp;
1586 struct MigrationReadyBlock *pos;
1589 struct GNUNET_TIME_Relative latency;
1591 latency = get_latency (atsi);
1592 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1599 cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
1600 cp->transmission_delay = GNUNET_LOAD_value_init (latency);
1601 cp->pid = GNUNET_PEER_intern (peer);
1603 fn = get_trust_filename (peer);
1604 if ((GNUNET_DISK_file_test (fn) == GNUNET_YES) &&
1605 (sizeof (trust) == GNUNET_DISK_fn_read (fn, &trust, sizeof (trust))))
1606 cp->disk_trust = cp->trust = ntohl (trust);
1609 GNUNET_break (GNUNET_OK ==
1610 GNUNET_CONTAINER_multihashmap_put (connected_peers,
1613 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1618 (void) consider_migration (pos, &peer->hashPubKey, cp);
1625 * Method called whenever a given peer has a status change.
1627 * @param cls closure
1628 * @param peer peer identity this notification is about
1629 * @param bandwidth_in available amount of inbound bandwidth
1630 * @param bandwidth_out available amount of outbound bandwidth
1631 * @param timeout absolute time when this peer will time out
1632 * unless we see some further activity from it
1633 * @param atsi status information
1636 peer_status_handler (void *cls,
1638 GNUNET_PeerIdentity * peer,
1639 struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
1640 struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
1641 struct GNUNET_TIME_Absolute timeout,
1642 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1644 struct ConnectedPeer *cp;
1645 struct GNUNET_TIME_Relative latency;
1647 latency = get_latency (atsi);
1648 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1655 GNUNET_LOAD_value_set_decline (cp->transmission_delay,
1662 * Increase the host credit by a value.
1664 * @param host which peer to change the trust value on
1665 * @param value is the int value by which the
1666 * host credit is to be increased or decreased
1667 * @returns the actual change in trust (positive or negative)
1670 change_host_trust (struct ConnectedPeer *host, int value)
1674 GNUNET_assert (host != NULL);
1677 if (host->trust + value < host->trust)
1679 value = UINT32_MAX - host->trust;
1680 host->trust = UINT32_MAX;
1683 host->trust += value;
1687 if (host->trust < -value)
1689 value = -host->trust;
1693 host->trust += value;
1700 * Write host-trust information to a file - flush the buffer entry!
1703 flush_trust (void *cls,
1704 const GNUNET_HashCode *key,
1707 struct ConnectedPeer *host = value;
1710 struct GNUNET_PeerIdentity pid;
1712 if (host->trust == host->disk_trust)
1713 return GNUNET_OK; /* unchanged */
1714 GNUNET_PEER_resolve (host->pid,
1716 fn = get_trust_filename (&pid);
1717 if (host->trust == 0)
1719 if ((0 != UNLINK (fn)) && (errno != ENOENT))
1720 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
1721 GNUNET_ERROR_TYPE_BULK, "unlink", fn);
1725 trust = htonl (host->trust);
1726 if (sizeof(uint32_t) == GNUNET_DISK_fn_write (fn, &trust,
1728 GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE
1729 | GNUNET_DISK_PERM_GROUP_READ | GNUNET_DISK_PERM_OTHER_READ))
1730 host->disk_trust = host->trust;
1737 * Call this method periodically to scan data/hosts for new hosts.
1740 cron_flush_trust (void *cls,
1741 const struct GNUNET_SCHEDULER_TaskContext *tc)
1744 if (NULL == connected_peers)
1746 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1751 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1753 GNUNET_SCHEDULER_add_delayed (TRUST_FLUSH_FREQ, &cron_flush_trust, NULL);
1758 * Free (each) request made by the peer.
1760 * @param cls closure, points to peer that the request belongs to
1761 * @param key current key code
1762 * @param value value in the hash map
1763 * @return GNUNET_YES (we should continue to iterate)
1766 destroy_request (void *cls,
1767 const GNUNET_HashCode * key,
1770 const struct GNUNET_PeerIdentity * peer = cls;
1771 struct PendingRequest *pr = value;
1773 GNUNET_break (GNUNET_YES ==
1774 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
1777 destroy_pending_request (pr);
1783 * Method called whenever a peer disconnects.
1785 * @param cls closure, not used
1786 * @param peer peer identity this notification is about
1789 peer_disconnect_handler (void *cls,
1791 GNUNET_PeerIdentity * peer)
1793 struct ConnectedPeer *cp;
1794 struct PendingMessage *pm;
1796 struct MigrationReadyBlock *pos;
1797 struct MigrationReadyBlock *next;
1799 GNUNET_CONTAINER_multihashmap_get_multiple (peer_request_map,
1803 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1807 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1809 if (NULL != cp->last_client_replies[i])
1811 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1812 cp->last_client_replies[i] = NULL;
1815 GNUNET_break (GNUNET_YES ==
1816 GNUNET_CONTAINER_multihashmap_remove (connected_peers,
1819 /* remove this peer from migration considerations; schedule
1822 while (NULL != (pos = next))
1825 for (i=0;i<MIGRATION_LIST_SIZE;i++)
1827 if (pos->target_list[i] == cp->pid)
1829 GNUNET_PEER_change_rc (pos->target_list[i], -1);
1830 pos->target_list[i] = 0;
1833 if (pos->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers))
1835 delete_migration_block (pos);
1836 consider_migration_gathering ();
1839 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1840 &consider_migration,
1843 GNUNET_PEER_change_rc (cp->pid, -1);
1844 GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
1845 if (NULL != cp->cth)
1847 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
1850 if (cp->delayed_transmission_request_task != GNUNET_SCHEDULER_NO_TASK)
1852 GNUNET_SCHEDULER_cancel (cp->delayed_transmission_request_task);
1853 cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
1855 while (NULL != (pm = cp->pending_messages_head))
1856 destroy_pending_message (pm, 0 /* delivery failed */);
1857 GNUNET_LOAD_value_free (cp->transmission_delay);
1858 GNUNET_break (0 == cp->pending_requests);
1864 * Iterator over hash map entries that removes all occurences
1865 * of the given 'client' from the 'last_client_replies' of the
1866 * given connected peer.
1868 * @param cls closure, the 'struct GNUNET_SERVER_Client*' to remove
1869 * @param key current key code (unused)
1870 * @param value value in the hash map (the 'struct ConnectedPeer*' to change)
1871 * @return GNUNET_YES (we should continue to iterate)
1874 remove_client_from_last_client_replies (void *cls,
1875 const GNUNET_HashCode * key,
1878 struct GNUNET_SERVER_Client *client = cls;
1879 struct ConnectedPeer *cp = value;
1882 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1884 if (cp->last_client_replies[i] == client)
1886 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1887 cp->last_client_replies[i] = NULL;
1895 * A client disconnected. Remove all of its pending queries.
1897 * @param cls closure, NULL
1898 * @param client identification of the client
1901 handle_client_disconnect (void *cls,
1902 struct GNUNET_SERVER_Client
1905 struct ClientList *pos;
1906 struct ClientList *prev;
1907 struct ClientRequestList *rcl;
1908 struct ClientResponseMessage *creply;
1914 while ( (NULL != pos) &&
1915 (pos->client != client) )
1921 return; /* no requests pending for this client */
1922 while (NULL != (rcl = pos->rl_head))
1924 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1925 "Destroying pending request `%s' on disconnect\n",
1926 GNUNET_h2s (&rcl->req->query));
1927 destroy_pending_request (rcl->req);
1930 client_list = pos->next;
1932 prev->next = pos->next;
1933 if (pos->th != NULL)
1935 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
1938 while (NULL != (creply = pos->res_head))
1940 GNUNET_CONTAINER_DLL_remove (pos->res_head,
1943 GNUNET_free (creply);
1945 GNUNET_SERVER_client_drop (pos->client);
1947 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1948 &remove_client_from_last_client_replies,
1954 * Iterator to free peer entries.
1956 * @param cls closure, unused
1957 * @param key current key code
1958 * @param value value in the hash map (peer entry)
1959 * @return GNUNET_YES (we should continue to iterate)
1962 clean_peer (void *cls,
1963 const GNUNET_HashCode * key,
1966 peer_disconnect_handler (NULL, (const struct GNUNET_PeerIdentity*) key);
1972 * Task run during shutdown.
1978 shutdown_task (void *cls,
1979 const struct GNUNET_SCHEDULER_TaskContext *tc)
1983 GNUNET_DATASTORE_cancel (mig_qe);
1988 GNUNET_DATASTORE_cancel (dht_qe);
1991 if (GNUNET_SCHEDULER_NO_TASK != mig_task)
1993 GNUNET_SCHEDULER_cancel (mig_task);
1994 mig_task = GNUNET_SCHEDULER_NO_TASK;
1996 if (GNUNET_SCHEDULER_NO_TASK != dht_task)
1998 GNUNET_SCHEDULER_cancel (dht_task);
1999 dht_task = GNUNET_SCHEDULER_NO_TASK;
2001 while (client_list != NULL)
2002 handle_client_disconnect (NULL,
2003 client_list->client);
2004 cron_flush_trust (NULL, NULL);
2005 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
2008 GNUNET_break (0 == GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap));
2009 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
2010 requests_by_expiration_heap = 0;
2011 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
2012 connected_peers = NULL;
2013 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (query_request_map));
2014 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
2015 query_request_map = NULL;
2016 GNUNET_LOAD_value_free (rt_entry_lifetime);
2017 rt_entry_lifetime = NULL;
2018 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (peer_request_map));
2019 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
2020 peer_request_map = NULL;
2021 GNUNET_assert (NULL != core);
2022 GNUNET_CORE_disconnect (core);
2026 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
2031 GNUNET_DATASTORE_disconnect (dsh,
2035 while (mig_head != NULL)
2036 delete_migration_block (mig_head);
2037 GNUNET_assert (0 == mig_size);
2038 GNUNET_DHT_disconnect (dht_handle);
2040 GNUNET_LOAD_value_free (datastore_get_load);
2041 datastore_get_load = NULL;
2042 GNUNET_LOAD_value_free (datastore_put_load);
2043 datastore_put_load = NULL;
2044 GNUNET_BLOCK_context_destroy (block_ctx);
2046 GNUNET_CONFIGURATION_destroy (block_cfg);
2049 GNUNET_free_non_null (trustDirectory);
2050 trustDirectory = NULL;
2054 /* ******************* Utility functions ******************** */
2058 * We've had to delay a request for transmission to core, but now
2059 * we should be ready. Run it.
2061 * @param cls the 'struct ConnectedPeer' for which a request was delayed
2062 * @param tc task context (unused)
2065 delayed_transmission_request (void *cls,
2066 const struct GNUNET_SCHEDULER_TaskContext *tc)
2068 struct ConnectedPeer *cp = cls;
2069 struct GNUNET_PeerIdentity pid;
2070 struct PendingMessage *pm;
2072 pm = cp->pending_messages_head;
2073 cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
2074 GNUNET_assert (cp->cth == NULL);
2077 GNUNET_PEER_resolve (cp->pid,
2079 cp->last_transmission_request_start = GNUNET_TIME_absolute_get ();
2080 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
2082 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
2091 * Transmit messages by copying it to the target buffer
2092 * "buf". "buf" will be NULL and "size" zero if the socket was closed
2093 * for writing in the meantime. In that case, do nothing
2094 * (the disconnect or shutdown handler will take care of the rest).
2095 * If we were able to transmit messages and there are still more
2096 * pending, ask core again for further calls to this function.
2098 * @param cls closure, pointer to the 'struct ConnectedPeer*'
2099 * @param size number of bytes available in buf
2100 * @param buf where the callee should write the message
2101 * @return number of bytes written to buf
2104 transmit_to_peer (void *cls,
2105 size_t size, void *buf)
2107 struct ConnectedPeer *cp = cls;
2109 struct PendingMessage *pm;
2110 struct PendingMessage *next_pm;
2111 struct GNUNET_TIME_Absolute now;
2112 struct GNUNET_TIME_Relative min_delay;
2113 struct MigrationReadyBlock *mb;
2114 struct MigrationReadyBlock *next;
2115 struct PutMessage migm;
2118 struct GNUNET_PeerIdentity pid;
2124 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2125 "Dropping message, core too busy.\n");
2127 GNUNET_LOAD_update (cp->transmission_delay,
2131 GNUNET_LOAD_update (cp->transmission_delay,
2132 GNUNET_TIME_absolute_get_duration (cp->last_transmission_request_start).rel_value);
2133 now = GNUNET_TIME_absolute_get ();
2135 min_delay = GNUNET_TIME_UNIT_FOREVER_REL;
2136 next_pm = cp->pending_messages_head;
2137 while ( (NULL != (pm = next_pm) ) &&
2138 (pm->msize <= size) )
2141 if (pm->delay_until.abs_value > now.abs_value)
2143 min_delay = GNUNET_TIME_relative_min (min_delay,
2144 GNUNET_TIME_absolute_get_remaining (pm->delay_until));
2147 memcpy (&cbuf[msize], &pm[1], pm->msize);
2150 if (NULL == pm->pml)
2152 GNUNET_CONTAINER_DLL_remove (cp->pending_messages_head,
2153 cp->pending_messages_tail,
2155 cp->pending_requests--;
2157 destroy_pending_message (pm, cp->pid);
2160 min_delay = GNUNET_TIME_UNIT_ZERO;
2161 if (NULL != cp->pending_messages_head)
2163 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == cp->delayed_transmission_request_task);
2164 cp->delayed_transmission_request_task
2165 = GNUNET_SCHEDULER_add_delayed (min_delay,
2166 &delayed_transmission_request,
2171 GNUNET_PEER_resolve (cp->pid,
2174 while (NULL != (mb = next))
2177 for (i=0;i<MIGRATION_LIST_SIZE;i++)
2179 if ( (cp->pid == mb->target_list[i]) &&
2180 (mb->size + sizeof (migm) <= size) )
2182 GNUNET_PEER_change_rc (mb->target_list[i], -1);
2183 mb->target_list[i] = 0;
2185 memset (&migm, 0, sizeof (migm));
2186 migm.header.size = htons (sizeof (migm) + mb->size);
2187 migm.header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2188 migm.type = htonl (mb->type);
2189 migm.expiration = GNUNET_TIME_absolute_hton (mb->expiration);
2190 memcpy (&cbuf[msize], &migm, sizeof (migm));
2191 msize += sizeof (migm);
2192 size -= sizeof (migm);
2193 memcpy (&cbuf[msize], &mb[1], mb->size);
2197 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2198 "Pushing migration block `%s' (%u bytes) to `%s'\n",
2199 GNUNET_h2s (&mb->query),
2200 (unsigned int) mb->size,
2208 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2209 "Migration block `%s' (%u bytes) is not on migration list for peer `%s'\n",
2210 GNUNET_h2s (&mb->query),
2211 (unsigned int) mb->size,
2216 if ( (mb->used_targets >= MIGRATION_TARGET_COUNT) ||
2217 (mb->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers)) )
2219 delete_migration_block (mb);
2220 consider_migration_gathering ();
2223 consider_migration (NULL,
2228 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2229 "Transmitting %u bytes to peer with PID %u\n",
2230 (unsigned int) msize,
2231 (unsigned int) cp->pid);
2238 * Add a message to the set of pending messages for the given peer.
2240 * @param cp peer to send message to
2241 * @param pm message to queue
2242 * @param pr request on which behalf this message is being queued
2245 add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
2246 struct PendingMessage *pm,
2247 struct PendingRequest *pr)
2249 struct PendingMessage *pos;
2250 struct PendingMessageList *pml;
2251 struct GNUNET_PeerIdentity pid;
2253 GNUNET_assert (pm->next == NULL);
2254 GNUNET_assert (pm->pml == NULL);
2257 pml = GNUNET_malloc (sizeof (struct PendingMessageList));
2262 GNUNET_CONTAINER_DLL_insert (pr->pending_head,
2266 pos = cp->pending_messages_head;
2267 while ( (pos != NULL) &&
2268 (pm->priority < pos->priority) )
2270 GNUNET_CONTAINER_DLL_insert_after (cp->pending_messages_head,
2271 cp->pending_messages_tail,
2274 cp->pending_requests++;
2275 if (cp->pending_requests > MAX_QUEUE_PER_PEER)
2277 GNUNET_STATISTICS_update (stats,
2278 gettext_noop ("# P2P searches discarded (queue length bound)"),
2281 destroy_pending_message (cp->pending_messages_tail, 0);
2283 GNUNET_PEER_resolve (cp->pid, &pid);
2284 if (NULL != cp->cth)
2286 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
2289 if (cp->delayed_transmission_request_task != GNUNET_SCHEDULER_NO_TASK)
2291 GNUNET_SCHEDULER_cancel (cp->delayed_transmission_request_task);
2292 cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
2294 /* need to schedule transmission */
2295 cp->last_transmission_request_start = GNUNET_TIME_absolute_get ();
2296 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
2297 cp->pending_messages_head->priority,
2300 cp->pending_messages_head->msize,
2303 if (cp->cth == NULL)
2306 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2307 "Failed to schedule transmission with core!\n");
2309 GNUNET_STATISTICS_update (stats,
2310 gettext_noop ("# CORE transmission failures"),
2318 * Test if the DATABASE (GET) load on this peer is too high
2319 * to even consider processing the query at
2322 * @return GNUNET_YES if the load is too high to do anything (load high)
2323 * GNUNET_NO to process normally (load normal)
2324 * GNUNET_SYSERR to process for free (load low)
2327 test_get_load_too_high (uint32_t priority)
2331 ld = GNUNET_LOAD_get_load (datastore_get_load);
2333 return GNUNET_SYSERR;
2343 * Test if the DATABASE (PUT) load on this peer is too high
2344 * to even consider processing the query at
2347 * @return GNUNET_YES if the load is too high to do anything (load high)
2348 * GNUNET_NO to process normally (load normal or low)
2351 test_put_load_too_high (uint32_t priority)
2355 if (GNUNET_LOAD_get_average (datastore_put_load) < 50)
2356 return GNUNET_NO; /* very fast */
2357 ld = GNUNET_LOAD_get_load (datastore_put_load);
2358 if (ld < 2.0 * (1 + priority))
2360 GNUNET_STATISTICS_update (stats,
2361 gettext_noop ("# storage requests dropped due to high load"),
2368 /* ******************* Pending Request Refresh Task ******************** */
2373 * We use a random delay to make the timing of requests less
2374 * predictable. This function returns such a random delay. We add a base
2375 * delay of MAX_CORK_DELAY (1s).
2377 * FIXME: make schedule dependent on the specifics of the request?
2378 * Or bandwidth and number of connected peers and load?
2380 * @return random delay to use for some request, between 1s and 1000+TTL_DECREMENT ms
2382 static struct GNUNET_TIME_Relative
2383 get_processing_delay ()
2386 GNUNET_TIME_relative_add (GNUNET_CONSTANTS_MAX_CORK_DELAY,
2387 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
2388 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2394 * We're processing a GET request from another peer and have decided
2395 * to forward it to other peers. This function is called periodically
2396 * and should forward the request to other peers until we have all
2397 * possible replies. If we have transmitted the *only* reply to
2398 * the initiator we should destroy the pending request. If we have
2399 * many replies in the queue to the initiator, we should delay sending
2400 * out more queries until the reply queue has shrunk some.
2402 * @param cls our "struct ProcessGetContext *"
2406 forward_request_task (void *cls,
2407 const struct GNUNET_SCHEDULER_TaskContext *tc);
2411 * Function called after we either failed or succeeded
2412 * at transmitting a query to a peer.
2414 * @param cls the requests "struct PendingRequest*"
2415 * @param tpid ID of receiving peer, 0 on transmission error
2418 transmit_query_continuation (void *cls,
2419 GNUNET_PEER_Id tpid)
2421 struct PendingRequest *pr = cls;
2424 GNUNET_STATISTICS_update (stats,
2425 gettext_noop ("# queries scheduled for forwarding"),
2431 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2432 "Transmission of request failed, will try again later.\n");
2434 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2435 pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2436 &forward_request_task,
2441 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2442 "Transmitted query `%s'\n",
2443 GNUNET_h2s (&pr->query));
2445 GNUNET_STATISTICS_update (stats,
2446 gettext_noop ("# queries forwarded"),
2449 for (i=0;i<pr->used_targets_off;i++)
2450 if (pr->used_targets[i].pid == tpid)
2451 break; /* found match! */
2452 if (i == pr->used_targets_off)
2454 /* need to create new entry */
2455 if (pr->used_targets_off == pr->used_targets_size)
2456 GNUNET_array_grow (pr->used_targets,
2457 pr->used_targets_size,
2458 pr->used_targets_size * 2 + 2);
2459 GNUNET_PEER_change_rc (tpid, 1);
2460 pr->used_targets[pr->used_targets_off].pid = tpid;
2461 pr->used_targets[pr->used_targets_off].num_requests = 0;
2462 i = pr->used_targets_off++;
2464 pr->used_targets[i].last_request_time = GNUNET_TIME_absolute_get ();
2465 pr->used_targets[i].num_requests++;
2466 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2467 pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2468 &forward_request_task,
2474 * How many bytes should a bloomfilter be if we have already seen
2475 * entry_count responses? Note that BLOOMFILTER_K gives us the number
2476 * of bits set per entry. Furthermore, we should not re-size the
2477 * filter too often (to keep it cheap).
2479 * Since other peers will also add entries but not resize the filter,
2480 * we should generally pick a slightly larger size than what the
2481 * strict math would suggest.
2483 * @return must be a power of two and smaller or equal to 2^15.
2486 compute_bloomfilter_size (unsigned int entry_count)
2489 unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
2490 uint16_t max = 1 << 15;
2492 if (entry_count > max)
2495 while ((size < max) && (size < ideal))
2504 * Recalculate our bloom filter for filtering replies. This function
2505 * will create a new bloom filter from scratch, so it should only be
2506 * called if we have no bloomfilter at all (and hence can create a
2507 * fresh one of minimal size without problems) OR if our peer is the
2508 * initiator (in which case we may resize to larger than mimimum size).
2510 * @param pr request for which the BF is to be recomputed
2513 refresh_bloomfilter (struct PendingRequest *pr)
2517 GNUNET_HashCode mhash;
2519 nsize = compute_bloomfilter_size (pr->replies_seen_off);
2520 if (nsize == pr->bf_size)
2521 return; /* size not changed */
2523 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
2524 pr->bf_size = nsize;
2525 pr->mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
2526 pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
2529 for (i=0;i<pr->replies_seen_off;i++)
2531 GNUNET_BLOCK_mingle_hash (&pr->replies_seen[i],
2534 GNUNET_CONTAINER_bloomfilter_add (pr->bf, &mhash);
2540 * Function called after we've tried to reserve a certain amount of
2541 * bandwidth for a reply. Check if we succeeded and if so send our
2544 * @param cls the requests "struct PendingRequest*"
2545 * @param peer identifies the peer
2546 * @param bpm_out set to the current bandwidth limit (sending) for this peer
2547 * @param amount set to the amount that was actually reserved or unreserved
2548 * @param preference current traffic preference for the given peer
2551 target_reservation_cb (void *cls,
2553 GNUNET_PeerIdentity * peer,
2554 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
2556 uint64_t preference)
2558 struct PendingRequest *pr = cls;
2559 struct ConnectedPeer *cp;
2560 struct PendingMessage *pm;
2561 struct GetMessage *gm;
2562 GNUNET_HashCode *ext;
2573 /* error in communication with core, try again later */
2574 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2575 pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2576 &forward_request_task,
2580 /* (3) transmit, update ttl/priority */
2581 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2585 /* Peer must have just left */
2587 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2588 "Selected peer disconnected!\n");
2590 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2591 pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2592 &forward_request_task,
2596 no_route = GNUNET_NO;
2602 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2603 "Failed to reserve bandwidth for reply (got %d/%u bytes only)!\n",
2607 GNUNET_STATISTICS_update (stats,
2608 gettext_noop ("# reply bandwidth reservation requests failed"),
2611 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2612 pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2613 &forward_request_task,
2615 return; /* this target round failed */
2617 no_route = GNUNET_YES;
2620 GNUNET_STATISTICS_update (stats,
2621 gettext_noop ("# queries scheduled for forwarding"),
2624 for (i=0;i<pr->used_targets_off;i++)
2625 if (pr->used_targets[i].pid == cp->pid)
2627 GNUNET_STATISTICS_update (stats,
2628 gettext_noop ("# queries retransmitted to same target"),
2634 /* build message and insert message into priority queue */
2636 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2637 "Forwarding request `%s' to `%4s'!\n",
2638 GNUNET_h2s (&pr->query),
2643 if (GNUNET_YES == no_route)
2645 bm |= GET_MESSAGE_BIT_RETURN_TO;
2648 if (pr->namespace != NULL)
2650 bm |= GET_MESSAGE_BIT_SKS_NAMESPACE;
2653 if (pr->target_pid != 0)
2655 bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
2658 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
2659 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
2660 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
2662 gm = (struct GetMessage*) &pm[1];
2663 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
2664 gm->header.size = htons (msize);
2665 gm->type = htonl (pr->type);
2666 pr->remaining_priority /= 2;
2667 gm->priority = htonl (pr->remaining_priority);
2668 gm->ttl = htonl (pr->ttl);
2669 gm->filter_mutator = htonl(pr->mingle);
2670 gm->hash_bitmap = htonl (bm);
2671 gm->query = pr->query;
2672 ext = (GNUNET_HashCode*) &gm[1];
2674 if (GNUNET_YES == no_route)
2675 GNUNET_PEER_resolve (pr->cp->pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
2676 if (pr->namespace != NULL)
2677 memcpy (&ext[k++], pr->namespace, sizeof (GNUNET_HashCode));
2678 if (pr->target_pid != 0)
2679 GNUNET_PEER_resolve (pr->target_pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
2680 bfdata = (char *) &ext[k];
2682 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
2685 pm->cont = &transmit_query_continuation;
2687 cp->last_request_times[(cp->last_request_times_off++) % MAX_QUEUE_PER_PEER] = GNUNET_TIME_absolute_get ();
2688 add_to_pending_messages_for_peer (cp, pm, pr);
2693 * Closure used for "target_peer_select_cb".
2695 struct PeerSelectionContext
2698 * The request for which we are selecting
2701 struct PendingRequest *pr;
2704 * Current "prime" target.
2706 struct GNUNET_PeerIdentity target;
2709 * How much do we like this target?
2711 double target_score;
2717 * Function called for each connected peer to determine
2718 * which one(s) would make good targets for forwarding.
2720 * @param cls closure (struct PeerSelectionContext)
2721 * @param key current key code (peer identity)
2722 * @param value value in the hash map (struct ConnectedPeer)
2723 * @return GNUNET_YES if we should continue to
2728 target_peer_select_cb (void *cls,
2729 const GNUNET_HashCode * key,
2732 struct PeerSelectionContext *psc = cls;
2733 struct ConnectedPeer *cp = value;
2734 struct PendingRequest *pr = psc->pr;
2735 struct GNUNET_TIME_Relative delay;
2740 /* 1) check that this peer is not the initiator */
2744 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2745 "Skipping initiator in forwarding selection\n");
2747 return GNUNET_YES; /* skip */
2750 /* 2) check if we have already (recently) forwarded to this peer */
2751 /* 2a) this particular request */
2753 for (i=0;i<pr->used_targets_off;i++)
2754 if (pr->used_targets[i].pid == cp->pid)
2756 pc = pr->used_targets[i].num_requests;
2757 GNUNET_assert (pc > 0);
2758 if (0 != GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2759 RETRY_PROBABILITY_INV * pc))
2762 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2763 "NOT re-trying query that was previously transmitted %u times\n",
2766 return GNUNET_YES; /* skip */
2773 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2774 "Re-trying query that was previously transmitted %u times to this peer\n",
2778 /* 2b) many other requests to this peer */
2779 delay = GNUNET_TIME_absolute_get_duration (cp->last_request_times[cp->last_request_times_off % MAX_QUEUE_PER_PEER]);
2780 if (delay.rel_value <= cp->avg_delay.rel_value)
2783 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2784 "NOT sending query since we send %u others to this peer in the last %llums\n",
2786 cp->avg_delay.rel_value);
2788 return GNUNET_YES; /* skip */
2791 /* 3) calculate how much we'd like to forward to this peer,
2792 starting with a random value that is strong enough
2793 to at least give any peer a chance sometimes
2794 (compared to the other factors that come later) */
2795 /* 3a) count successful (recent) routes from cp for same source */
2798 score = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2799 P2P_SUCCESS_LIST_SIZE);
2800 for (i=0;i<P2P_SUCCESS_LIST_SIZE;i++)
2801 if (cp->last_p2p_replies[i] == pr->cp->pid)
2802 score += 1.0; /* likely successful based on hot path */
2806 score = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2807 CS2P_SUCCESS_LIST_SIZE);
2808 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
2809 if (cp->last_client_replies[i] == pr->client_request_list->client_list->client)
2810 score += 1.0; /* likely successful based on hot path */
2812 /* 3b) include latency */
2813 if (cp->avg_delay.rel_value < 4 * TTL_DECREMENT)
2814 score += 1.0; /* likely fast based on latency */
2815 /* 3c) include priorities */
2816 if (cp->avg_priority <= pr->remaining_priority / 2.0)
2817 score += 1.0; /* likely successful based on priorities */
2818 /* 3d) penalize for queue size */
2819 score -= (2.0 * cp->pending_requests / (double) MAX_QUEUE_PER_PEER);
2820 /* 3e) include peer proximity */
2821 score -= (2.0 * (GNUNET_CRYPTO_hash_distance_u32 (key,
2822 &pr->query)) / (double) UINT32_MAX);
2823 /* 4) super-bonus for being the known target */
2824 if (pr->target_pid == cp->pid)
2826 /* store best-fit in closure */
2828 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2829 "Peer `%s' gets score %f for forwarding query, max is %f\n",
2834 score++; /* avoid zero */
2835 if (score > psc->target_score)
2837 psc->target_score = score;
2838 psc->target.hashPubKey = *key;
2845 * The priority level imposes a bound on the maximum
2846 * value for the ttl that can be requested.
2848 * @param ttl_in requested ttl
2849 * @param prio given priority
2850 * @return ttl_in if ttl_in is below the limit,
2851 * otherwise the ttl-limit for the given priority
2854 bound_ttl (int32_t ttl_in, uint32_t prio)
2856 unsigned long long allowed;
2860 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
2861 if (ttl_in > allowed)
2863 if (allowed >= (1 << 30))
2872 * Iterator called on each result obtained for a DHT
2873 * operation that expects a reply
2875 * @param cls closure
2876 * @param exp when will this value expire
2877 * @param key key of the result
2878 * @param get_path NULL-terminated array of pointers
2879 * to the peers on reverse GET path (or NULL if not recorded)
2880 * @param put_path NULL-terminated array of pointers
2881 * to the peers on the PUT path (or NULL if not recorded)
2882 * @param type type of the result
2883 * @param size number of bytes in data
2884 * @param data pointer to the result data
2887 process_dht_reply (void *cls,
2888 struct GNUNET_TIME_Absolute exp,
2889 const GNUNET_HashCode * key,
2890 const struct GNUNET_PeerIdentity * const *get_path,
2891 const struct GNUNET_PeerIdentity * const *put_path,
2892 enum GNUNET_BLOCK_Type type,
2898 * We're processing a GET request and have decided
2899 * to forward it to other peers. This function is called periodically
2900 * and should forward the request to other peers until we have all
2901 * possible replies. If we have transmitted the *only* reply to
2902 * the initiator we should destroy the pending request. If we have
2903 * many replies in the queue to the initiator, we should delay sending
2904 * out more queries until the reply queue has shrunk some.
2906 * @param cls our "struct ProcessGetContext *"
2910 forward_request_task (void *cls,
2911 const struct GNUNET_SCHEDULER_TaskContext *tc)
2913 struct PendingRequest *pr = cls;
2914 struct PeerSelectionContext psc;
2915 struct ConnectedPeer *cp;
2916 struct GNUNET_TIME_Relative delay;
2918 pr->task = GNUNET_SCHEDULER_NO_TASK;
2919 if (pr->irc != NULL)
2922 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2923 "Forwarding of query `%s' not attempted due to pending local lookup!\n",
2924 GNUNET_h2s (&pr->query));
2926 return; /* already pending */
2928 if (GNUNET_YES == pr->local_only)
2929 return; /* configured to not do P2P search */
2931 if ( (0 == pr->anonymity_level) &&
2932 (GNUNET_YES != pr->forward_only) &&
2933 (pr->type != GNUNET_BLOCK_TYPE_FS_DBLOCK) &&
2934 (pr->type != GNUNET_BLOCK_TYPE_FS_IBLOCK) )
2936 pr->dht_get = GNUNET_DHT_get_start (dht_handle,
2937 GNUNET_TIME_UNIT_FOREVER_REL,
2940 DEFAULT_GET_REPLICATION,
2945 (pr->namespace != NULL) ? sizeof (GNUNET_HashCode) : 0,
2949 /* (1) select target */
2951 psc.target_score = -DBL_MAX;
2952 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
2953 &target_peer_select_cb,
2955 if (psc.target_score == -DBL_MAX)
2957 delay = get_processing_delay ();
2959 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2960 "No peer selected for forwarding of query `%s', will try again in %llu ms!\n",
2961 GNUNET_h2s (&pr->query),
2964 pr->task = GNUNET_SCHEDULER_add_delayed (delay,
2965 &forward_request_task,
2967 return; /* nobody selected */
2969 /* (3) update TTL/priority */
2970 if (pr->client_request_list != NULL)
2972 /* FIXME: use better algorithm!? */
2973 if (0 == GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2976 /* bound priority we use by priorities we see from other peers
2977 rounded up (must round up so that we can see non-zero
2978 priorities, but round up as little as possible to make it
2979 plausible that we forwarded another peers request) */
2980 if (pr->priority > current_priorities + 1.0)
2981 pr->priority = (uint32_t) current_priorities + 1.0;
2982 pr->ttl = bound_ttl (pr->ttl + TTL_DECREMENT * 2,
2985 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2986 "Trying query `%s' with priority %u and TTL %d.\n",
2987 GNUNET_h2s (&pr->query),
2993 /* (3) reserve reply bandwidth */
2994 if (GNUNET_NO == pr->forward_only)
2996 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2997 &psc.target.hashPubKey);
2998 GNUNET_assert (NULL != cp);
2999 pr->irc = GNUNET_CORE_peer_change_preference (core,
3001 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
3002 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
3005 &target_reservation_cb,
3007 cp->inc_preference = 0;
3011 /* force forwarding */
3012 static struct GNUNET_BANDWIDTH_Value32NBO zerobw;
3013 target_reservation_cb (pr, &psc.target,
3019 /* **************************** P2P PUT Handling ************************ */
3023 * Function called after we either failed or succeeded
3024 * at transmitting a reply to a peer.
3026 * @param cls the requests "struct PendingRequest*"
3027 * @param tpid ID of receiving peer, 0 on transmission error
3030 transmit_reply_continuation (void *cls,
3031 GNUNET_PEER_Id tpid)
3033 struct PendingRequest *pr = cls;
3037 case GNUNET_BLOCK_TYPE_FS_DBLOCK:
3038 case GNUNET_BLOCK_TYPE_FS_IBLOCK:
3039 /* only one reply expected, done with the request! */
3040 destroy_pending_request (pr);
3042 case GNUNET_BLOCK_TYPE_ANY:
3043 case GNUNET_BLOCK_TYPE_FS_KBLOCK:
3044 case GNUNET_BLOCK_TYPE_FS_SBLOCK:
3054 * Transmit the given message by copying it to the target buffer
3055 * "buf". "buf" will be NULL and "size" zero if the socket was closed
3056 * for writing in the meantime. In that case, do nothing
3057 * (the disconnect or shutdown handler will take care of the rest).
3058 * If we were able to transmit messages and there are still more
3059 * pending, ask core again for further calls to this function.
3061 * @param cls closure, pointer to the 'struct ClientList*'
3062 * @param size number of bytes available in buf
3063 * @param buf where the callee should write the message
3064 * @return number of bytes written to buf
3067 transmit_to_client (void *cls,
3068 size_t size, void *buf)
3070 struct ClientList *cl = cls;
3072 struct ClientResponseMessage *creply;
3079 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3080 "Not sending reply, client communication problem.\n");
3085 while ( (NULL != (creply = cl->res_head) ) &&
3086 (creply->msize <= size) )
3088 memcpy (&cbuf[msize], &creply[1], creply->msize);
3089 msize += creply->msize;
3090 size -= creply->msize;
3091 GNUNET_CONTAINER_DLL_remove (cl->res_head,
3094 GNUNET_free (creply);
3097 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
3099 GNUNET_TIME_UNIT_FOREVER_REL,
3100 &transmit_to_client,
3103 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3104 "Transmitted %u bytes to client\n",
3105 (unsigned int) msize);
3112 * Closure for "process_reply" function.
3114 struct ProcessReplyClosure
3117 * The data for the reply.
3122 * Who gave us this reply? NULL for local host (or DHT)
3124 struct ConnectedPeer *sender;
3127 * When the reply expires.
3129 struct GNUNET_TIME_Absolute expiration;
3137 * Type of the block.
3139 enum GNUNET_BLOCK_Type type;
3142 * How much was this reply worth to us?
3147 * Evaluation result (returned).
3149 enum GNUNET_BLOCK_EvaluationResult eval;
3152 * Did we finish processing the associated request?
3157 * Did we find a matching request?
3164 * We have received a reply; handle it!
3166 * @param cls response (struct ProcessReplyClosure)
3167 * @param key our query
3168 * @param value value in the hash map (info about the query)
3169 * @return GNUNET_YES (we should continue to iterate)
3172 process_reply (void *cls,
3173 const GNUNET_HashCode * key,
3176 struct ProcessReplyClosure *prq = cls;
3177 struct PendingRequest *pr = value;
3178 struct PendingMessage *reply;
3179 struct ClientResponseMessage *creply;
3180 struct ClientList *cl;
3181 struct PutMessage *pm;
3182 struct ConnectedPeer *cp;
3183 struct GNUNET_TIME_Relative cur_delay;
3185 struct GNUNET_TIME_Relative art_delay;
3191 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3192 "Matched result (type %u) for query `%s' with pending request\n",
3193 (unsigned int) prq->type,
3196 GNUNET_STATISTICS_update (stats,
3197 gettext_noop ("# replies received and matched"),
3200 if (prq->sender != NULL)
3202 for (i=0;i<pr->used_targets_off;i++)
3203 if (pr->used_targets[i].pid == prq->sender->pid)
3205 if (i < pr->used_targets_off)
3207 cur_delay = GNUNET_TIME_absolute_get_duration (pr->used_targets[i].last_request_time);
3208 prq->sender->avg_delay.rel_value
3209 = (prq->sender->avg_delay.rel_value *
3210 (RUNAVG_DELAY_N - 1) + cur_delay.rel_value) / RUNAVG_DELAY_N;
3211 prq->sender->avg_priority
3212 = (prq->sender->avg_priority *
3213 (RUNAVG_DELAY_N - 1) + pr->priority) / (double) RUNAVG_DELAY_N;
3217 GNUNET_PEER_change_rc (prq->sender->last_p2p_replies
3218 [prq->sender->last_p2p_replies_woff % P2P_SUCCESS_LIST_SIZE],
3220 GNUNET_PEER_change_rc (pr->cp->pid, 1);
3221 prq->sender->last_p2p_replies
3222 [(prq->sender->last_p2p_replies_woff++) % P2P_SUCCESS_LIST_SIZE]
3227 if (NULL != prq->sender->last_client_replies
3228 [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE])
3229 GNUNET_SERVER_client_drop (prq->sender->last_client_replies
3230 [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE]);
3231 prq->sender->last_client_replies
3232 [(prq->sender->last_client_replies_woff++) % CS2P_SUCCESS_LIST_SIZE]
3233 = pr->client_request_list->client_list->client;
3234 GNUNET_SERVER_client_keep (pr->client_request_list->client_list->client);
3237 prq->eval = GNUNET_BLOCK_evaluate (block_ctx,
3242 pr->namespace, (pr->namespace != NULL) ? sizeof (GNUNET_HashCode) : 0,
3247 case GNUNET_BLOCK_EVALUATION_OK_MORE:
3249 case GNUNET_BLOCK_EVALUATION_OK_LAST:
3250 while (NULL != pr->pending_head)
3251 destroy_pending_message_list_entry (pr->pending_head);
3254 if (pr->client_request_list != NULL)
3255 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
3257 GNUNET_DATASTORE_cancel (pr->qe);
3260 pr->do_remove = GNUNET_YES;
3261 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
3263 GNUNET_SCHEDULER_cancel (pr->task);
3264 pr->task = GNUNET_SCHEDULER_NO_TASK;
3266 GNUNET_break (GNUNET_YES ==
3267 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
3270 GNUNET_LOAD_update (rt_entry_lifetime,
3271 GNUNET_TIME_absolute_get_duration (pr->start_time).rel_value);
3273 case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
3274 GNUNET_STATISTICS_update (stats,
3275 gettext_noop ("# duplicate replies discarded (bloomfilter)"),
3279 /* GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3280 "Duplicate response `%s', discarding.\n",
3281 GNUNET_h2s (&mhash));*/
3283 return GNUNET_YES; /* duplicate */
3284 case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
3285 return GNUNET_YES; /* wrong namespace */
3286 case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
3289 case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
3292 case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
3293 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3294 _("Unsupported block type %u\n"),
3298 if (pr->client_request_list != NULL)
3300 if (pr->replies_seen_size == pr->replies_seen_off)
3301 GNUNET_array_grow (pr->replies_seen,
3302 pr->replies_seen_size,
3303 pr->replies_seen_size * 2 + 4);
3304 GNUNET_CRYPTO_hash (prq->data,
3306 &pr->replies_seen[pr->replies_seen_off++]);
3307 refresh_bloomfilter (pr);
3309 if (NULL == prq->sender)
3312 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3313 "Found result for query `%s' in local datastore\n",
3316 GNUNET_STATISTICS_update (stats,
3317 gettext_noop ("# results found locally"),
3321 prq->priority += pr->remaining_priority;
3322 pr->remaining_priority = 0;
3323 pr->results_found++;
3324 prq->request_found = GNUNET_YES;
3325 if (NULL != pr->client_request_list)
3327 GNUNET_STATISTICS_update (stats,
3328 gettext_noop ("# replies received for local clients"),
3331 cl = pr->client_request_list->client_list;
3332 msize = sizeof (struct PutMessage) + prq->size;
3333 creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
3334 creply->msize = msize;
3335 creply->client_list = cl;
3336 GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
3340 pm = (struct PutMessage*) &creply[1];
3341 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
3342 pm->header.size = htons (msize);
3343 pm->type = htonl (prq->type);
3344 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
3345 memcpy (&pm[1], prq->data, prq->size);
3349 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3350 "Transmitting result for query `%s' to client\n",
3353 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
3355 GNUNET_TIME_UNIT_FOREVER_REL,
3356 &transmit_to_client,
3359 GNUNET_break (cl->th != NULL);
3362 prq->finished = GNUNET_YES;
3363 destroy_pending_request (pr);
3370 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3371 "Transmitting result for query `%s' to other peer (PID=%u)\n",
3373 (unsigned int) cp->pid);
3375 GNUNET_STATISTICS_update (stats,
3376 gettext_noop ("# replies received for other peers"),
3379 msize = sizeof (struct PutMessage) + prq->size;
3380 reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
3381 reply->cont = &transmit_reply_continuation;
3382 reply->cont_cls = pr;
3384 art_delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
3385 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3388 = GNUNET_TIME_relative_to_absolute (art_delay);
3389 GNUNET_STATISTICS_update (stats,
3390 gettext_noop ("cummulative artificial delay introduced (ms)"),
3391 art_delay.abs_value,
3394 reply->msize = msize;
3395 reply->priority = UINT32_MAX; /* send replies first! */
3396 pm = (struct PutMessage*) &reply[1];
3397 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
3398 pm->header.size = htons (msize);
3399 pm->type = htonl (prq->type);
3400 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
3401 memcpy (&pm[1], prq->data, prq->size);
3402 add_to_pending_messages_for_peer (cp, reply, pr);
3409 * Iterator called on each result obtained for a DHT
3410 * operation that expects a reply
3412 * @param cls closure
3413 * @param exp when will this value expire
3414 * @param key key of the result
3415 * @param get_path NULL-terminated array of pointers
3416 * to the peers on reverse GET path (or NULL if not recorded)
3417 * @param put_path NULL-terminated array of pointers
3418 * to the peers on the PUT path (or NULL if not recorded)
3419 * @param type type of the result
3420 * @param size number of bytes in data
3421 * @param data pointer to the result data
3424 process_dht_reply (void *cls,
3425 struct GNUNET_TIME_Absolute exp,
3426 const GNUNET_HashCode * key,
3427 const struct GNUNET_PeerIdentity * const *get_path,
3428 const struct GNUNET_PeerIdentity * const *put_path,
3429 enum GNUNET_BLOCK_Type type,
3433 struct PendingRequest *pr = cls;
3434 struct ProcessReplyClosure prq;
3436 memset (&prq, 0, sizeof (prq));
3438 prq.expiration = exp;
3441 process_reply (&prq, key, pr);
3447 * Continuation called to notify client about result of the
3450 * @param cls closure
3451 * @param success GNUNET_SYSERR on failure
3452 * @param msg NULL on success, otherwise an error message
3455 put_migration_continuation (void *cls,
3459 struct GNUNET_TIME_Absolute *start = cls;
3460 struct GNUNET_TIME_Relative delay;
3462 delay = GNUNET_TIME_absolute_get_duration (*start);
3463 GNUNET_free (start);
3464 GNUNET_LOAD_update (datastore_put_load,
3466 if (GNUNET_OK == success)
3468 GNUNET_STATISTICS_update (stats,
3469 gettext_noop ("# datastore 'put' failures"),
3476 * Handle P2P "PUT" message.
3478 * @param cls closure, always NULL
3479 * @param other the other peer involved (sender or receiver, NULL
3480 * for loopback messages where we are both sender and receiver)
3481 * @param message the actual message
3482 * @param atsi performance information
3483 * @return GNUNET_OK to keep the connection open,
3484 * GNUNET_SYSERR to close it (signal serious error)
3487 handle_p2p_put (void *cls,
3488 const struct GNUNET_PeerIdentity *other,
3489 const struct GNUNET_MessageHeader *message,
3490 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
3492 const struct PutMessage *put;
3495 enum GNUNET_BLOCK_Type type;
3496 struct GNUNET_TIME_Absolute expiration;
3497 GNUNET_HashCode query;
3498 struct ProcessReplyClosure prq;
3499 struct GNUNET_TIME_Absolute *start;
3500 struct GNUNET_TIME_Relative block_time;
3502 struct ConnectedPeer *cp;
3503 struct PendingMessage *pm;
3504 struct MigrationStopMessage *msm;
3506 msize = ntohs (message->size);
3507 if (msize < sizeof (struct PutMessage))
3510 return GNUNET_SYSERR;
3512 put = (const struct PutMessage*) message;
3513 dsize = msize - sizeof (struct PutMessage);
3514 type = ntohl (put->type);
3515 expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
3517 if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
3518 return GNUNET_SYSERR;
3520 GNUNET_BLOCK_get_key (block_ctx,
3526 GNUNET_break_op (0);
3527 return GNUNET_SYSERR;
3530 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3531 "Received result for query `%s' from peer `%4s'\n",
3532 GNUNET_h2s (&query),
3533 GNUNET_i2s (other));
3535 GNUNET_STATISTICS_update (stats,
3536 gettext_noop ("# replies received (overall)"),
3539 /* now, lookup 'query' */
3540 prq.data = (const void*) &put[1];
3542 prq.sender = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3543 &other->hashPubKey);
3548 prq.expiration = expiration;
3550 prq.finished = GNUNET_NO;
3551 prq.request_found = GNUNET_NO;
3552 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
3556 if (prq.sender != NULL)
3558 prq.sender->inc_preference += CONTENT_BANDWIDTH_VALUE + 1000 * prq.priority;
3559 change_host_trust (prq.sender, prq.priority);
3561 if ( (GNUNET_YES == active_migration) &&
3562 (GNUNET_NO == test_put_load_too_high (prq.priority)) )
3565 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3566 "Replicating result for query `%s' with priority %u\n",
3567 GNUNET_h2s (&query),
3570 start = GNUNET_malloc (sizeof (struct GNUNET_TIME_Absolute));
3571 *start = GNUNET_TIME_absolute_get ();
3572 GNUNET_DATASTORE_put (dsh,
3573 0, &query, dsize, &put[1],
3574 type, prq.priority, 1 /* anonymity */,
3576 1 + prq.priority, MAX_DATASTORE_QUEUE,
3577 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
3578 &put_migration_continuation,
3581 putl = GNUNET_LOAD_get_load (datastore_put_load);
3582 if ( (GNUNET_NO == prq.request_found) &&
3583 ( (GNUNET_YES != active_migration) ||
3584 (putl > 2.5 * (1 + prq.priority)) ) )
3586 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3587 &other->hashPubKey);
3588 if (GNUNET_TIME_absolute_get_duration (cp->last_migration_block).rel_value < 5000)
3589 return GNUNET_OK; /* already blocked */
3590 /* We're too busy; send MigrationStop message! */
3591 if (GNUNET_YES != active_migration)
3592 putl = 1.0 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 5);
3593 block_time = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
3594 5000 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3595 (unsigned int) (60000 * putl * putl)));
3597 cp->last_migration_block = GNUNET_TIME_relative_to_absolute (block_time);
3598 pm = GNUNET_malloc (sizeof (struct PendingMessage) +
3599 sizeof (struct MigrationStopMessage));
3600 pm->msize = sizeof (struct MigrationStopMessage);
3601 pm->priority = UINT32_MAX;
3602 msm = (struct MigrationStopMessage*) &pm[1];
3603 msm->header.size = htons (sizeof (struct MigrationStopMessage));
3604 msm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP);
3605 msm->duration = GNUNET_TIME_relative_hton (block_time);
3606 add_to_pending_messages_for_peer (cp,
3615 * Handle P2P "MIGRATION_STOP" message.
3617 * @param cls closure, always NULL
3618 * @param other the other peer involved (sender or receiver, NULL
3619 * for loopback messages where we are both sender and receiver)
3620 * @param message the actual message
3621 * @param atsi performance information
3622 * @return GNUNET_OK to keep the connection open,
3623 * GNUNET_SYSERR to close it (signal serious error)
3626 handle_p2p_migration_stop (void *cls,
3627 const struct GNUNET_PeerIdentity *other,
3628 const struct GNUNET_MessageHeader *message,
3629 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
3631 struct ConnectedPeer *cp;
3632 const struct MigrationStopMessage *msm;
3634 msm = (const struct MigrationStopMessage*) message;
3635 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3636 &other->hashPubKey);
3642 cp->migration_blocked = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (msm->duration));
3648 /* **************************** P2P GET Handling ************************ */
3652 * Closure for 'check_duplicate_request_{peer,client}'.
3654 struct CheckDuplicateRequestClosure
3657 * The new request we should check if it already exists.
3659 const struct PendingRequest *pr;
3662 * Existing request found by the checker, NULL if none.
3664 struct PendingRequest *have;
3669 * Iterator over entries in the 'query_request_map' that
3670 * tries to see if we have the same request pending from
3671 * the same client already.
3673 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
3674 * @param key current key code (query, ignored, must match)
3675 * @param value value in the hash map (a 'struct PendingRequest'
3676 * that already exists)
3677 * @return GNUNET_YES if we should continue to
3678 * iterate (no match yet)
3679 * GNUNET_NO if not (match found).
3682 check_duplicate_request_client (void *cls,
3683 const GNUNET_HashCode * key,
3686 struct CheckDuplicateRequestClosure *cdc = cls;
3687 struct PendingRequest *have = value;
3689 if (have->client_request_list == NULL)
3691 if ( (cdc->pr->client_request_list->client_list->client == have->client_request_list->client_list->client) &&
3702 * We're processing (local) results for a search request
3703 * from another peer. Pass applicable results to the
3704 * peer and if we are done either clean up (operation
3705 * complete) or forward to other peers (more results possible).
3707 * @param cls our closure (struct LocalGetContext)
3708 * @param key key for the content
3709 * @param size number of bytes in data
3710 * @param data content stored
3711 * @param type type of the content
3712 * @param priority priority of the content
3713 * @param anonymity anonymity-level for the content
3714 * @param expiration expiration time for the content
3715 * @param uid unique identifier for the datum;
3716 * maybe 0 if no unique identifier is available
3719 process_local_reply (void *cls,
3720 const GNUNET_HashCode * key,
3723 enum GNUNET_BLOCK_Type type,
3726 struct GNUNET_TIME_Absolute
3730 struct PendingRequest *pr = cls;
3731 struct ProcessReplyClosure prq;
3732 struct CheckDuplicateRequestClosure cdrc;
3733 GNUNET_HashCode query;
3734 unsigned int old_rf;
3739 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3740 "Done processing local replies, forwarding request to other peers.\n");
3743 if (pr->client_request_list != NULL)
3745 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
3747 /* Figure out if this is a duplicate request and possibly
3748 merge 'struct PendingRequest' entries */
3751 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
3753 &check_duplicate_request_client,
3755 if (cdrc.have != NULL)
3758 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3759 "Received request for block `%s' twice from client, will only request once.\n",
3760 GNUNET_h2s (&pr->query));
3763 destroy_pending_request (pr);
3767 if (pr->local_only == GNUNET_YES)
3769 destroy_pending_request (pr);
3772 /* no more results */
3773 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
3774 pr->task = GNUNET_SCHEDULER_add_now (&forward_request_task,
3779 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3780 "New local response to `%s' of type %u.\n",
3784 if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
3787 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3788 "Found ONDEMAND block, performing on-demand encoding\n");
3790 GNUNET_STATISTICS_update (stats,
3791 gettext_noop ("# on-demand blocks matched requests"),
3795 GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
3796 anonymity, expiration, uid,
3797 &process_local_reply,
3801 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3805 old_rf = pr->results_found;
3806 memset (&prq, 0, sizeof (prq));
3808 prq.expiration = expiration;
3811 GNUNET_BLOCK_get_key (block_ctx,
3818 GNUNET_DATASTORE_remove (dsh,
3822 GNUNET_TIME_UNIT_FOREVER_REL,
3824 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3828 prq.priority = priority;
3829 prq.finished = GNUNET_NO;
3830 prq.request_found = GNUNET_NO;
3831 if ( (old_rf == 0) &&
3832 (pr->results_found == 0) )
3833 update_datastore_delays (pr->start_time);
3834 process_reply (&prq, key, pr);
3835 if (prq.finished == GNUNET_YES)
3838 return; /* done here */
3839 if (prq.eval == GNUNET_BLOCK_EVALUATION_OK_LAST)
3841 pr->local_only = GNUNET_YES; /* do not forward */
3842 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
3845 if ( (pr->client_request_list == NULL) &&
3846 ( (GNUNET_YES == test_get_load_too_high (0)) ||
3847 (pr->results_found > 5 + 2 * pr->priority) ) )
3850 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3851 "Load too high, done with request\n");
3853 GNUNET_STATISTICS_update (stats,
3854 gettext_noop ("# processing result set cut short due to load"),
3857 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
3860 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3865 * We've received a request with the specified priority. Bound it
3866 * according to how much we trust the given peer.
3868 * @param prio_in requested priority
3869 * @param cp the peer making the request
3870 * @return effective priority
3873 bound_priority (uint32_t prio_in,
3874 struct ConnectedPeer *cp)
3876 #define N ((double)128.0)
3881 ld = test_get_load_too_high (0);
3882 if (ld == GNUNET_SYSERR)
3884 GNUNET_STATISTICS_update (stats,
3885 gettext_noop ("# requests done for free (low load)"),
3888 return 0; /* excess resources */
3890 if (prio_in > INT32_MAX)
3891 prio_in = INT32_MAX;
3892 ret = - change_host_trust (cp, - (int) prio_in);
3895 if (ret > current_priorities + N)
3896 rret = current_priorities + N;
3900 = (current_priorities * (N-1) + rret)/N;
3902 if ( (ld == GNUNET_YES) && (ret > 0) )
3904 /* try with charging */
3905 ld = test_get_load_too_high (ret);
3907 if (ld == GNUNET_YES)
3909 GNUNET_STATISTICS_update (stats,
3910 gettext_noop ("# request dropped, priority insufficient"),
3914 change_host_trust (cp, (int) ret);
3915 return -1; /* not enough resources */
3919 GNUNET_STATISTICS_update (stats,
3920 gettext_noop ("# requests done for a price (normal load)"),
3930 * Iterator over entries in the 'query_request_map' that
3931 * tries to see if we have the same request pending from
3932 * the same peer already.
3934 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
3935 * @param key current key code (query, ignored, must match)
3936 * @param value value in the hash map (a 'struct PendingRequest'
3937 * that already exists)
3938 * @return GNUNET_YES if we should continue to
3939 * iterate (no match yet)
3940 * GNUNET_NO if not (match found).
3943 check_duplicate_request_peer (void *cls,
3944 const GNUNET_HashCode * key,
3947 struct CheckDuplicateRequestClosure *cdc = cls;
3948 struct PendingRequest *have = value;
3950 if (cdc->pr->target_pid == have->target_pid)
3960 * Handle P2P "GET" request.
3962 * @param cls closure, always NULL
3963 * @param other the other peer involved (sender or receiver, NULL
3964 * for loopback messages where we are both sender and receiver)
3965 * @param message the actual message
3966 * @param atsi performance information
3967 * @return GNUNET_OK to keep the connection open,
3968 * GNUNET_SYSERR to close it (signal serious error)
3971 handle_p2p_get (void *cls,
3972 const struct GNUNET_PeerIdentity *other,
3973 const struct GNUNET_MessageHeader *message,
3974 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
3976 struct PendingRequest *pr;
3977 struct ConnectedPeer *cp;
3978 struct ConnectedPeer *cps;
3979 struct CheckDuplicateRequestClosure cdc;
3980 struct GNUNET_TIME_Relative timeout;
3982 const struct GetMessage *gm;
3984 const GNUNET_HashCode *opt;
3987 uint32_t ttl_decrement;
3989 enum GNUNET_BLOCK_Type type;
3992 msize = ntohs(message->size);
3993 if (msize < sizeof (struct GetMessage))
3995 GNUNET_break_op (0);
3996 return GNUNET_SYSERR;
3998 gm = (const struct GetMessage*) message;
4000 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4001 "Received request for `%s'\n",
4002 GNUNET_h2s (&gm->query));
4004 type = ntohl (gm->type);
4005 bm = ntohl (gm->hash_bitmap);
4013 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
4015 GNUNET_break_op (0);
4016 return GNUNET_SYSERR;
4018 opt = (const GNUNET_HashCode*) &gm[1];
4019 bfsize = msize - sizeof (struct GetMessage) - bits * sizeof (GNUNET_HashCode);
4020 /* bfsize must be power of 2, check! */
4021 if (0 != ( (bfsize - 1) & bfsize))
4023 GNUNET_break_op (0);
4024 return GNUNET_SYSERR;
4026 bm = ntohl (gm->hash_bitmap);
4028 cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
4029 &other->hashPubKey);
4032 /* peer must have just disconnected */
4033 GNUNET_STATISTICS_update (stats,
4034 gettext_noop ("# requests dropped due to initiator not being connected"),
4037 return GNUNET_SYSERR;
4039 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
4040 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
4047 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
4048 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4049 "Failed to find RETURN-TO peer `%4s' in connection set. Dropping query.\n",
4050 GNUNET_i2s ((const struct GNUNET_PeerIdentity*) &opt[bits-1]));
4053 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4054 "Failed to find peer `%4s' in connection set. Dropping query.\n",
4055 GNUNET_i2s (other));
4057 GNUNET_STATISTICS_update (stats,
4058 gettext_noop ("# requests dropped due to missing reverse route"),
4061 /* FIXME: try connect? */
4064 /* note that we can really only check load here since otherwise
4065 peers could find out that we are overloaded by not being
4066 disconnected after sending us a malformed query... */
4067 priority = bound_priority (ntohl (gm->priority), cps);
4071 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4072 "Dropping query from `%s', this peer is too busy.\n",
4073 GNUNET_i2s (other));
4078 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4079 "Received request for `%s' of type %u from peer `%4s' with flags %u\n",
4080 GNUNET_h2s (&gm->query),
4081 (unsigned int) type,
4085 have_ns = (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE));
4086 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
4087 (have_ns ? sizeof(GNUNET_HashCode) : 0));
4090 pr->namespace = (GNUNET_HashCode*) &pr[1];
4091 memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
4093 if ( (GNUNET_LOAD_get_load (cp->transmission_delay) > 3 * (1 + priority)) ||
4094 (GNUNET_LOAD_get_average (cp->transmission_delay) >
4095 GNUNET_CONSTANTS_MAX_CORK_DELAY.rel_value * 2 + GNUNET_LOAD_get_average (rt_entry_lifetime)) )
4097 /* don't have BW to send to peer, or would likely take longer than we have for it,
4098 so at best indirect the query */
4100 pr->forward_only = GNUNET_YES;
4103 pr->mingle = ntohl (gm->filter_mutator);
4104 if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
4105 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
4106 pr->anonymity_level = 1;
4107 pr->priority = (uint32_t) priority;
4108 pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
4109 pr->query = gm->query;
4110 /* decrement ttl (always) */
4111 ttl_decrement = 2 * TTL_DECREMENT +
4112 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
4114 if ( (pr->ttl < 0) &&
4115 (((int32_t)(pr->ttl - ttl_decrement)) > 0) )
4118 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4119 "Dropping query from `%s' due to TTL underflow (%d - %u).\n",
4124 GNUNET_STATISTICS_update (stats,
4125 gettext_noop ("# requests dropped due TTL underflow"),
4128 /* integer underflow => drop (should be very rare)! */
4132 pr->ttl -= ttl_decrement;
4133 pr->start_time = GNUNET_TIME_absolute_get ();
4135 /* get bloom filter */
4138 pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
4141 pr->bf_size = bfsize;
4145 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
4147 &check_duplicate_request_peer,
4149 if (cdc.have != NULL)
4151 if (cdc.have->start_time.abs_value + cdc.have->ttl >=
4152 pr->start_time.abs_value + pr->ttl)
4154 /* existing request has higher TTL, drop new one! */
4155 cdc.have->priority += pr->priority;
4156 destroy_pending_request (pr);
4158 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4159 "Have existing request with higher TTL, dropping new request.\n",
4160 GNUNET_i2s (other));
4162 GNUNET_STATISTICS_update (stats,
4163 gettext_noop ("# requests dropped due to higher-TTL request"),
4170 /* existing request has lower TTL, drop old one! */
4171 pr->priority += cdc.have->priority;
4172 /* Possible optimization: if we have applicable pending
4173 replies in 'cdc.have', we might want to move those over
4174 (this is a really rare special-case, so it is not clear
4175 that this would be worth it) */
4176 destroy_pending_request (cdc.have);
4177 /* keep processing 'pr'! */
4182 GNUNET_break (GNUNET_OK ==
4183 GNUNET_CONTAINER_multihashmap_put (query_request_map,
4186 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
4187 GNUNET_break (GNUNET_OK ==
4188 GNUNET_CONTAINER_multihashmap_put (peer_request_map,
4191 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
4193 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
4195 pr->start_time.abs_value + pr->ttl);
4197 GNUNET_STATISTICS_update (stats,
4198 gettext_noop ("# P2P searches received"),
4201 GNUNET_STATISTICS_update (stats,
4202 gettext_noop ("# P2P searches active"),
4206 /* calculate change in traffic preference */
4207 cps->inc_preference += pr->priority * 1000 + QUERY_BANDWIDTH_VALUE;
4208 /* process locally */
4209 if (type == GNUNET_BLOCK_TYPE_FS_DBLOCK)
4210 type = GNUNET_BLOCK_TYPE_ANY; /* to get on-demand as well */
4211 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
4212 (pr->priority + 1));
4213 if (GNUNET_YES != pr->forward_only)
4216 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4217 "Handing request for `%s' to datastore\n",
4218 GNUNET_h2s (&gm->query));
4220 pr->qe = GNUNET_DATASTORE_get (dsh,
4224 MAX_DATASTORE_QUEUE,
4226 &process_local_reply,
4230 GNUNET_STATISTICS_update (stats,
4231 gettext_noop ("# requests dropped by datastore (queue length limit)"),
4238 GNUNET_STATISTICS_update (stats,
4239 gettext_noop ("# requests forwarded due to high load"),
4244 /* Are multiple results possible (and did we look locally)? If so, start processing remotely now! */
4247 case GNUNET_BLOCK_TYPE_FS_DBLOCK:
4248 case GNUNET_BLOCK_TYPE_FS_IBLOCK:
4249 /* only one result, wait for datastore */
4250 if (GNUNET_YES != pr->forward_only)
4252 GNUNET_STATISTICS_update (stats,
4253 gettext_noop ("# requests not instantly forwarded (waiting for datastore)"),
4259 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
4260 pr->task = GNUNET_SCHEDULER_add_now (&forward_request_task,
4264 /* make sure we don't track too many requests */
4265 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
4267 pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
4268 GNUNET_assert (pr != NULL);
4269 destroy_pending_request (pr);
4275 /* **************************** CS GET Handling ************************ */
4279 * Handle START_SEARCH-message (search request from client).
4281 * @param cls closure
4282 * @param client identification of the client
4283 * @param message the actual message
4286 handle_start_search (void *cls,
4287 struct GNUNET_SERVER_Client *client,
4288 const struct GNUNET_MessageHeader *message)
4290 static GNUNET_HashCode all_zeros;
4291 const struct SearchMessage *sm;
4292 struct ClientList *cl;
4293 struct ClientRequestList *crl;
4294 struct PendingRequest *pr;
4297 enum GNUNET_BLOCK_Type type;
4299 msize = ntohs (message->size);
4300 if ( (msize < sizeof (struct SearchMessage)) ||
4301 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
4304 GNUNET_SERVER_receive_done (client,
4308 GNUNET_STATISTICS_update (stats,
4309 gettext_noop ("# client searches received"),
4312 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
4313 sm = (const struct SearchMessage*) message;
4314 type = ntohl (sm->type);
4316 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4317 "Received request for `%s' of type %u from local client\n",
4318 GNUNET_h2s (&sm->query),
4319 (unsigned int) type);
4322 while ( (cl != NULL) &&
4323 (cl->client != client) )
4327 cl = GNUNET_malloc (sizeof (struct ClientList));
4328 cl->client = client;
4329 GNUNET_SERVER_client_keep (client);
4330 cl->next = client_list;
4333 /* detect duplicate KBLOCK requests */
4334 if ( (type == GNUNET_BLOCK_TYPE_FS_KBLOCK) ||
4335 (type == GNUNET_BLOCK_TYPE_FS_NBLOCK) ||
4336 (type == GNUNET_BLOCK_TYPE_ANY) )
4339 while ( (crl != NULL) &&
4340 ( (0 != memcmp (&crl->req->query,
4342 sizeof (GNUNET_HashCode))) ||
4343 (crl->req->type != type) ) )
4348 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4349 "Have existing request, merging content-seen lists.\n");
4352 /* Duplicate request (used to send long list of
4353 known/blocked results); merge 'pr->replies_seen'
4354 and update bloom filter */
4355 GNUNET_array_grow (pr->replies_seen,
4356 pr->replies_seen_size,
4357 pr->replies_seen_off + sc);
4358 memcpy (&pr->replies_seen[pr->replies_seen_off],
4360 sc * sizeof (GNUNET_HashCode));
4361 pr->replies_seen_off += sc;
4362 refresh_bloomfilter (pr);
4363 GNUNET_STATISTICS_update (stats,
4364 gettext_noop ("# client searches updated (merged content seen list)"),
4367 GNUNET_SERVER_receive_done (client,
4372 GNUNET_STATISTICS_update (stats,
4373 gettext_noop ("# client searches active"),
4376 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
4377 ((type == GNUNET_BLOCK_TYPE_FS_SBLOCK) ? sizeof(GNUNET_HashCode) : 0));
4378 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
4379 memset (crl, 0, sizeof (struct ClientRequestList));
4380 crl->client_list = cl;
4381 GNUNET_CONTAINER_DLL_insert (cl->rl_head,
4386 pr->client_request_list = crl;
4387 GNUNET_array_grow (pr->replies_seen,
4388 pr->replies_seen_size,
4390 memcpy (pr->replies_seen,
4392 sc * sizeof (GNUNET_HashCode));
4393 pr->replies_seen_off = sc;
4394 pr->anonymity_level = ntohl (sm->anonymity_level);
4395 pr->start_time = GNUNET_TIME_absolute_get ();
4396 refresh_bloomfilter (pr);
4397 pr->query = sm->query;
4398 if (0 == (1 & ntohl (sm->options)))
4399 pr->local_only = GNUNET_NO;
4401 pr->local_only = GNUNET_YES;
4404 case GNUNET_BLOCK_TYPE_FS_DBLOCK:
4405 case GNUNET_BLOCK_TYPE_FS_IBLOCK:
4406 if (0 != memcmp (&sm->target,
4408 sizeof (GNUNET_HashCode)))
4409 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
4411 case GNUNET_BLOCK_TYPE_FS_SBLOCK:
4412 pr->namespace = (GNUNET_HashCode*) &pr[1];
4413 memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
4418 GNUNET_break (GNUNET_OK ==
4419 GNUNET_CONTAINER_multihashmap_put (query_request_map,
4422 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
4423 if (type == GNUNET_BLOCK_TYPE_FS_DBLOCK)
4424 type = GNUNET_BLOCK_TYPE_ANY; /* get on-demand blocks too! */
4425 pr->qe = GNUNET_DATASTORE_get (dsh,
4429 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
4430 &process_local_reply,
4435 /* **************************** Startup ************************ */
4438 * Process fs requests.
4440 * @param server the initialized server
4441 * @param c configuration to use
4444 main_init (struct GNUNET_SERVER_Handle *server,
4445 const struct GNUNET_CONFIGURATION_Handle *c)
4447 static const struct GNUNET_CORE_MessageHandler p2p_handlers[] =
4450 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
4452 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
4453 { &handle_p2p_migration_stop,
4454 GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP,
4455 sizeof (struct MigrationStopMessage) },
4458 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
4459 {&GNUNET_FS_handle_index_start, NULL,
4460 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
4461 {&GNUNET_FS_handle_index_list_get, NULL,
4462 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
4463 {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
4464 sizeof (struct UnindexMessage) },
4465 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
4469 unsigned long long enc = 128;
4472 stats = GNUNET_STATISTICS_create ("fs", cfg);
4473 min_migration_delay = GNUNET_TIME_UNIT_SECONDS;
4475 GNUNET_CONFIGURATION_get_value_number (cfg,
4477 "MAX_PENDING_REQUESTS",
4478 &max_pending_requests)) ||
4480 GNUNET_CONFIGURATION_get_value_number (cfg,
4482 "EXPECTED_NEIGHBOUR_COUNT",
4485 GNUNET_CONFIGURATION_get_value_time (cfg,
4487 "MIN_MIGRATION_DELAY",
4488 &min_migration_delay)) )
4490 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4491 _("Configuration fails to specify certain parameters, assuming default values."));
4493 connected_peers = GNUNET_CONTAINER_multihashmap_create (enc);
4494 query_request_map = GNUNET_CONTAINER_multihashmap_create (max_pending_requests);
4495 rt_entry_lifetime = GNUNET_LOAD_value_init (GNUNET_TIME_UNIT_FOREVER_REL);
4496 peer_request_map = GNUNET_CONTAINER_multihashmap_create (enc);
4497 requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
4498 core = GNUNET_CORE_connect (cfg,
4502 &peer_connect_handler,
4503 &peer_disconnect_handler,
4504 &peer_status_handler,
4510 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4511 _("Failed to connect to `%s' service.\n"),
4513 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
4514 connected_peers = NULL;
4515 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
4516 query_request_map = NULL;
4517 GNUNET_LOAD_value_free (rt_entry_lifetime);
4518 rt_entry_lifetime = NULL;
4519 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
4520 requests_by_expiration_heap = NULL;
4521 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
4522 peer_request_map = NULL;
4525 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
4528 return GNUNET_SYSERR;
4530 /* FIXME: distinguish between sending and storing in options? */
4531 if (active_migration)
4533 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4534 _("Content migration is enabled, will start to gather data\n"));
4535 consider_migration_gathering ();
4537 consider_dht_put_gathering (NULL);
4538 GNUNET_SERVER_disconnect_notify (server,
4539 &handle_client_disconnect,
4541 GNUNET_assert (GNUNET_OK ==
4542 GNUNET_CONFIGURATION_get_value_filename (cfg,
4546 GNUNET_DISK_directory_create (trustDirectory);
4547 GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_HIGH,
4548 &cron_flush_trust, NULL);
4551 GNUNET_SERVER_add_handlers (server, handlers);
4552 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4560 * Process fs requests.
4562 * @param cls closure
4563 * @param server the initialized server
4564 * @param cfg configuration to use
4568 struct GNUNET_SERVER_Handle *server,
4569 const struct GNUNET_CONFIGURATION_Handle *cfg)
4571 active_migration = GNUNET_CONFIGURATION_get_value_yesno (cfg,
4574 dsh = GNUNET_DATASTORE_connect (cfg);
4577 GNUNET_SCHEDULER_shutdown ();
4580 datastore_get_load = GNUNET_LOAD_value_init (DATASTORE_LOAD_AUTODECLINE);
4581 datastore_put_load = GNUNET_LOAD_value_init (DATASTORE_LOAD_AUTODECLINE);
4582 block_cfg = GNUNET_CONFIGURATION_create ();
4583 GNUNET_CONFIGURATION_set_value_string (block_cfg,
4587 block_ctx = GNUNET_BLOCK_context_create (block_cfg);
4588 GNUNET_assert (NULL != block_ctx);
4589 dht_handle = GNUNET_DHT_connect (cfg,
4591 if ( (GNUNET_OK != GNUNET_FS_indexing_init (cfg, dsh)) ||
4592 (GNUNET_OK != main_init (server, cfg)) )
4594 GNUNET_SCHEDULER_shutdown ();
4595 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
4597 GNUNET_DHT_disconnect (dht_handle);
4599 GNUNET_BLOCK_context_destroy (block_ctx);
4601 GNUNET_CONFIGURATION_destroy (block_cfg);
4603 GNUNET_LOAD_value_free (datastore_get_load);
4604 datastore_get_load = NULL;
4605 GNUNET_LOAD_value_free (datastore_put_load);
4606 datastore_put_load = NULL;
4613 * The main function for the fs service.
4615 * @param argc number of arguments from the command line
4616 * @param argv command line arguments
4617 * @return 0 ok, 1 on error
4620 main (int argc, char *const *argv)
4622 return (GNUNET_OK ==
4623 GNUNET_SERVICE_run (argc,
4626 GNUNET_SERVICE_OPTION_NONE,
4627 &run, NULL)) ? 0 : 1;
4630 /* end of gnunet-service-fs.c */