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 * Context of our GNUNET_CORE_peer_change_preference call (or NULL).
288 struct GNUNET_CORE_InformationRequestContext *irc;
291 * Request for which 'irc' is currently active (or NULL).
293 struct PendingRequest *pr;
296 * Time when the last transmission request was issued.
298 struct GNUNET_TIME_Absolute last_transmission_request_start;
301 * ID of delay task for scheduling transmission.
303 GNUNET_SCHEDULER_TaskIdentifier delayed_transmission_request_task;
306 * Average priority of successful replies. Calculated
307 * as a moving average: new_avg = ((n-1)*last_avg+curr_prio) / n
312 * Increase in traffic preference still to be submitted
313 * to the core service for this peer.
315 uint64_t inc_preference;
318 * Trust rating for this peer
323 * Trust rating for this peer on disk.
328 * The peer's identity.
333 * Size of the linked list of 'pending_messages'.
335 unsigned int pending_requests;
338 * Which offset in "last_p2p_replies" will be updated next?
339 * (we go round-robin).
341 unsigned int last_p2p_replies_woff;
344 * Which offset in "last_client_replies" will be updated next?
345 * (we go round-robin).
347 unsigned int last_client_replies_woff;
350 * Current offset into 'last_request_times' ring buffer.
352 unsigned int last_request_times_off;
358 * Information we keep for each pending request. We should try to
359 * keep this struct as small as possible since its memory consumption
360 * is key to how many requests we can have pending at once.
362 struct PendingRequest;
366 * Doubly-linked list of requests we are performing
367 * on behalf of the same client.
369 struct ClientRequestList
373 * This is a doubly-linked list.
375 struct ClientRequestList *next;
378 * This is a doubly-linked list.
380 struct ClientRequestList *prev;
383 * Request this entry represents.
385 struct PendingRequest *req;
388 * Client list this request belongs to.
390 struct ClientList *client_list;
396 * Replies to be transmitted to the client. The actual
397 * response message is allocated after this struct.
399 struct ClientResponseMessage
402 * This is a doubly-linked list.
404 struct ClientResponseMessage *next;
407 * This is a doubly-linked list.
409 struct ClientResponseMessage *prev;
412 * Client list entry this response belongs to.
414 struct ClientList *client_list;
417 * Number of bytes in the response.
424 * Linked list of clients we are performing requests
430 * This is a linked list.
432 struct ClientList *next;
435 * ID of a client making a request, NULL if this entry is for a
438 struct GNUNET_SERVER_Client *client;
441 * Head of list of requests performed on behalf
442 * of this client right now.
444 struct ClientRequestList *rl_head;
447 * Tail of list of requests performed on behalf
448 * of this client right now.
450 struct ClientRequestList *rl_tail;
453 * Head of linked list of responses.
455 struct ClientResponseMessage *res_head;
458 * Tail of linked list of responses.
460 struct ClientResponseMessage *res_tail;
463 * Context for sending replies.
465 struct GNUNET_CONNECTION_TransmitHandle *th;
471 * Information about a peer that we have forwarded this
472 * request to already.
474 struct UsedTargetEntry
477 * What was the last time we have transmitted this request to this
480 struct GNUNET_TIME_Absolute last_request_time;
483 * How often have we transmitted this request to this peer?
485 unsigned int num_requests;
488 * PID of the target peer.
499 * Doubly-linked list of messages we are performing
500 * due to a pending request.
502 struct PendingMessageList
506 * This is a doubly-linked list of messages on behalf of the same request.
508 struct PendingMessageList *next;
511 * This is a doubly-linked list of messages on behalf of the same request.
513 struct PendingMessageList *prev;
516 * Message this entry represents.
518 struct PendingMessage *pm;
521 * Request this entry belongs to.
523 struct PendingRequest *req;
526 * Peer this message is targeted for.
528 struct ConnectedPeer *target;
534 * Information we keep for each pending request. We should try to
535 * keep this struct as small as possible since its memory consumption
536 * is key to how many requests we can have pending at once.
538 struct PendingRequest
542 * If this request was made by a client, this is our entry in the
543 * client request list; otherwise NULL.
545 struct ClientRequestList *client_request_list;
548 * Entry of peer responsible for this entry (if this request
549 * was made by a peer).
551 struct ConnectedPeer *cp;
554 * If this is a namespace query, pointer to the hash of the public
555 * key of the namespace; otherwise NULL. Pointer will be to the
556 * end of this struct (so no need to free it).
558 const GNUNET_HashCode *namespace;
561 * Bloomfilter we use to filter out replies that we don't care about
562 * (anymore). NULL as long as we are interested in all replies.
564 struct GNUNET_CONTAINER_BloomFilter *bf;
567 * Reference to DHT get operation for this request (or NULL).
569 struct GNUNET_DHT_GetHandle *dht_get;
572 * Context of our GNUNET_CORE_peer_change_preference call.
574 struct ConnectedPeer *pirc;
577 * Hash code of all replies that we have seen so far (only valid
578 * if client is not NULL since we only track replies like this for
581 GNUNET_HashCode *replies_seen;
584 * Node in the heap representing this entry; NULL
585 * if we have no heap node.
587 struct GNUNET_CONTAINER_HeapNode *hnode;
590 * Head of list of messages being performed on behalf of this
593 struct PendingMessageList *pending_head;
596 * Tail of list of messages being performed on behalf of this
599 struct PendingMessageList *pending_tail;
602 * When did we first see this request (form this peer), or, if our
603 * client is initiating, when did we last initiate a search?
605 struct GNUNET_TIME_Absolute start_time;
608 * The query that this request is for.
610 GNUNET_HashCode query;
613 * The task responsible for transmitting queries
616 GNUNET_SCHEDULER_TaskIdentifier task;
619 * (Interned) Peer identifier that identifies a preferred target
622 GNUNET_PEER_Id target_pid;
625 * (Interned) Peer identifiers of peers that have already
626 * received our query for this content.
628 struct UsedTargetEntry *used_targets;
631 * Our entry in the queue (non-NULL while we wait for our
632 * turn to interact with the local database).
634 struct GNUNET_DATASTORE_QueueEntry *qe;
637 * Size of the 'bf' (in bytes).
642 * Desired anonymity level; only valid for requests from a local client.
644 uint32_t anonymity_level;
647 * How many entries in "used_targets" are actually valid?
649 unsigned int used_targets_off;
652 * How long is the "used_targets" array?
654 unsigned int used_targets_size;
657 * Number of results found for this request.
659 unsigned int results_found;
662 * How many entries in "replies_seen" are actually valid?
664 unsigned int replies_seen_off;
667 * How long is the "replies_seen" array?
669 unsigned int replies_seen_size;
672 * Priority with which this request was made. If one of our clients
673 * made the request, then this is the current priority that we are
674 * using when initiating the request. This value is used when
675 * we decide to reward other peers with trust for providing a reply.
680 * Priority points left for us to spend when forwarding this request
683 uint32_t remaining_priority;
686 * Number to mingle hashes for bloom-filter tests with.
691 * TTL with which we saw this request (or, if we initiated, TTL that
692 * we used for the request).
697 * Type of the content that this request is for.
699 enum GNUNET_BLOCK_Type type;
702 * Remove this request after transmission of the current response.
707 * GNUNET_YES if we should not forward this request to other peers.
712 * GNUNET_YES if we should not forward this request to other peers.
720 * Block that is ready for migration to other peers. Actual data is at the end of the block.
722 struct MigrationReadyBlock
726 * This is a doubly-linked list.
728 struct MigrationReadyBlock *next;
731 * This is a doubly-linked list.
733 struct MigrationReadyBlock *prev;
736 * Query for the block.
738 GNUNET_HashCode query;
741 * When does this block expire?
743 struct GNUNET_TIME_Absolute expiration;
746 * Peers we would consider forwarding this
747 * block to. Zero for empty entries.
749 GNUNET_PEER_Id target_list[MIGRATION_LIST_SIZE];
757 * Number of targets already used.
759 unsigned int used_targets;
764 enum GNUNET_BLOCK_Type type;
769 * Our connection to the datastore.
771 static struct GNUNET_DATASTORE_Handle *dsh;
776 static struct GNUNET_BLOCK_Context *block_ctx;
779 * Our block configuration.
781 static struct GNUNET_CONFIGURATION_Handle *block_cfg;
786 static const struct GNUNET_CONFIGURATION_Handle *cfg;
789 * Map of peer identifiers to "struct ConnectedPeer" (for that peer).
791 static struct GNUNET_CONTAINER_MultiHashMap *connected_peers;
794 * Map of peer identifiers to "struct PendingRequest" (for that peer).
796 static struct GNUNET_CONTAINER_MultiHashMap *peer_request_map;
799 * Map of query identifiers to "struct PendingRequest" (for that query).
801 static struct GNUNET_CONTAINER_MultiHashMap *query_request_map;
804 * Heap with the request that will expire next at the top. Contains
805 * pointers of type "struct PendingRequest*"; these will *also* be
806 * aliased from the "requests_by_peer" data structures and the
807 * "requests_by_query" table. Note that requests from our clients
808 * don't expire and are thus NOT in the "requests_by_expiration"
809 * (or the "requests_by_peer" tables).
811 static struct GNUNET_CONTAINER_Heap *requests_by_expiration_heap;
814 * Handle for reporting statistics.
816 static struct GNUNET_STATISTICS_Handle *stats;
819 * Linked list of clients we are currently processing requests for.
821 static struct ClientList *client_list;
824 * Pointer to handle to the core service (points to NULL until we've
827 static struct GNUNET_CORE_Handle *core;
830 * Head of linked list of blocks that can be migrated.
832 static struct MigrationReadyBlock *mig_head;
835 * Tail of linked list of blocks that can be migrated.
837 static struct MigrationReadyBlock *mig_tail;
840 * Request to datastore for migration (or NULL).
842 static struct GNUNET_DATASTORE_QueueEntry *mig_qe;
845 * Request to datastore for DHT PUTs (or NULL).
847 static struct GNUNET_DATASTORE_QueueEntry *dht_qe;
850 * Type we will request for the next DHT PUT round from the datastore.
852 static enum GNUNET_BLOCK_Type dht_put_type = GNUNET_BLOCK_TYPE_FS_KBLOCK;
855 * Where do we store trust information?
857 static char *trustDirectory;
860 * ID of task that collects blocks for migration.
862 static GNUNET_SCHEDULER_TaskIdentifier mig_task;
865 * ID of task that collects blocks for DHT PUTs.
867 static GNUNET_SCHEDULER_TaskIdentifier dht_task;
870 * What is the maximum frequency at which we are allowed to
871 * poll the datastore for migration content?
873 static struct GNUNET_TIME_Relative min_migration_delay;
876 * Handle for DHT operations.
878 static struct GNUNET_DHT_Handle *dht_handle;
881 * Size of the doubly-linked list of migration blocks.
883 static unsigned int mig_size;
886 * Are we allowed to migrate content to this peer.
888 static int active_migration;
891 * How many entires with zero anonymity do we currently estimate
892 * to have in the database?
894 static unsigned int zero_anonymity_count_estimate;
897 * Typical priorities we're seeing from other peers right now. Since
898 * most priorities will be zero, this value is the weighted average of
899 * non-zero priorities seen "recently". In order to ensure that new
900 * values do not dramatically change the ratio, values are first
901 * "capped" to a reasonable range (+N of the current value) and then
902 * averaged into the existing value by a ratio of 1:N. Hence
903 * receiving the largest possible priority can still only raise our
904 * "current_priorities" by at most 1.
906 static double current_priorities;
909 * Datastore 'GET' load tracking.
911 static struct GNUNET_LOAD_Value *datastore_get_load;
914 * Datastore 'PUT' load tracking.
916 static struct GNUNET_LOAD_Value *datastore_put_load;
919 * How long do requests typically stay in the routing table?
921 static struct GNUNET_LOAD_Value *rt_entry_lifetime;
924 * We've just now completed a datastore request. Update our
925 * datastore load calculations.
927 * @param start time when the datastore request was issued
930 update_datastore_delays (struct GNUNET_TIME_Absolute start)
932 struct GNUNET_TIME_Relative delay;
934 delay = GNUNET_TIME_absolute_get_duration (start);
935 GNUNET_LOAD_update (datastore_get_load,
941 * Get the filename under which we would store the GNUNET_HELLO_Message
942 * for the given host and protocol.
943 * @return filename of the form DIRECTORY/HOSTID
946 get_trust_filename (const struct GNUNET_PeerIdentity *id)
948 struct GNUNET_CRYPTO_HashAsciiEncoded fil;
951 GNUNET_CRYPTO_hash_to_enc (&id->hashPubKey, &fil);
952 GNUNET_asprintf (&fn, "%s%s%s", trustDirectory, DIR_SEPARATOR_STR, &fil);
959 * Transmit messages by copying it to the target buffer
960 * "buf". "buf" will be NULL and "size" zero if the socket was closed
961 * for writing in the meantime. In that case, do nothing
962 * (the disconnect or shutdown handler will take care of the rest).
963 * If we were able to transmit messages and there are still more
964 * pending, ask core again for further calls to this function.
966 * @param cls closure, pointer to the 'struct ConnectedPeer*'
967 * @param size number of bytes available in buf
968 * @param buf where the callee should write the message
969 * @return number of bytes written to buf
972 transmit_to_peer (void *cls,
973 size_t size, void *buf);
976 /* ******************* clean up functions ************************ */
979 * Delete the given migration block.
981 * @param mb block to delete
984 delete_migration_block (struct MigrationReadyBlock *mb)
986 GNUNET_CONTAINER_DLL_remove (mig_head,
989 GNUNET_PEER_decrement_rcs (mb->target_list,
990 MIGRATION_LIST_SIZE);
997 * Compare the distance of two peers to a key.
1000 * @param p1 first peer
1001 * @param p2 second peer
1002 * @return GNUNET_YES if P1 is closer to key than P2
1005 is_closer (const GNUNET_HashCode *key,
1006 const struct GNUNET_PeerIdentity *p1,
1007 const struct GNUNET_PeerIdentity *p2)
1009 return GNUNET_CRYPTO_hash_xorcmp (&p1->hashPubKey,
1016 * Consider migrating content to a given peer.
1018 * @param cls 'struct MigrationReadyBlock*' to select
1019 * targets for (or NULL for none)
1020 * @param key ID of the peer
1021 * @param value 'struct ConnectedPeer' of the peer
1022 * @return GNUNET_YES (always continue iteration)
1025 consider_migration (void *cls,
1026 const GNUNET_HashCode *key,
1029 struct MigrationReadyBlock *mb = cls;
1030 struct ConnectedPeer *cp = value;
1031 struct MigrationReadyBlock *pos;
1032 struct GNUNET_PeerIdentity cppid;
1033 struct GNUNET_PeerIdentity otherpid;
1034 struct GNUNET_PeerIdentity worstpid;
1039 /* consider 'cp' as a migration target for mb */
1040 if (GNUNET_TIME_absolute_get_remaining (cp->migration_blocked).rel_value > 0)
1041 return GNUNET_YES; /* peer has requested no migration! */
1044 GNUNET_PEER_resolve (cp->pid,
1046 repl = MIGRATION_LIST_SIZE;
1047 for (i=0;i<MIGRATION_LIST_SIZE;i++)
1049 if (mb->target_list[i] == 0)
1051 mb->target_list[i] = cp->pid;
1052 GNUNET_PEER_change_rc (mb->target_list[i], 1);
1053 repl = MIGRATION_LIST_SIZE;
1056 GNUNET_PEER_resolve (mb->target_list[i],
1058 if ( (repl == MIGRATION_LIST_SIZE) &&
1059 is_closer (&mb->query,
1064 worstpid = otherpid;
1066 else if ( (repl != MIGRATION_LIST_SIZE) &&
1067 (is_closer (&mb->query,
1072 worstpid = otherpid;
1075 if (repl != MIGRATION_LIST_SIZE)
1077 GNUNET_PEER_change_rc (mb->target_list[repl], -1);
1078 mb->target_list[repl] = cp->pid;
1079 GNUNET_PEER_change_rc (mb->target_list[repl], 1);
1083 /* consider scheduling transmission to cp for content migration */
1084 if (cp->cth != NULL)
1090 for (i=0;i<MIGRATION_LIST_SIZE;i++)
1092 if (cp->pid == pos->target_list[i])
1097 msize = GNUNET_MIN (msize,
1105 return GNUNET_YES; /* no content available */
1107 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1108 "Trying to migrate at least %u bytes to peer `%s'\n",
1112 if (cp->delayed_transmission_request_task != GNUNET_SCHEDULER_NO_TASK)
1114 GNUNET_SCHEDULER_cancel (cp->delayed_transmission_request_task);
1115 cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
1118 = GNUNET_CORE_notify_transmit_ready (core,
1119 0, GNUNET_TIME_UNIT_FOREVER_REL,
1120 (const struct GNUNET_PeerIdentity*) key,
1121 msize + sizeof (struct PutMessage),
1129 * Task that is run periodically to obtain blocks for content
1133 * @param tc scheduler context (also unused)
1136 gather_migration_blocks (void *cls,
1137 const struct GNUNET_SCHEDULER_TaskContext *tc);
1143 * Task that is run periodically to obtain blocks for DHT PUTs.
1145 * @param cls type of blocks to gather
1146 * @param tc scheduler context (unused)
1149 gather_dht_put_blocks (void *cls,
1150 const struct GNUNET_SCHEDULER_TaskContext *tc);
1154 * If the migration task is not currently running, consider
1155 * (re)scheduling it with the appropriate delay.
1158 consider_migration_gathering ()
1160 struct GNUNET_TIME_Relative delay;
1166 if (mig_task != GNUNET_SCHEDULER_NO_TASK)
1168 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
1170 delay = GNUNET_TIME_relative_divide (delay,
1171 MAX_MIGRATION_QUEUE);
1172 delay = GNUNET_TIME_relative_max (delay,
1173 min_migration_delay);
1174 mig_task = GNUNET_SCHEDULER_add_delayed (delay,
1175 &gather_migration_blocks,
1181 * If the DHT PUT gathering task is not currently running, consider
1182 * (re)scheduling it with the appropriate delay.
1185 consider_dht_put_gathering (void *cls)
1187 struct GNUNET_TIME_Relative delay;
1193 if (dht_task != GNUNET_SCHEDULER_NO_TASK)
1195 if (zero_anonymity_count_estimate > 0)
1197 delay = GNUNET_TIME_relative_divide (GNUNET_DHT_DEFAULT_REPUBLISH_FREQUENCY,
1198 zero_anonymity_count_estimate);
1199 delay = GNUNET_TIME_relative_min (delay,
1204 /* if we have NO zero-anonymity content yet, wait 5 minutes for some to
1205 (hopefully) appear */
1206 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5);
1208 dht_task = GNUNET_SCHEDULER_add_delayed (delay,
1209 &gather_dht_put_blocks,
1215 * Process content offered for migration.
1217 * @param cls closure
1218 * @param key key for the content
1219 * @param size number of bytes in data
1220 * @param data content stored
1221 * @param type type of the content
1222 * @param priority priority of the content
1223 * @param anonymity anonymity-level for the content
1224 * @param expiration expiration time for the content
1225 * @param uid unique identifier for the datum;
1226 * maybe 0 if no unique identifier is available
1229 process_migration_content (void *cls,
1230 const GNUNET_HashCode * key,
1233 enum GNUNET_BLOCK_Type type,
1236 struct GNUNET_TIME_Absolute
1237 expiration, uint64_t uid)
1239 struct MigrationReadyBlock *mb;
1244 if (mig_size < MAX_MIGRATION_QUEUE)
1245 consider_migration_gathering ();
1248 if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
1251 GNUNET_FS_handle_on_demand_block (key, size, data,
1252 type, priority, anonymity,
1254 &process_migration_content,
1257 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1262 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1263 "Retrieved block `%s' of type %u for migration\n",
1267 mb = GNUNET_malloc (sizeof (struct MigrationReadyBlock) + size);
1269 mb->expiration = expiration;
1272 memcpy (&mb[1], data, size);
1273 GNUNET_CONTAINER_DLL_insert_after (mig_head,
1278 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1279 &consider_migration,
1281 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1286 * Function called upon completion of the DHT PUT operation.
1289 dht_put_continuation (void *cls,
1290 const struct GNUNET_SCHEDULER_TaskContext *tc)
1292 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1297 * Store content in DHT.
1299 * @param cls closure
1300 * @param key key for the content
1301 * @param size number of bytes in data
1302 * @param data content stored
1303 * @param type type of the content
1304 * @param priority priority of the content
1305 * @param anonymity anonymity-level for the content
1306 * @param expiration expiration time for the content
1307 * @param uid unique identifier for the datum;
1308 * maybe 0 if no unique identifier is available
1311 process_dht_put_content (void *cls,
1312 const GNUNET_HashCode * key,
1315 enum GNUNET_BLOCK_Type type,
1318 struct GNUNET_TIME_Absolute
1319 expiration, uint64_t uid)
1321 static unsigned int counter;
1322 static GNUNET_HashCode last_vhash;
1323 static GNUNET_HashCode vhash;
1328 consider_dht_put_gathering (cls);
1331 /* slightly funky code to estimate the total number of values with zero
1332 anonymity from the maximum observed length of a monotonically increasing
1333 sequence of hashes over the contents */
1334 GNUNET_CRYPTO_hash (data, size, &vhash);
1335 if (GNUNET_CRYPTO_hash_cmp (&vhash, &last_vhash) <= 0)
1337 if (zero_anonymity_count_estimate > 0)
1338 zero_anonymity_count_estimate /= 2;
1344 if (zero_anonymity_count_estimate < (1 << counter))
1345 zero_anonymity_count_estimate = (1 << counter);
1347 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1348 "Retrieved block `%s' of type %u for DHT PUT\n",
1352 GNUNET_DHT_put (dht_handle,
1354 DEFAULT_PUT_REPLICATION,
1360 GNUNET_TIME_UNIT_FOREVER_REL,
1361 &dht_put_continuation,
1367 * Task that is run periodically to obtain blocks for content
1371 * @param tc scheduler context (also unused)
1374 gather_migration_blocks (void *cls,
1375 const struct GNUNET_SCHEDULER_TaskContext *tc)
1377 mig_task = GNUNET_SCHEDULER_NO_TASK;
1380 mig_qe = GNUNET_DATASTORE_get_random (dsh, 0, UINT_MAX,
1381 GNUNET_TIME_UNIT_FOREVER_REL,
1382 &process_migration_content, NULL);
1383 GNUNET_assert (mig_qe != NULL);
1389 * Task that is run periodically to obtain blocks for DHT PUTs.
1391 * @param cls type of blocks to gather
1392 * @param tc scheduler context (unused)
1395 gather_dht_put_blocks (void *cls,
1396 const struct GNUNET_SCHEDULER_TaskContext *tc)
1398 dht_task = GNUNET_SCHEDULER_NO_TASK;
1401 if (dht_put_type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
1402 dht_put_type = GNUNET_BLOCK_TYPE_FS_KBLOCK;
1403 dht_qe = GNUNET_DATASTORE_get_zero_anonymity (dsh, 0, UINT_MAX,
1404 GNUNET_TIME_UNIT_FOREVER_REL,
1406 &process_dht_put_content, NULL);
1407 GNUNET_assert (dht_qe != NULL);
1413 * We're done with a particular message list entry.
1414 * Free all associated resources.
1416 * @param pml entry to destroy
1419 destroy_pending_message_list_entry (struct PendingMessageList *pml)
1421 GNUNET_CONTAINER_DLL_remove (pml->req->pending_head,
1422 pml->req->pending_tail,
1424 GNUNET_CONTAINER_DLL_remove (pml->target->pending_messages_head,
1425 pml->target->pending_messages_tail,
1427 pml->target->pending_requests--;
1428 GNUNET_free (pml->pm);
1434 * Destroy the given pending message (and call the respective
1437 * @param pm message to destroy
1438 * @param tpid id of peer that the message was delivered to, or 0 for none
1441 destroy_pending_message (struct PendingMessage *pm,
1442 GNUNET_PEER_Id tpid)
1444 struct PendingMessageList *pml = pm->pml;
1445 TransmissionContinuation cont;
1449 cont_cls = pm->cont_cls;
1452 GNUNET_assert (pml->pm == pm);
1453 GNUNET_assert ( (tpid == 0) || (tpid == pml->target->pid) );
1454 destroy_pending_message_list_entry (pml);
1461 cont (cont_cls, tpid);
1466 * We're done processing a particular request.
1467 * Free all associated resources.
1469 * @param pr request to destroy
1472 destroy_pending_request (struct PendingRequest *pr)
1474 struct GNUNET_PeerIdentity pid;
1477 if (pr->hnode != NULL)
1479 GNUNET_CONTAINER_heap_remove_node (requests_by_expiration_heap,
1483 if (NULL == pr->client_request_list)
1485 GNUNET_STATISTICS_update (stats,
1486 gettext_noop ("# P2P searches active"),
1492 GNUNET_STATISTICS_update (stats,
1493 gettext_noop ("# client searches active"),
1498 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
1502 GNUNET_LOAD_update (rt_entry_lifetime,
1503 GNUNET_TIME_absolute_get_duration (pr->start_time).rel_value);
1507 GNUNET_DATASTORE_cancel (pr->qe);
1510 if (pr->dht_get != NULL)
1512 GNUNET_DHT_get_stop (pr->dht_get);
1515 if (pr->client_request_list != NULL)
1517 GNUNET_CONTAINER_DLL_remove (pr->client_request_list->client_list->rl_head,
1518 pr->client_request_list->client_list->rl_tail,
1519 pr->client_request_list);
1520 GNUNET_free (pr->client_request_list);
1521 pr->client_request_list = NULL;
1525 GNUNET_PEER_resolve (pr->cp->pid,
1527 (void) GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
1534 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
1537 if (pr->pirc != NULL)
1539 GNUNET_CORE_peer_change_preference_cancel (pr->pirc->irc);
1540 pr->pirc->irc = NULL;
1543 if (pr->replies_seen != NULL)
1545 GNUNET_free (pr->replies_seen);
1546 pr->replies_seen = NULL;
1548 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
1550 GNUNET_SCHEDULER_cancel (pr->task);
1551 pr->task = GNUNET_SCHEDULER_NO_TASK;
1553 while (NULL != pr->pending_head)
1554 destroy_pending_message_list_entry (pr->pending_head);
1555 GNUNET_PEER_change_rc (pr->target_pid, -1);
1556 if (pr->used_targets != NULL)
1558 for (i=0;i<pr->used_targets_off;i++)
1559 GNUNET_PEER_change_rc (pr->used_targets[i].pid, -1);
1560 GNUNET_free (pr->used_targets);
1561 pr->used_targets_off = 0;
1562 pr->used_targets_size = 0;
1563 pr->used_targets = NULL;
1570 * Find latency information in 'atsi'.
1572 * @param atsi performance data
1573 * @return connection latency
1575 static struct GNUNET_TIME_Relative
1576 get_latency (const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1578 /* FIXME: extract latency data from 'atsi' */
1579 return GNUNET_TIME_UNIT_SECONDS;
1584 * Method called whenever a given peer connects.
1586 * @param cls closure, not used
1587 * @param peer peer identity this notification is about
1588 * @param atsi performance information
1591 peer_connect_handler (void *cls,
1593 GNUNET_PeerIdentity * peer,
1594 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1596 struct ConnectedPeer *cp;
1597 struct MigrationReadyBlock *pos;
1600 struct GNUNET_TIME_Relative latency;
1602 latency = get_latency (atsi);
1603 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1610 cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
1611 cp->transmission_delay = GNUNET_LOAD_value_init (latency);
1612 cp->pid = GNUNET_PEER_intern (peer);
1614 fn = get_trust_filename (peer);
1615 if ((GNUNET_DISK_file_test (fn) == GNUNET_YES) &&
1616 (sizeof (trust) == GNUNET_DISK_fn_read (fn, &trust, sizeof (trust))))
1617 cp->disk_trust = cp->trust = ntohl (trust);
1620 GNUNET_break (GNUNET_OK ==
1621 GNUNET_CONTAINER_multihashmap_put (connected_peers,
1624 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1629 (void) consider_migration (pos, &peer->hashPubKey, cp);
1636 * Method called whenever a given peer has a status change.
1638 * @param cls closure
1639 * @param peer peer identity this notification is about
1640 * @param bandwidth_in available amount of inbound bandwidth
1641 * @param bandwidth_out available amount of outbound bandwidth
1642 * @param timeout absolute time when this peer will time out
1643 * unless we see some further activity from it
1644 * @param atsi status information
1647 peer_status_handler (void *cls,
1649 GNUNET_PeerIdentity * peer,
1650 struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
1651 struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
1652 struct GNUNET_TIME_Absolute timeout,
1653 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1655 struct ConnectedPeer *cp;
1656 struct GNUNET_TIME_Relative latency;
1658 latency = get_latency (atsi);
1659 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1666 GNUNET_LOAD_value_set_decline (cp->transmission_delay,
1673 * Increase the host credit by a value.
1675 * @param host which peer to change the trust value on
1676 * @param value is the int value by which the
1677 * host credit is to be increased or decreased
1678 * @returns the actual change in trust (positive or negative)
1681 change_host_trust (struct ConnectedPeer *host, int value)
1685 GNUNET_assert (host != NULL);
1688 if (host->trust + value < host->trust)
1690 value = UINT32_MAX - host->trust;
1691 host->trust = UINT32_MAX;
1694 host->trust += value;
1698 if (host->trust < -value)
1700 value = -host->trust;
1704 host->trust += value;
1711 * Write host-trust information to a file - flush the buffer entry!
1714 flush_trust (void *cls,
1715 const GNUNET_HashCode *key,
1718 struct ConnectedPeer *host = value;
1721 struct GNUNET_PeerIdentity pid;
1723 if (host->trust == host->disk_trust)
1724 return GNUNET_OK; /* unchanged */
1725 GNUNET_PEER_resolve (host->pid,
1727 fn = get_trust_filename (&pid);
1728 if (host->trust == 0)
1730 if ((0 != UNLINK (fn)) && (errno != ENOENT))
1731 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
1732 GNUNET_ERROR_TYPE_BULK, "unlink", fn);
1736 trust = htonl (host->trust);
1737 if (sizeof(uint32_t) == GNUNET_DISK_fn_write (fn, &trust,
1739 GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE
1740 | GNUNET_DISK_PERM_GROUP_READ | GNUNET_DISK_PERM_OTHER_READ))
1741 host->disk_trust = host->trust;
1748 * Call this method periodically to scan data/hosts for new hosts.
1751 cron_flush_trust (void *cls,
1752 const struct GNUNET_SCHEDULER_TaskContext *tc)
1755 if (NULL == connected_peers)
1757 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1762 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1764 GNUNET_SCHEDULER_add_delayed (TRUST_FLUSH_FREQ, &cron_flush_trust, NULL);
1769 * Free (each) request made by the peer.
1771 * @param cls closure, points to peer that the request belongs to
1772 * @param key current key code
1773 * @param value value in the hash map
1774 * @return GNUNET_YES (we should continue to iterate)
1777 destroy_request (void *cls,
1778 const GNUNET_HashCode * key,
1781 const struct GNUNET_PeerIdentity * peer = cls;
1782 struct PendingRequest *pr = value;
1784 GNUNET_break (GNUNET_YES ==
1785 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
1788 destroy_pending_request (pr);
1794 * Method called whenever a peer disconnects.
1796 * @param cls closure, not used
1797 * @param peer peer identity this notification is about
1800 peer_disconnect_handler (void *cls,
1802 GNUNET_PeerIdentity * peer)
1804 struct ConnectedPeer *cp;
1805 struct PendingMessage *pm;
1807 struct MigrationReadyBlock *pos;
1808 struct MigrationReadyBlock *next;
1810 GNUNET_CONTAINER_multihashmap_get_multiple (peer_request_map,
1814 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1818 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1820 if (NULL != cp->last_client_replies[i])
1822 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1823 cp->last_client_replies[i] = NULL;
1826 GNUNET_break (GNUNET_YES ==
1827 GNUNET_CONTAINER_multihashmap_remove (connected_peers,
1830 if (cp->irc != NULL)
1832 GNUNET_CORE_peer_change_preference_cancel (cp->irc);
1834 cp->pr->pirc = NULL;
1838 /* remove this peer from migration considerations; schedule
1841 while (NULL != (pos = next))
1844 for (i=0;i<MIGRATION_LIST_SIZE;i++)
1846 if (pos->target_list[i] == cp->pid)
1848 GNUNET_PEER_change_rc (pos->target_list[i], -1);
1849 pos->target_list[i] = 0;
1852 if (pos->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers))
1854 delete_migration_block (pos);
1855 consider_migration_gathering ();
1858 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1859 &consider_migration,
1862 GNUNET_PEER_change_rc (cp->pid, -1);
1863 GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
1864 if (NULL != cp->cth)
1866 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
1869 if (cp->delayed_transmission_request_task != GNUNET_SCHEDULER_NO_TASK)
1871 GNUNET_SCHEDULER_cancel (cp->delayed_transmission_request_task);
1872 cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
1874 while (NULL != (pm = cp->pending_messages_head))
1875 destroy_pending_message (pm, 0 /* delivery failed */);
1876 GNUNET_LOAD_value_free (cp->transmission_delay);
1877 GNUNET_break (0 == cp->pending_requests);
1883 * Iterator over hash map entries that removes all occurences
1884 * of the given 'client' from the 'last_client_replies' of the
1885 * given connected peer.
1887 * @param cls closure, the 'struct GNUNET_SERVER_Client*' to remove
1888 * @param key current key code (unused)
1889 * @param value value in the hash map (the 'struct ConnectedPeer*' to change)
1890 * @return GNUNET_YES (we should continue to iterate)
1893 remove_client_from_last_client_replies (void *cls,
1894 const GNUNET_HashCode * key,
1897 struct GNUNET_SERVER_Client *client = cls;
1898 struct ConnectedPeer *cp = value;
1901 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1903 if (cp->last_client_replies[i] == client)
1905 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1906 cp->last_client_replies[i] = NULL;
1914 * A client disconnected. Remove all of its pending queries.
1916 * @param cls closure, NULL
1917 * @param client identification of the client
1920 handle_client_disconnect (void *cls,
1921 struct GNUNET_SERVER_Client
1924 struct ClientList *pos;
1925 struct ClientList *prev;
1926 struct ClientRequestList *rcl;
1927 struct ClientResponseMessage *creply;
1933 while ( (NULL != pos) &&
1934 (pos->client != client) )
1940 return; /* no requests pending for this client */
1941 while (NULL != (rcl = pos->rl_head))
1943 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1944 "Destroying pending request `%s' on disconnect\n",
1945 GNUNET_h2s (&rcl->req->query));
1946 destroy_pending_request (rcl->req);
1949 client_list = pos->next;
1951 prev->next = pos->next;
1952 if (pos->th != NULL)
1954 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
1957 while (NULL != (creply = pos->res_head))
1959 GNUNET_CONTAINER_DLL_remove (pos->res_head,
1962 GNUNET_free (creply);
1964 GNUNET_SERVER_client_drop (pos->client);
1966 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1967 &remove_client_from_last_client_replies,
1973 * Iterator to free peer entries.
1975 * @param cls closure, unused
1976 * @param key current key code
1977 * @param value value in the hash map (peer entry)
1978 * @return GNUNET_YES (we should continue to iterate)
1981 clean_peer (void *cls,
1982 const GNUNET_HashCode * key,
1985 peer_disconnect_handler (NULL, (const struct GNUNET_PeerIdentity*) key);
1991 * Task run during shutdown.
1997 shutdown_task (void *cls,
1998 const struct GNUNET_SCHEDULER_TaskContext *tc)
2002 GNUNET_DATASTORE_cancel (mig_qe);
2007 GNUNET_DATASTORE_cancel (dht_qe);
2010 if (GNUNET_SCHEDULER_NO_TASK != mig_task)
2012 GNUNET_SCHEDULER_cancel (mig_task);
2013 mig_task = GNUNET_SCHEDULER_NO_TASK;
2015 if (GNUNET_SCHEDULER_NO_TASK != dht_task)
2017 GNUNET_SCHEDULER_cancel (dht_task);
2018 dht_task = GNUNET_SCHEDULER_NO_TASK;
2020 while (client_list != NULL)
2021 handle_client_disconnect (NULL,
2022 client_list->client);
2023 cron_flush_trust (NULL, NULL);
2024 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
2027 GNUNET_break (0 == GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap));
2028 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
2029 requests_by_expiration_heap = 0;
2030 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
2031 connected_peers = NULL;
2032 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (query_request_map));
2033 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
2034 query_request_map = NULL;
2035 GNUNET_LOAD_value_free (rt_entry_lifetime);
2036 rt_entry_lifetime = NULL;
2037 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (peer_request_map));
2038 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
2039 peer_request_map = NULL;
2040 GNUNET_assert (NULL != core);
2041 GNUNET_CORE_disconnect (core);
2045 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
2050 GNUNET_DATASTORE_disconnect (dsh,
2054 while (mig_head != NULL)
2055 delete_migration_block (mig_head);
2056 GNUNET_assert (0 == mig_size);
2057 GNUNET_DHT_disconnect (dht_handle);
2059 GNUNET_LOAD_value_free (datastore_get_load);
2060 datastore_get_load = NULL;
2061 GNUNET_LOAD_value_free (datastore_put_load);
2062 datastore_put_load = NULL;
2063 GNUNET_BLOCK_context_destroy (block_ctx);
2065 GNUNET_CONFIGURATION_destroy (block_cfg);
2068 GNUNET_free_non_null (trustDirectory);
2069 trustDirectory = NULL;
2073 /* ******************* Utility functions ******************** */
2077 * We've had to delay a request for transmission to core, but now
2078 * we should be ready. Run it.
2080 * @param cls the 'struct ConnectedPeer' for which a request was delayed
2081 * @param tc task context (unused)
2084 delayed_transmission_request (void *cls,
2085 const struct GNUNET_SCHEDULER_TaskContext *tc)
2087 struct ConnectedPeer *cp = cls;
2088 struct GNUNET_PeerIdentity pid;
2089 struct PendingMessage *pm;
2091 pm = cp->pending_messages_head;
2092 cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
2093 GNUNET_assert (cp->cth == NULL);
2096 GNUNET_PEER_resolve (cp->pid,
2098 cp->last_transmission_request_start = GNUNET_TIME_absolute_get ();
2099 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
2101 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
2110 * Transmit messages by copying it to the target buffer
2111 * "buf". "buf" will be NULL and "size" zero if the socket was closed
2112 * for writing in the meantime. In that case, do nothing
2113 * (the disconnect or shutdown handler will take care of the rest).
2114 * If we were able to transmit messages and there are still more
2115 * pending, ask core again for further calls to this function.
2117 * @param cls closure, pointer to the 'struct ConnectedPeer*'
2118 * @param size number of bytes available in buf
2119 * @param buf where the callee should write the message
2120 * @return number of bytes written to buf
2123 transmit_to_peer (void *cls,
2124 size_t size, void *buf)
2126 struct ConnectedPeer *cp = cls;
2128 struct PendingMessage *pm;
2129 struct PendingMessage *next_pm;
2130 struct GNUNET_TIME_Absolute now;
2131 struct GNUNET_TIME_Relative min_delay;
2132 struct MigrationReadyBlock *mb;
2133 struct MigrationReadyBlock *next;
2134 struct PutMessage migm;
2137 struct GNUNET_PeerIdentity pid;
2143 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2144 "Dropping message, core too busy.\n");
2146 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2147 "Dropping message, core too busy.\n");
2148 GNUNET_LOAD_update (cp->transmission_delay,
2151 if (NULL != (pm = cp->pending_messages_head))
2153 GNUNET_CONTAINER_DLL_remove (cp->pending_messages_head,
2154 cp->pending_messages_tail,
2156 cp->pending_requests--;
2157 destroy_pending_message (pm, 0);
2159 if (NULL != (pm = cp->pending_messages_head))
2161 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == cp->delayed_transmission_request_task);
2162 min_delay = GNUNET_TIME_absolute_get_remaining (pm->delay_until);
2163 cp->delayed_transmission_request_task
2164 = GNUNET_SCHEDULER_add_delayed (min_delay,
2165 &delayed_transmission_request,
2170 GNUNET_LOAD_update (cp->transmission_delay,
2171 GNUNET_TIME_absolute_get_duration (cp->last_transmission_request_start).rel_value);
2172 now = GNUNET_TIME_absolute_get ();
2174 min_delay = GNUNET_TIME_UNIT_FOREVER_REL;
2175 next_pm = cp->pending_messages_head;
2176 while ( (NULL != (pm = next_pm) ) &&
2177 (pm->msize <= size) )
2180 if (pm->delay_until.abs_value > now.abs_value)
2182 min_delay = GNUNET_TIME_relative_min (min_delay,
2183 GNUNET_TIME_absolute_get_remaining (pm->delay_until));
2186 memcpy (&cbuf[msize], &pm[1], pm->msize);
2189 if (NULL == pm->pml)
2191 GNUNET_CONTAINER_DLL_remove (cp->pending_messages_head,
2192 cp->pending_messages_tail,
2194 cp->pending_requests--;
2196 destroy_pending_message (pm, cp->pid);
2199 min_delay = GNUNET_TIME_UNIT_ZERO;
2200 if (NULL != cp->pending_messages_head)
2202 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == cp->delayed_transmission_request_task);
2203 cp->delayed_transmission_request_task
2204 = GNUNET_SCHEDULER_add_delayed (min_delay,
2205 &delayed_transmission_request,
2210 GNUNET_PEER_resolve (cp->pid,
2213 while (NULL != (mb = next))
2216 for (i=0;i<MIGRATION_LIST_SIZE;i++)
2218 if ( (cp->pid == mb->target_list[i]) &&
2219 (mb->size + sizeof (migm) <= size) )
2221 GNUNET_PEER_change_rc (mb->target_list[i], -1);
2222 mb->target_list[i] = 0;
2224 memset (&migm, 0, sizeof (migm));
2225 migm.header.size = htons (sizeof (migm) + mb->size);
2226 migm.header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2227 migm.type = htonl (mb->type);
2228 migm.expiration = GNUNET_TIME_absolute_hton (mb->expiration);
2229 memcpy (&cbuf[msize], &migm, sizeof (migm));
2230 msize += sizeof (migm);
2231 size -= sizeof (migm);
2232 memcpy (&cbuf[msize], &mb[1], mb->size);
2236 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2237 "Pushing migration block `%s' (%u bytes) to `%s'\n",
2238 GNUNET_h2s (&mb->query),
2239 (unsigned int) mb->size,
2247 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2248 "Migration block `%s' (%u bytes) is not on migration list for peer `%s'\n",
2249 GNUNET_h2s (&mb->query),
2250 (unsigned int) mb->size,
2255 if ( (mb->used_targets >= MIGRATION_TARGET_COUNT) ||
2256 (mb->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers)) )
2258 delete_migration_block (mb);
2259 consider_migration_gathering ();
2262 consider_migration (NULL,
2267 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2268 "Transmitting %u bytes to peer with PID %u\n",
2269 (unsigned int) msize,
2270 (unsigned int) cp->pid);
2277 * Add a message to the set of pending messages for the given peer.
2279 * @param cp peer to send message to
2280 * @param pm message to queue
2281 * @param pr request on which behalf this message is being queued
2284 add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
2285 struct PendingMessage *pm,
2286 struct PendingRequest *pr)
2288 struct PendingMessage *pos;
2289 struct PendingMessageList *pml;
2290 struct GNUNET_PeerIdentity pid;
2292 GNUNET_assert (pm->next == NULL);
2293 GNUNET_assert (pm->pml == NULL);
2296 pml = GNUNET_malloc (sizeof (struct PendingMessageList));
2301 GNUNET_CONTAINER_DLL_insert (pr->pending_head,
2305 pos = cp->pending_messages_head;
2306 while ( (pos != NULL) &&
2307 (pm->priority < pos->priority) )
2309 GNUNET_CONTAINER_DLL_insert_after (cp->pending_messages_head,
2310 cp->pending_messages_tail,
2313 cp->pending_requests++;
2314 if (cp->pending_requests > MAX_QUEUE_PER_PEER)
2316 GNUNET_STATISTICS_update (stats,
2317 gettext_noop ("# P2P searches discarded (queue length bound)"),
2320 destroy_pending_message (cp->pending_messages_tail, 0);
2322 GNUNET_PEER_resolve (cp->pid, &pid);
2323 if (NULL != cp->cth)
2325 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
2328 if (cp->delayed_transmission_request_task != GNUNET_SCHEDULER_NO_TASK)
2330 GNUNET_SCHEDULER_cancel (cp->delayed_transmission_request_task);
2331 cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
2333 /* need to schedule transmission */
2334 cp->last_transmission_request_start = GNUNET_TIME_absolute_get ();
2335 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
2336 cp->pending_messages_head->priority,
2339 cp->pending_messages_head->msize,
2342 if (cp->cth == NULL)
2345 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2346 "Failed to schedule transmission with core!\n");
2348 GNUNET_STATISTICS_update (stats,
2349 gettext_noop ("# CORE transmission failures"),
2357 * Test if the DATABASE (GET) load on this peer is too high
2358 * to even consider processing the query at
2361 * @return GNUNET_YES if the load is too high to do anything (load high)
2362 * GNUNET_NO to process normally (load normal)
2363 * GNUNET_SYSERR to process for free (load low)
2366 test_get_load_too_high (uint32_t priority)
2370 ld = GNUNET_LOAD_get_load (datastore_get_load);
2372 return GNUNET_SYSERR;
2382 * Test if the DATABASE (PUT) load on this peer is too high
2383 * to even consider processing the query at
2386 * @return GNUNET_YES if the load is too high to do anything (load high)
2387 * GNUNET_NO to process normally (load normal or low)
2390 test_put_load_too_high (uint32_t priority)
2394 if (GNUNET_LOAD_get_average (datastore_put_load) < 50)
2395 return GNUNET_NO; /* very fast */
2396 ld = GNUNET_LOAD_get_load (datastore_put_load);
2397 if (ld < 2.0 * (1 + priority))
2399 GNUNET_STATISTICS_update (stats,
2400 gettext_noop ("# storage requests dropped due to high load"),
2407 /* ******************* Pending Request Refresh Task ******************** */
2412 * We use a random delay to make the timing of requests less
2413 * predictable. This function returns such a random delay. We add a base
2414 * delay of MAX_CORK_DELAY (1s).
2416 * FIXME: make schedule dependent on the specifics of the request?
2417 * Or bandwidth and number of connected peers and load?
2419 * @return random delay to use for some request, between 1s and 1000+TTL_DECREMENT ms
2421 static struct GNUNET_TIME_Relative
2422 get_processing_delay ()
2425 GNUNET_TIME_relative_add (GNUNET_CONSTANTS_MAX_CORK_DELAY,
2426 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
2427 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2433 * We're processing a GET request from another peer and have decided
2434 * to forward it to other peers. This function is called periodically
2435 * and should forward the request to other peers until we have all
2436 * possible replies. If we have transmitted the *only* reply to
2437 * the initiator we should destroy the pending request. If we have
2438 * many replies in the queue to the initiator, we should delay sending
2439 * out more queries until the reply queue has shrunk some.
2441 * @param cls our "struct ProcessGetContext *"
2445 forward_request_task (void *cls,
2446 const struct GNUNET_SCHEDULER_TaskContext *tc);
2450 * Function called after we either failed or succeeded
2451 * at transmitting a query to a peer.
2453 * @param cls the requests "struct PendingRequest*"
2454 * @param tpid ID of receiving peer, 0 on transmission error
2457 transmit_query_continuation (void *cls,
2458 GNUNET_PEER_Id tpid)
2460 struct PendingRequest *pr = cls;
2463 GNUNET_STATISTICS_update (stats,
2464 gettext_noop ("# queries scheduled for forwarding"),
2470 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2471 "Transmission of request failed, will try again later.\n");
2473 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2474 pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2475 &forward_request_task,
2480 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2481 "Transmitted query `%s'\n",
2482 GNUNET_h2s (&pr->query));
2484 GNUNET_STATISTICS_update (stats,
2485 gettext_noop ("# queries forwarded"),
2488 for (i=0;i<pr->used_targets_off;i++)
2489 if (pr->used_targets[i].pid == tpid)
2490 break; /* found match! */
2491 if (i == pr->used_targets_off)
2493 /* need to create new entry */
2494 if (pr->used_targets_off == pr->used_targets_size)
2495 GNUNET_array_grow (pr->used_targets,
2496 pr->used_targets_size,
2497 pr->used_targets_size * 2 + 2);
2498 GNUNET_PEER_change_rc (tpid, 1);
2499 pr->used_targets[pr->used_targets_off].pid = tpid;
2500 pr->used_targets[pr->used_targets_off].num_requests = 0;
2501 i = pr->used_targets_off++;
2503 pr->used_targets[i].last_request_time = GNUNET_TIME_absolute_get ();
2504 pr->used_targets[i].num_requests++;
2505 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2506 pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2507 &forward_request_task,
2513 * How many bytes should a bloomfilter be if we have already seen
2514 * entry_count responses? Note that BLOOMFILTER_K gives us the number
2515 * of bits set per entry. Furthermore, we should not re-size the
2516 * filter too often (to keep it cheap).
2518 * Since other peers will also add entries but not resize the filter,
2519 * we should generally pick a slightly larger size than what the
2520 * strict math would suggest.
2522 * @return must be a power of two and smaller or equal to 2^15.
2525 compute_bloomfilter_size (unsigned int entry_count)
2528 unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
2529 uint16_t max = 1 << 15;
2531 if (entry_count > max)
2534 while ((size < max) && (size < ideal))
2543 * Recalculate our bloom filter for filtering replies. This function
2544 * will create a new bloom filter from scratch, so it should only be
2545 * called if we have no bloomfilter at all (and hence can create a
2546 * fresh one of minimal size without problems) OR if our peer is the
2547 * initiator (in which case we may resize to larger than mimimum size).
2549 * @param pr request for which the BF is to be recomputed
2552 refresh_bloomfilter (struct PendingRequest *pr)
2556 GNUNET_HashCode mhash;
2558 nsize = compute_bloomfilter_size (pr->replies_seen_off);
2559 if (nsize == pr->bf_size)
2560 return; /* size not changed */
2562 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
2563 pr->bf_size = nsize;
2564 pr->mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
2565 pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
2568 for (i=0;i<pr->replies_seen_off;i++)
2570 GNUNET_BLOCK_mingle_hash (&pr->replies_seen[i],
2573 GNUNET_CONTAINER_bloomfilter_add (pr->bf, &mhash);
2579 * Function called after we've tried to reserve a certain amount of
2580 * bandwidth for a reply. Check if we succeeded and if so send our
2583 * @param cls the requests "struct PendingRequest*"
2584 * @param peer identifies the peer
2585 * @param bpm_out set to the current bandwidth limit (sending) for this peer
2586 * @param amount set to the amount that was actually reserved or unreserved
2587 * @param preference current traffic preference for the given peer
2590 target_reservation_cb (void *cls,
2592 GNUNET_PeerIdentity * peer,
2593 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
2595 uint64_t preference)
2597 struct PendingRequest *pr = cls;
2598 struct ConnectedPeer *cp;
2599 struct PendingMessage *pm;
2600 struct GetMessage *gm;
2601 GNUNET_HashCode *ext;
2609 /* (3) transmit, update ttl/priority */
2610 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2614 /* Peer must have just left */
2616 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2617 "Selected peer disconnected!\n");
2619 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2620 pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2621 &forward_request_task,
2629 /* error in communication with core, try again later */
2630 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2631 pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2632 &forward_request_task,
2636 no_route = GNUNET_NO;
2642 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2643 "Failed to reserve bandwidth for reply (got %d/%u bytes only)!\n",
2647 GNUNET_STATISTICS_update (stats,
2648 gettext_noop ("# reply bandwidth reservation requests failed"),
2651 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2652 pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2653 &forward_request_task,
2655 return; /* this target round failed */
2657 no_route = GNUNET_YES;
2660 GNUNET_STATISTICS_update (stats,
2661 gettext_noop ("# queries scheduled for forwarding"),
2664 for (i=0;i<pr->used_targets_off;i++)
2665 if (pr->used_targets[i].pid == cp->pid)
2667 GNUNET_STATISTICS_update (stats,
2668 gettext_noop ("# queries retransmitted to same target"),
2674 /* build message and insert message into priority queue */
2676 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2677 "Forwarding request `%s' to `%4s'!\n",
2678 GNUNET_h2s (&pr->query),
2683 if (GNUNET_YES == no_route)
2685 bm |= GET_MESSAGE_BIT_RETURN_TO;
2688 if (pr->namespace != NULL)
2690 bm |= GET_MESSAGE_BIT_SKS_NAMESPACE;
2693 if (pr->target_pid != 0)
2695 bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
2698 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
2699 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
2700 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
2702 gm = (struct GetMessage*) &pm[1];
2703 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
2704 gm->header.size = htons (msize);
2705 gm->type = htonl (pr->type);
2706 pr->remaining_priority /= 2;
2707 gm->priority = htonl (pr->remaining_priority);
2708 gm->ttl = htonl (pr->ttl);
2709 gm->filter_mutator = htonl(pr->mingle);
2710 gm->hash_bitmap = htonl (bm);
2711 gm->query = pr->query;
2712 ext = (GNUNET_HashCode*) &gm[1];
2714 if (GNUNET_YES == no_route)
2715 GNUNET_PEER_resolve (pr->cp->pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
2716 if (pr->namespace != NULL)
2717 memcpy (&ext[k++], pr->namespace, sizeof (GNUNET_HashCode));
2718 if (pr->target_pid != 0)
2719 GNUNET_PEER_resolve (pr->target_pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
2720 bfdata = (char *) &ext[k];
2722 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
2725 pm->cont = &transmit_query_continuation;
2727 cp->last_request_times[(cp->last_request_times_off++) % MAX_QUEUE_PER_PEER] = GNUNET_TIME_absolute_get ();
2728 add_to_pending_messages_for_peer (cp, pm, pr);
2733 * Closure used for "target_peer_select_cb".
2735 struct PeerSelectionContext
2738 * The request for which we are selecting
2741 struct PendingRequest *pr;
2744 * Current "prime" target.
2746 struct GNUNET_PeerIdentity target;
2749 * How much do we like this target?
2751 double target_score;
2754 * Does it make sense to we re-try quickly again?
2762 * Function called for each connected peer to determine
2763 * which one(s) would make good targets for forwarding.
2765 * @param cls closure (struct PeerSelectionContext)
2766 * @param key current key code (peer identity)
2767 * @param value value in the hash map (struct ConnectedPeer)
2768 * @return GNUNET_YES if we should continue to
2773 target_peer_select_cb (void *cls,
2774 const GNUNET_HashCode * key,
2777 struct PeerSelectionContext *psc = cls;
2778 struct ConnectedPeer *cp = value;
2779 struct PendingRequest *pr = psc->pr;
2780 struct GNUNET_TIME_Relative delay;
2785 /* 1) check that this peer is not the initiator */
2789 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2790 "Skipping initiator in forwarding selection\n");
2792 return GNUNET_YES; /* skip */
2794 if (cp->irc != NULL)
2796 psc->fast_retry = GNUNET_YES;
2797 return GNUNET_YES; /* skip: already querying core about this peer for other reasons */
2800 /* 2) check if we have already (recently) forwarded to this peer */
2801 /* 2a) this particular request */
2803 for (i=0;i<pr->used_targets_off;i++)
2804 if (pr->used_targets[i].pid == cp->pid)
2806 pc = pr->used_targets[i].num_requests;
2807 GNUNET_assert (pc > 0);
2808 /* FIXME: make re-enabling a peer independent of how often
2809 this function is called??? */
2810 if (0 != GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2811 RETRY_PROBABILITY_INV * pc))
2814 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2815 "NOT re-trying query that was previously transmitted %u times\n",
2818 return GNUNET_YES; /* skip */
2825 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2826 "Re-trying query that was previously transmitted %u times to this peer\n",
2830 /* 2b) many other requests to this peer */
2831 delay = GNUNET_TIME_absolute_get_duration (cp->last_request_times[cp->last_request_times_off % MAX_QUEUE_PER_PEER]);
2832 if (delay.rel_value <= cp->avg_delay.rel_value)
2835 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2836 "NOT sending query since we send %u others to this peer in the last %llums\n",
2838 cp->avg_delay.rel_value);
2840 return GNUNET_YES; /* skip */
2843 /* 3) calculate how much we'd like to forward to this peer,
2844 starting with a random value that is strong enough
2845 to at least give any peer a chance sometimes
2846 (compared to the other factors that come later) */
2847 /* 3a) count successful (recent) routes from cp for same source */
2850 score = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2851 P2P_SUCCESS_LIST_SIZE);
2852 for (i=0;i<P2P_SUCCESS_LIST_SIZE;i++)
2853 if (cp->last_p2p_replies[i] == pr->cp->pid)
2854 score += 1.0; /* likely successful based on hot path */
2858 score = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2859 CS2P_SUCCESS_LIST_SIZE);
2860 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
2861 if (cp->last_client_replies[i] == pr->client_request_list->client_list->client)
2862 score += 1.0; /* likely successful based on hot path */
2864 /* 3b) include latency */
2865 if (cp->avg_delay.rel_value < 4 * TTL_DECREMENT)
2866 score += 1.0; /* likely fast based on latency */
2867 /* 3c) include priorities */
2868 if (cp->avg_priority <= pr->remaining_priority / 2.0)
2869 score += 1.0; /* likely successful based on priorities */
2870 /* 3d) penalize for queue size */
2871 score -= (2.0 * cp->pending_requests / (double) MAX_QUEUE_PER_PEER);
2872 /* 3e) include peer proximity */
2873 score -= (2.0 * (GNUNET_CRYPTO_hash_distance_u32 (key,
2874 &pr->query)) / (double) UINT32_MAX);
2875 /* 4) super-bonus for being the known target */
2876 if (pr->target_pid == cp->pid)
2878 /* store best-fit in closure */
2879 score++; /* avoid zero */
2880 if (score > psc->target_score)
2882 psc->target_score = score;
2883 psc->target.hashPubKey = *key;
2886 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2887 "Peer `%s' gets score %f for forwarding query, max is %8f\n",
2897 * The priority level imposes a bound on the maximum
2898 * value for the ttl that can be requested.
2900 * @param ttl_in requested ttl
2901 * @param prio given priority
2902 * @return ttl_in if ttl_in is below the limit,
2903 * otherwise the ttl-limit for the given priority
2906 bound_ttl (int32_t ttl_in, uint32_t prio)
2908 unsigned long long allowed;
2912 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
2913 if (ttl_in > allowed)
2915 if (allowed >= (1 << 30))
2924 * Iterator called on each result obtained for a DHT
2925 * operation that expects a reply
2927 * @param cls closure
2928 * @param exp when will this value expire
2929 * @param key key of the result
2930 * @param get_path NULL-terminated array of pointers
2931 * to the peers on reverse GET path (or NULL if not recorded)
2932 * @param put_path NULL-terminated array of pointers
2933 * to the peers on the PUT path (or NULL if not recorded)
2934 * @param type type of the result
2935 * @param size number of bytes in data
2936 * @param data pointer to the result data
2939 process_dht_reply (void *cls,
2940 struct GNUNET_TIME_Absolute exp,
2941 const GNUNET_HashCode * key,
2942 const struct GNUNET_PeerIdentity * const *get_path,
2943 const struct GNUNET_PeerIdentity * const *put_path,
2944 enum GNUNET_BLOCK_Type type,
2950 * We're processing a GET request and have decided
2951 * to forward it to other peers. This function is called periodically
2952 * and should forward the request to other peers until we have all
2953 * possible replies. If we have transmitted the *only* reply to
2954 * the initiator we should destroy the pending request. If we have
2955 * many replies in the queue to the initiator, we should delay sending
2956 * out more queries until the reply queue has shrunk some.
2958 * @param cls our "struct ProcessGetContext *"
2962 forward_request_task (void *cls,
2963 const struct GNUNET_SCHEDULER_TaskContext *tc)
2965 struct PendingRequest *pr = cls;
2966 struct PeerSelectionContext psc;
2967 struct ConnectedPeer *cp;
2968 struct GNUNET_TIME_Relative delay;
2970 pr->task = GNUNET_SCHEDULER_NO_TASK;
2971 if (pr->pirc != NULL)
2974 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2975 "Forwarding of query `%s' not attempted due to pending local lookup!\n",
2976 GNUNET_h2s (&pr->query));
2978 return; /* already pending */
2980 if (GNUNET_YES == pr->local_only)
2981 return; /* configured to not do P2P search */
2983 if ( (0 == pr->anonymity_level) &&
2984 (GNUNET_YES != pr->forward_only) &&
2985 (pr->type != GNUNET_BLOCK_TYPE_FS_DBLOCK) &&
2986 (pr->type != GNUNET_BLOCK_TYPE_FS_IBLOCK) )
2988 pr->dht_get = GNUNET_DHT_get_start (dht_handle,
2989 GNUNET_TIME_UNIT_FOREVER_REL,
2992 DEFAULT_GET_REPLICATION,
2997 (pr->namespace != NULL) ? sizeof (GNUNET_HashCode) : 0,
3001 /* (1) select target */
3003 psc.target_score = -DBL_MAX;
3004 psc.fast_retry = GNUNET_NO;
3005 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
3006 &target_peer_select_cb,
3008 if (psc.target_score == -DBL_MAX)
3010 if (psc.fast_retry == GNUNET_YES)
3011 delay = GNUNET_TIME_UNIT_MILLISECONDS; /* FIXME: store adaptive fast-retry value in 'pr' */
3013 delay = get_processing_delay ();
3015 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3016 "No peer selected for forwarding of query `%s', will try again in %llu ms!\n",
3017 GNUNET_h2s (&pr->query),
3020 pr->task = GNUNET_SCHEDULER_add_delayed (delay,
3021 &forward_request_task,
3023 return; /* nobody selected */
3025 /* (3) update TTL/priority */
3026 if (pr->client_request_list != NULL)
3028 /* FIXME: use better algorithm!? */
3029 if (0 == GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3032 /* bound priority we use by priorities we see from other peers
3033 rounded up (must round up so that we can see non-zero
3034 priorities, but round up as little as possible to make it
3035 plausible that we forwarded another peers request) */
3036 if (pr->priority > current_priorities + 1.0)
3037 pr->priority = (uint32_t) current_priorities + 1.0;
3038 pr->ttl = bound_ttl (pr->ttl + TTL_DECREMENT * 2,
3041 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3042 "Trying query `%s' with priority %u and TTL %d.\n",
3043 GNUNET_h2s (&pr->query),
3049 /* (3) reserve reply bandwidth */
3050 if (GNUNET_NO == pr->forward_only)
3052 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3053 &psc.target.hashPubKey);
3054 GNUNET_assert (NULL != cp);
3055 GNUNET_assert (cp->irc == NULL);
3058 cp->irc = GNUNET_CORE_peer_change_preference (core,
3060 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
3061 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
3064 &target_reservation_cb,
3066 GNUNET_assert (cp->irc != NULL);
3067 cp->inc_preference = 0;
3071 /* force forwarding */
3072 static struct GNUNET_BANDWIDTH_Value32NBO zerobw;
3073 target_reservation_cb (pr, &psc.target,
3079 /* **************************** P2P PUT Handling ************************ */
3083 * Function called after we either failed or succeeded
3084 * at transmitting a reply to a peer.
3086 * @param cls the requests "struct PendingRequest*"
3087 * @param tpid ID of receiving peer, 0 on transmission error
3090 transmit_reply_continuation (void *cls,
3091 GNUNET_PEER_Id tpid)
3093 struct PendingRequest *pr = cls;
3097 case GNUNET_BLOCK_TYPE_FS_DBLOCK:
3098 case GNUNET_BLOCK_TYPE_FS_IBLOCK:
3099 /* only one reply expected, done with the request! */
3100 destroy_pending_request (pr);
3102 case GNUNET_BLOCK_TYPE_ANY:
3103 case GNUNET_BLOCK_TYPE_FS_KBLOCK:
3104 case GNUNET_BLOCK_TYPE_FS_SBLOCK:
3114 * Transmit the given message by copying it to the target buffer
3115 * "buf". "buf" will be NULL and "size" zero if the socket was closed
3116 * for writing in the meantime. In that case, do nothing
3117 * (the disconnect or shutdown handler will take care of the rest).
3118 * If we were able to transmit messages and there are still more
3119 * pending, ask core again for further calls to this function.
3121 * @param cls closure, pointer to the 'struct ClientList*'
3122 * @param size number of bytes available in buf
3123 * @param buf where the callee should write the message
3124 * @return number of bytes written to buf
3127 transmit_to_client (void *cls,
3128 size_t size, void *buf)
3130 struct ClientList *cl = cls;
3132 struct ClientResponseMessage *creply;
3139 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3140 "Not sending reply, client communication problem.\n");
3145 while ( (NULL != (creply = cl->res_head) ) &&
3146 (creply->msize <= size) )
3148 memcpy (&cbuf[msize], &creply[1], creply->msize);
3149 msize += creply->msize;
3150 size -= creply->msize;
3151 GNUNET_CONTAINER_DLL_remove (cl->res_head,
3154 GNUNET_free (creply);
3157 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
3159 GNUNET_TIME_UNIT_FOREVER_REL,
3160 &transmit_to_client,
3163 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3164 "Transmitted %u bytes to client\n",
3165 (unsigned int) msize);
3172 * Closure for "process_reply" function.
3174 struct ProcessReplyClosure
3177 * The data for the reply.
3182 * Who gave us this reply? NULL for local host (or DHT)
3184 struct ConnectedPeer *sender;
3187 * When the reply expires.
3189 struct GNUNET_TIME_Absolute expiration;
3197 * Type of the block.
3199 enum GNUNET_BLOCK_Type type;
3202 * How much was this reply worth to us?
3207 * Evaluation result (returned).
3209 enum GNUNET_BLOCK_EvaluationResult eval;
3212 * Did we finish processing the associated request?
3217 * Did we find a matching request?
3224 * We have received a reply; handle it!
3226 * @param cls response (struct ProcessReplyClosure)
3227 * @param key our query
3228 * @param value value in the hash map (info about the query)
3229 * @return GNUNET_YES (we should continue to iterate)
3232 process_reply (void *cls,
3233 const GNUNET_HashCode * key,
3236 struct ProcessReplyClosure *prq = cls;
3237 struct PendingRequest *pr = value;
3238 struct PendingMessage *reply;
3239 struct ClientResponseMessage *creply;
3240 struct ClientList *cl;
3241 struct PutMessage *pm;
3242 struct ConnectedPeer *cp;
3243 struct GNUNET_TIME_Relative cur_delay;
3245 struct GNUNET_TIME_Relative art_delay;
3251 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3252 "Matched result (type %u) for query `%s' with pending request\n",
3253 (unsigned int) prq->type,
3256 GNUNET_STATISTICS_update (stats,
3257 gettext_noop ("# replies received and matched"),
3260 if (prq->sender != NULL)
3262 for (i=0;i<pr->used_targets_off;i++)
3263 if (pr->used_targets[i].pid == prq->sender->pid)
3265 if (i < pr->used_targets_off)
3267 cur_delay = GNUNET_TIME_absolute_get_duration (pr->used_targets[i].last_request_time);
3268 prq->sender->avg_delay.rel_value
3269 = (prq->sender->avg_delay.rel_value *
3270 (RUNAVG_DELAY_N - 1) + cur_delay.rel_value) / RUNAVG_DELAY_N;
3271 prq->sender->avg_priority
3272 = (prq->sender->avg_priority *
3273 (RUNAVG_DELAY_N - 1) + pr->priority) / (double) RUNAVG_DELAY_N;
3277 GNUNET_PEER_change_rc (prq->sender->last_p2p_replies
3278 [prq->sender->last_p2p_replies_woff % P2P_SUCCESS_LIST_SIZE],
3280 GNUNET_PEER_change_rc (pr->cp->pid, 1);
3281 prq->sender->last_p2p_replies
3282 [(prq->sender->last_p2p_replies_woff++) % P2P_SUCCESS_LIST_SIZE]
3287 if (NULL != prq->sender->last_client_replies
3288 [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE])
3289 GNUNET_SERVER_client_drop (prq->sender->last_client_replies
3290 [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE]);
3291 prq->sender->last_client_replies
3292 [(prq->sender->last_client_replies_woff++) % CS2P_SUCCESS_LIST_SIZE]
3293 = pr->client_request_list->client_list->client;
3294 GNUNET_SERVER_client_keep (pr->client_request_list->client_list->client);
3297 prq->eval = GNUNET_BLOCK_evaluate (block_ctx,
3302 pr->namespace, (pr->namespace != NULL) ? sizeof (GNUNET_HashCode) : 0,
3307 case GNUNET_BLOCK_EVALUATION_OK_MORE:
3309 case GNUNET_BLOCK_EVALUATION_OK_LAST:
3310 while (NULL != pr->pending_head)
3311 destroy_pending_message_list_entry (pr->pending_head);
3314 if (pr->client_request_list != NULL)
3315 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
3317 GNUNET_DATASTORE_cancel (pr->qe);
3320 pr->do_remove = GNUNET_YES;
3321 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
3323 GNUNET_SCHEDULER_cancel (pr->task);
3324 pr->task = GNUNET_SCHEDULER_NO_TASK;
3326 GNUNET_break (GNUNET_YES ==
3327 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
3330 GNUNET_LOAD_update (rt_entry_lifetime,
3331 GNUNET_TIME_absolute_get_duration (pr->start_time).rel_value);
3333 case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
3334 GNUNET_STATISTICS_update (stats,
3335 gettext_noop ("# duplicate replies discarded (bloomfilter)"),
3339 /* GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3340 "Duplicate response `%s', discarding.\n",
3341 GNUNET_h2s (&mhash));*/
3343 return GNUNET_YES; /* duplicate */
3344 case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
3345 return GNUNET_YES; /* wrong namespace */
3346 case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
3349 case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
3352 case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
3353 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3354 _("Unsupported block type %u\n"),
3358 if (pr->client_request_list != NULL)
3360 if (pr->replies_seen_size == pr->replies_seen_off)
3361 GNUNET_array_grow (pr->replies_seen,
3362 pr->replies_seen_size,
3363 pr->replies_seen_size * 2 + 4);
3364 GNUNET_CRYPTO_hash (prq->data,
3366 &pr->replies_seen[pr->replies_seen_off++]);
3367 refresh_bloomfilter (pr);
3369 if (NULL == prq->sender)
3372 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3373 "Found result for query `%s' in local datastore\n",
3376 GNUNET_STATISTICS_update (stats,
3377 gettext_noop ("# results found locally"),
3381 prq->priority += pr->remaining_priority;
3382 pr->remaining_priority = 0;
3383 pr->results_found++;
3384 prq->request_found = GNUNET_YES;
3385 if (NULL != pr->client_request_list)
3387 GNUNET_STATISTICS_update (stats,
3388 gettext_noop ("# replies received for local clients"),
3391 cl = pr->client_request_list->client_list;
3392 msize = sizeof (struct PutMessage) + prq->size;
3393 creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
3394 creply->msize = msize;
3395 creply->client_list = cl;
3396 GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
3400 pm = (struct PutMessage*) &creply[1];
3401 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
3402 pm->header.size = htons (msize);
3403 pm->type = htonl (prq->type);
3404 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
3405 memcpy (&pm[1], prq->data, prq->size);
3409 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3410 "Transmitting result for query `%s' to client\n",
3413 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
3415 GNUNET_TIME_UNIT_FOREVER_REL,
3416 &transmit_to_client,
3419 GNUNET_break (cl->th != NULL);
3422 prq->finished = GNUNET_YES;
3423 destroy_pending_request (pr);
3430 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3431 "Transmitting result for query `%s' to other peer (PID=%u)\n",
3433 (unsigned int) cp->pid);
3435 GNUNET_STATISTICS_update (stats,
3436 gettext_noop ("# replies received for other peers"),
3439 msize = sizeof (struct PutMessage) + prq->size;
3440 reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
3441 reply->cont = &transmit_reply_continuation;
3442 reply->cont_cls = pr;
3444 art_delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
3445 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3448 = GNUNET_TIME_relative_to_absolute (art_delay);
3449 GNUNET_STATISTICS_update (stats,
3450 gettext_noop ("cummulative artificial delay introduced (ms)"),
3451 art_delay.abs_value,
3454 reply->msize = msize;
3455 reply->priority = UINT32_MAX; /* send replies first! */
3456 pm = (struct PutMessage*) &reply[1];
3457 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
3458 pm->header.size = htons (msize);
3459 pm->type = htonl (prq->type);
3460 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
3461 memcpy (&pm[1], prq->data, prq->size);
3462 add_to_pending_messages_for_peer (cp, reply, pr);
3469 * Iterator called on each result obtained for a DHT
3470 * operation that expects a reply
3472 * @param cls closure
3473 * @param exp when will this value expire
3474 * @param key key of the result
3475 * @param get_path NULL-terminated array of pointers
3476 * to the peers on reverse GET path (or NULL if not recorded)
3477 * @param put_path NULL-terminated array of pointers
3478 * to the peers on the PUT path (or NULL if not recorded)
3479 * @param type type of the result
3480 * @param size number of bytes in data
3481 * @param data pointer to the result data
3484 process_dht_reply (void *cls,
3485 struct GNUNET_TIME_Absolute exp,
3486 const GNUNET_HashCode * key,
3487 const struct GNUNET_PeerIdentity * const *get_path,
3488 const struct GNUNET_PeerIdentity * const *put_path,
3489 enum GNUNET_BLOCK_Type type,
3493 struct PendingRequest *pr = cls;
3494 struct ProcessReplyClosure prq;
3496 memset (&prq, 0, sizeof (prq));
3498 prq.expiration = exp;
3501 process_reply (&prq, key, pr);
3507 * Continuation called to notify client about result of the
3510 * @param cls closure
3511 * @param success GNUNET_SYSERR on failure
3512 * @param msg NULL on success, otherwise an error message
3515 put_migration_continuation (void *cls,
3519 struct GNUNET_TIME_Absolute *start = cls;
3520 struct GNUNET_TIME_Relative delay;
3522 delay = GNUNET_TIME_absolute_get_duration (*start);
3523 GNUNET_free (start);
3524 GNUNET_LOAD_update (datastore_put_load,
3526 if (GNUNET_OK == success)
3528 GNUNET_STATISTICS_update (stats,
3529 gettext_noop ("# datastore 'put' failures"),
3536 * Handle P2P "PUT" message.
3538 * @param cls closure, always NULL
3539 * @param other the other peer involved (sender or receiver, NULL
3540 * for loopback messages where we are both sender and receiver)
3541 * @param message the actual message
3542 * @param atsi performance information
3543 * @return GNUNET_OK to keep the connection open,
3544 * GNUNET_SYSERR to close it (signal serious error)
3547 handle_p2p_put (void *cls,
3548 const struct GNUNET_PeerIdentity *other,
3549 const struct GNUNET_MessageHeader *message,
3550 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
3552 const struct PutMessage *put;
3555 enum GNUNET_BLOCK_Type type;
3556 struct GNUNET_TIME_Absolute expiration;
3557 GNUNET_HashCode query;
3558 struct ProcessReplyClosure prq;
3559 struct GNUNET_TIME_Absolute *start;
3560 struct GNUNET_TIME_Relative block_time;
3562 struct ConnectedPeer *cp;
3563 struct PendingMessage *pm;
3564 struct MigrationStopMessage *msm;
3566 msize = ntohs (message->size);
3567 if (msize < sizeof (struct PutMessage))
3570 return GNUNET_SYSERR;
3572 put = (const struct PutMessage*) message;
3573 dsize = msize - sizeof (struct PutMessage);
3574 type = ntohl (put->type);
3575 expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
3577 if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
3578 return GNUNET_SYSERR;
3580 GNUNET_BLOCK_get_key (block_ctx,
3586 GNUNET_break_op (0);
3587 return GNUNET_SYSERR;
3590 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3591 "Received result for query `%s' from peer `%4s'\n",
3592 GNUNET_h2s (&query),
3593 GNUNET_i2s (other));
3595 GNUNET_STATISTICS_update (stats,
3596 gettext_noop ("# replies received (overall)"),
3599 /* now, lookup 'query' */
3600 prq.data = (const void*) &put[1];
3602 prq.sender = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3603 &other->hashPubKey);
3608 prq.expiration = expiration;
3610 prq.finished = GNUNET_NO;
3611 prq.request_found = GNUNET_NO;
3612 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
3616 if (prq.sender != NULL)
3618 prq.sender->inc_preference += CONTENT_BANDWIDTH_VALUE + 1000 * prq.priority;
3619 change_host_trust (prq.sender, prq.priority);
3621 if ( (GNUNET_YES == active_migration) &&
3622 (GNUNET_NO == test_put_load_too_high (prq.priority)) )
3625 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3626 "Replicating result for query `%s' with priority %u\n",
3627 GNUNET_h2s (&query),
3630 start = GNUNET_malloc (sizeof (struct GNUNET_TIME_Absolute));
3631 *start = GNUNET_TIME_absolute_get ();
3632 GNUNET_DATASTORE_put (dsh,
3633 0, &query, dsize, &put[1],
3634 type, prq.priority, 1 /* anonymity */,
3636 1 + prq.priority, MAX_DATASTORE_QUEUE,
3637 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
3638 &put_migration_continuation,
3641 putl = GNUNET_LOAD_get_load (datastore_put_load);
3642 if ( (GNUNET_NO == prq.request_found) &&
3643 ( (GNUNET_YES != active_migration) ||
3644 (putl > 2.5 * (1 + prq.priority)) ) )
3646 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3647 &other->hashPubKey);
3648 if (GNUNET_TIME_absolute_get_duration (cp->last_migration_block).rel_value < 5000)
3649 return GNUNET_OK; /* already blocked */
3650 /* We're too busy; send MigrationStop message! */
3651 if (GNUNET_YES != active_migration)
3652 putl = 1.0 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 5);
3653 block_time = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
3654 5000 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3655 (unsigned int) (60000 * putl * putl)));
3657 cp->last_migration_block = GNUNET_TIME_relative_to_absolute (block_time);
3658 pm = GNUNET_malloc (sizeof (struct PendingMessage) +
3659 sizeof (struct MigrationStopMessage));
3660 pm->msize = sizeof (struct MigrationStopMessage);
3661 pm->priority = UINT32_MAX;
3662 msm = (struct MigrationStopMessage*) &pm[1];
3663 msm->header.size = htons (sizeof (struct MigrationStopMessage));
3664 msm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP);
3665 msm->duration = GNUNET_TIME_relative_hton (block_time);
3666 add_to_pending_messages_for_peer (cp,
3675 * Handle P2P "MIGRATION_STOP" message.
3677 * @param cls closure, always NULL
3678 * @param other the other peer involved (sender or receiver, NULL
3679 * for loopback messages where we are both sender and receiver)
3680 * @param message the actual message
3681 * @param atsi performance information
3682 * @return GNUNET_OK to keep the connection open,
3683 * GNUNET_SYSERR to close it (signal serious error)
3686 handle_p2p_migration_stop (void *cls,
3687 const struct GNUNET_PeerIdentity *other,
3688 const struct GNUNET_MessageHeader *message,
3689 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
3691 struct ConnectedPeer *cp;
3692 const struct MigrationStopMessage *msm;
3694 msm = (const struct MigrationStopMessage*) message;
3695 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3696 &other->hashPubKey);
3702 cp->migration_blocked = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (msm->duration));
3708 /* **************************** P2P GET Handling ************************ */
3712 * Closure for 'check_duplicate_request_{peer,client}'.
3714 struct CheckDuplicateRequestClosure
3717 * The new request we should check if it already exists.
3719 const struct PendingRequest *pr;
3722 * Existing request found by the checker, NULL if none.
3724 struct PendingRequest *have;
3729 * Iterator over entries in the 'query_request_map' that
3730 * tries to see if we have the same request pending from
3731 * the same client already.
3733 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
3734 * @param key current key code (query, ignored, must match)
3735 * @param value value in the hash map (a 'struct PendingRequest'
3736 * that already exists)
3737 * @return GNUNET_YES if we should continue to
3738 * iterate (no match yet)
3739 * GNUNET_NO if not (match found).
3742 check_duplicate_request_client (void *cls,
3743 const GNUNET_HashCode * key,
3746 struct CheckDuplicateRequestClosure *cdc = cls;
3747 struct PendingRequest *have = value;
3749 if (have->client_request_list == NULL)
3751 if ( (cdc->pr->client_request_list->client_list->client == have->client_request_list->client_list->client) &&
3762 * We're processing (local) results for a search request
3763 * from another peer. Pass applicable results to the
3764 * peer and if we are done either clean up (operation
3765 * complete) or forward to other peers (more results possible).
3767 * @param cls our closure (struct LocalGetContext)
3768 * @param key key for the content
3769 * @param size number of bytes in data
3770 * @param data content stored
3771 * @param type type of the content
3772 * @param priority priority of the content
3773 * @param anonymity anonymity-level for the content
3774 * @param expiration expiration time for the content
3775 * @param uid unique identifier for the datum;
3776 * maybe 0 if no unique identifier is available
3779 process_local_reply (void *cls,
3780 const GNUNET_HashCode * key,
3783 enum GNUNET_BLOCK_Type type,
3786 struct GNUNET_TIME_Absolute
3790 struct PendingRequest *pr = cls;
3791 struct ProcessReplyClosure prq;
3792 struct CheckDuplicateRequestClosure cdrc;
3793 GNUNET_HashCode query;
3794 unsigned int old_rf;
3799 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3800 "Done processing local replies, forwarding request to other peers.\n");
3803 if (pr->client_request_list != NULL)
3805 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
3807 /* Figure out if this is a duplicate request and possibly
3808 merge 'struct PendingRequest' entries */
3811 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
3813 &check_duplicate_request_client,
3815 if (cdrc.have != NULL)
3818 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3819 "Received request for block `%s' twice from client, will only request once.\n",
3820 GNUNET_h2s (&pr->query));
3823 destroy_pending_request (pr);
3827 if (pr->local_only == GNUNET_YES)
3829 destroy_pending_request (pr);
3832 /* no more results */
3833 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
3834 pr->task = GNUNET_SCHEDULER_add_now (&forward_request_task,
3839 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3840 "New local response to `%s' of type %u.\n",
3844 if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
3847 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3848 "Found ONDEMAND block, performing on-demand encoding\n");
3850 GNUNET_STATISTICS_update (stats,
3851 gettext_noop ("# on-demand blocks matched requests"),
3855 GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
3856 anonymity, expiration, uid,
3857 &process_local_reply,
3861 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3865 old_rf = pr->results_found;
3866 memset (&prq, 0, sizeof (prq));
3868 prq.expiration = expiration;
3871 GNUNET_BLOCK_get_key (block_ctx,
3878 GNUNET_DATASTORE_remove (dsh,
3882 GNUNET_TIME_UNIT_FOREVER_REL,
3884 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3888 prq.priority = priority;
3889 prq.finished = GNUNET_NO;
3890 prq.request_found = GNUNET_NO;
3891 if ( (old_rf == 0) &&
3892 (pr->results_found == 0) )
3893 update_datastore_delays (pr->start_time);
3894 process_reply (&prq, key, pr);
3895 if (prq.finished == GNUNET_YES)
3898 return; /* done here */
3899 if (prq.eval == GNUNET_BLOCK_EVALUATION_OK_LAST)
3901 pr->local_only = GNUNET_YES; /* do not forward */
3902 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
3905 if ( (pr->client_request_list == NULL) &&
3906 ( (GNUNET_YES == test_get_load_too_high (0)) ||
3907 (pr->results_found > 5 + 2 * pr->priority) ) )
3910 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3911 "Load too high, done with request\n");
3913 GNUNET_STATISTICS_update (stats,
3914 gettext_noop ("# processing result set cut short due to load"),
3917 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
3920 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3925 * We've received a request with the specified priority. Bound it
3926 * according to how much we trust the given peer.
3928 * @param prio_in requested priority
3929 * @param cp the peer making the request
3930 * @return effective priority
3933 bound_priority (uint32_t prio_in,
3934 struct ConnectedPeer *cp)
3936 #define N ((double)128.0)
3941 ld = test_get_load_too_high (0);
3942 if (ld == GNUNET_SYSERR)
3944 GNUNET_STATISTICS_update (stats,
3945 gettext_noop ("# requests done for free (low load)"),
3948 return 0; /* excess resources */
3950 if (prio_in > INT32_MAX)
3951 prio_in = INT32_MAX;
3952 ret = - change_host_trust (cp, - (int) prio_in);
3955 if (ret > current_priorities + N)
3956 rret = current_priorities + N;
3960 = (current_priorities * (N-1) + rret)/N;
3962 if ( (ld == GNUNET_YES) && (ret > 0) )
3964 /* try with charging */
3965 ld = test_get_load_too_high (ret);
3967 if (ld == GNUNET_YES)
3969 GNUNET_STATISTICS_update (stats,
3970 gettext_noop ("# request dropped, priority insufficient"),
3974 change_host_trust (cp, (int) ret);
3975 return -1; /* not enough resources */
3979 GNUNET_STATISTICS_update (stats,
3980 gettext_noop ("# requests done for a price (normal load)"),
3990 * Iterator over entries in the 'query_request_map' that
3991 * tries to see if we have the same request pending from
3992 * the same peer already.
3994 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
3995 * @param key current key code (query, ignored, must match)
3996 * @param value value in the hash map (a 'struct PendingRequest'
3997 * that already exists)
3998 * @return GNUNET_YES if we should continue to
3999 * iterate (no match yet)
4000 * GNUNET_NO if not (match found).
4003 check_duplicate_request_peer (void *cls,
4004 const GNUNET_HashCode * key,
4007 struct CheckDuplicateRequestClosure *cdc = cls;
4008 struct PendingRequest *have = value;
4010 if (cdc->pr->target_pid == have->target_pid)
4020 * Handle P2P "GET" request.
4022 * @param cls closure, always NULL
4023 * @param other the other peer involved (sender or receiver, NULL
4024 * for loopback messages where we are both sender and receiver)
4025 * @param message the actual message
4026 * @param atsi performance information
4027 * @return GNUNET_OK to keep the connection open,
4028 * GNUNET_SYSERR to close it (signal serious error)
4031 handle_p2p_get (void *cls,
4032 const struct GNUNET_PeerIdentity *other,
4033 const struct GNUNET_MessageHeader *message,
4034 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
4036 struct PendingRequest *pr;
4037 struct ConnectedPeer *cp;
4038 struct ConnectedPeer *cps;
4039 struct CheckDuplicateRequestClosure cdc;
4040 struct GNUNET_TIME_Relative timeout;
4042 const struct GetMessage *gm;
4044 const GNUNET_HashCode *opt;
4047 uint32_t ttl_decrement;
4049 enum GNUNET_BLOCK_Type type;
4052 msize = ntohs(message->size);
4053 if (msize < sizeof (struct GetMessage))
4055 GNUNET_break_op (0);
4056 return GNUNET_SYSERR;
4058 gm = (const struct GetMessage*) message;
4060 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4061 "Received request for `%s'\n",
4062 GNUNET_h2s (&gm->query));
4064 type = ntohl (gm->type);
4065 bm = ntohl (gm->hash_bitmap);
4073 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
4075 GNUNET_break_op (0);
4076 return GNUNET_SYSERR;
4078 opt = (const GNUNET_HashCode*) &gm[1];
4079 bfsize = msize - sizeof (struct GetMessage) - bits * sizeof (GNUNET_HashCode);
4080 /* bfsize must be power of 2, check! */
4081 if (0 != ( (bfsize - 1) & bfsize))
4083 GNUNET_break_op (0);
4084 return GNUNET_SYSERR;
4086 bm = ntohl (gm->hash_bitmap);
4088 cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
4089 &other->hashPubKey);
4092 /* peer must have just disconnected */
4093 GNUNET_STATISTICS_update (stats,
4094 gettext_noop ("# requests dropped due to initiator not being connected"),
4097 return GNUNET_SYSERR;
4099 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
4100 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
4107 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
4108 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4109 "Failed to find RETURN-TO peer `%4s' in connection set. Dropping query.\n",
4110 GNUNET_i2s ((const struct GNUNET_PeerIdentity*) &opt[bits-1]));
4113 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4114 "Failed to find peer `%4s' in connection set. Dropping query.\n",
4115 GNUNET_i2s (other));
4117 GNUNET_STATISTICS_update (stats,
4118 gettext_noop ("# requests dropped due to missing reverse route"),
4121 /* FIXME: try connect? */
4124 /* note that we can really only check load here since otherwise
4125 peers could find out that we are overloaded by not being
4126 disconnected after sending us a malformed query... */
4127 priority = bound_priority (ntohl (gm->priority), cps);
4131 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4132 "Dropping query from `%s', this peer is too busy.\n",
4133 GNUNET_i2s (other));
4138 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4139 "Received request for `%s' of type %u from peer `%4s' with flags %u\n",
4140 GNUNET_h2s (&gm->query),
4141 (unsigned int) type,
4145 have_ns = (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE));
4146 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
4147 (have_ns ? sizeof(GNUNET_HashCode) : 0));
4150 pr->namespace = (GNUNET_HashCode*) &pr[1];
4151 memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
4153 if ( (GNUNET_LOAD_get_load (cp->transmission_delay) > 3 * (1 + priority)) ||
4154 (GNUNET_LOAD_get_average (cp->transmission_delay) >
4155 GNUNET_CONSTANTS_MAX_CORK_DELAY.rel_value * 2 + GNUNET_LOAD_get_average (rt_entry_lifetime)) )
4157 /* don't have BW to send to peer, or would likely take longer than we have for it,
4158 so at best indirect the query */
4160 pr->forward_only = GNUNET_YES;
4163 pr->mingle = ntohl (gm->filter_mutator);
4164 if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
4165 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
4166 pr->anonymity_level = 1;
4167 pr->priority = (uint32_t) priority;
4168 pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
4169 pr->query = gm->query;
4170 /* decrement ttl (always) */
4171 ttl_decrement = 2 * TTL_DECREMENT +
4172 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
4174 if ( (pr->ttl < 0) &&
4175 (((int32_t)(pr->ttl - ttl_decrement)) > 0) )
4178 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4179 "Dropping query from `%s' due to TTL underflow (%d - %u).\n",
4184 GNUNET_STATISTICS_update (stats,
4185 gettext_noop ("# requests dropped due TTL underflow"),
4188 /* integer underflow => drop (should be very rare)! */
4192 pr->ttl -= ttl_decrement;
4193 pr->start_time = GNUNET_TIME_absolute_get ();
4195 /* get bloom filter */
4198 pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
4201 pr->bf_size = bfsize;
4205 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
4207 &check_duplicate_request_peer,
4209 if (cdc.have != NULL)
4211 if (cdc.have->start_time.abs_value + cdc.have->ttl >=
4212 pr->start_time.abs_value + pr->ttl)
4214 /* existing request has higher TTL, drop new one! */
4215 cdc.have->priority += pr->priority;
4216 destroy_pending_request (pr);
4218 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4219 "Have existing request with higher TTL, dropping new request.\n",
4220 GNUNET_i2s (other));
4222 GNUNET_STATISTICS_update (stats,
4223 gettext_noop ("# requests dropped due to higher-TTL request"),
4230 /* existing request has lower TTL, drop old one! */
4231 pr->priority += cdc.have->priority;
4232 /* Possible optimization: if we have applicable pending
4233 replies in 'cdc.have', we might want to move those over
4234 (this is a really rare special-case, so it is not clear
4235 that this would be worth it) */
4236 destroy_pending_request (cdc.have);
4237 /* keep processing 'pr'! */
4242 GNUNET_break (GNUNET_OK ==
4243 GNUNET_CONTAINER_multihashmap_put (query_request_map,
4246 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
4247 GNUNET_break (GNUNET_OK ==
4248 GNUNET_CONTAINER_multihashmap_put (peer_request_map,
4251 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
4253 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
4255 pr->start_time.abs_value + pr->ttl);
4257 GNUNET_STATISTICS_update (stats,
4258 gettext_noop ("# P2P searches received"),
4261 GNUNET_STATISTICS_update (stats,
4262 gettext_noop ("# P2P searches active"),
4266 /* calculate change in traffic preference */
4267 cps->inc_preference += pr->priority * 1000 + QUERY_BANDWIDTH_VALUE;
4268 /* process locally */
4269 if (type == GNUNET_BLOCK_TYPE_FS_DBLOCK)
4270 type = GNUNET_BLOCK_TYPE_ANY; /* to get on-demand as well */
4271 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
4272 (pr->priority + 1));
4273 if (GNUNET_YES != pr->forward_only)
4276 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4277 "Handing request for `%s' to datastore\n",
4278 GNUNET_h2s (&gm->query));
4280 pr->qe = GNUNET_DATASTORE_get (dsh,
4284 MAX_DATASTORE_QUEUE,
4286 &process_local_reply,
4290 GNUNET_STATISTICS_update (stats,
4291 gettext_noop ("# requests dropped by datastore (queue length limit)"),
4298 GNUNET_STATISTICS_update (stats,
4299 gettext_noop ("# requests forwarded due to high load"),
4304 /* Are multiple results possible (and did we look locally)? If so, start processing remotely now! */
4307 case GNUNET_BLOCK_TYPE_FS_DBLOCK:
4308 case GNUNET_BLOCK_TYPE_FS_IBLOCK:
4309 /* only one result, wait for datastore */
4310 if (GNUNET_YES != pr->forward_only)
4312 GNUNET_STATISTICS_update (stats,
4313 gettext_noop ("# requests not instantly forwarded (waiting for datastore)"),
4319 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
4320 pr->task = GNUNET_SCHEDULER_add_now (&forward_request_task,
4324 /* make sure we don't track too many requests */
4325 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
4327 pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
4328 GNUNET_assert (pr != NULL);
4329 destroy_pending_request (pr);
4335 /* **************************** CS GET Handling ************************ */
4339 * Handle START_SEARCH-message (search request from client).
4341 * @param cls closure
4342 * @param client identification of the client
4343 * @param message the actual message
4346 handle_start_search (void *cls,
4347 struct GNUNET_SERVER_Client *client,
4348 const struct GNUNET_MessageHeader *message)
4350 static GNUNET_HashCode all_zeros;
4351 const struct SearchMessage *sm;
4352 struct ClientList *cl;
4353 struct ClientRequestList *crl;
4354 struct PendingRequest *pr;
4357 enum GNUNET_BLOCK_Type type;
4359 msize = ntohs (message->size);
4360 if ( (msize < sizeof (struct SearchMessage)) ||
4361 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
4364 GNUNET_SERVER_receive_done (client,
4368 GNUNET_STATISTICS_update (stats,
4369 gettext_noop ("# client searches received"),
4372 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
4373 sm = (const struct SearchMessage*) message;
4374 type = ntohl (sm->type);
4376 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4377 "Received request for `%s' of type %u from local client\n",
4378 GNUNET_h2s (&sm->query),
4379 (unsigned int) type);
4382 while ( (cl != NULL) &&
4383 (cl->client != client) )
4387 cl = GNUNET_malloc (sizeof (struct ClientList));
4388 cl->client = client;
4389 GNUNET_SERVER_client_keep (client);
4390 cl->next = client_list;
4393 /* detect duplicate KBLOCK requests */
4394 if ( (type == GNUNET_BLOCK_TYPE_FS_KBLOCK) ||
4395 (type == GNUNET_BLOCK_TYPE_FS_NBLOCK) ||
4396 (type == GNUNET_BLOCK_TYPE_ANY) )
4399 while ( (crl != NULL) &&
4400 ( (0 != memcmp (&crl->req->query,
4402 sizeof (GNUNET_HashCode))) ||
4403 (crl->req->type != type) ) )
4408 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4409 "Have existing request, merging content-seen lists.\n");
4412 /* Duplicate request (used to send long list of
4413 known/blocked results); merge 'pr->replies_seen'
4414 and update bloom filter */
4415 GNUNET_array_grow (pr->replies_seen,
4416 pr->replies_seen_size,
4417 pr->replies_seen_off + sc);
4418 memcpy (&pr->replies_seen[pr->replies_seen_off],
4420 sc * sizeof (GNUNET_HashCode));
4421 pr->replies_seen_off += sc;
4422 refresh_bloomfilter (pr);
4423 GNUNET_STATISTICS_update (stats,
4424 gettext_noop ("# client searches updated (merged content seen list)"),
4427 GNUNET_SERVER_receive_done (client,
4432 GNUNET_STATISTICS_update (stats,
4433 gettext_noop ("# client searches active"),
4436 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
4437 ((type == GNUNET_BLOCK_TYPE_FS_SBLOCK) ? sizeof(GNUNET_HashCode) : 0));
4438 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
4439 memset (crl, 0, sizeof (struct ClientRequestList));
4440 crl->client_list = cl;
4441 GNUNET_CONTAINER_DLL_insert (cl->rl_head,
4446 pr->client_request_list = crl;
4447 GNUNET_array_grow (pr->replies_seen,
4448 pr->replies_seen_size,
4450 memcpy (pr->replies_seen,
4452 sc * sizeof (GNUNET_HashCode));
4453 pr->replies_seen_off = sc;
4454 pr->anonymity_level = ntohl (sm->anonymity_level);
4455 pr->start_time = GNUNET_TIME_absolute_get ();
4456 refresh_bloomfilter (pr);
4457 pr->query = sm->query;
4458 if (0 == (1 & ntohl (sm->options)))
4459 pr->local_only = GNUNET_NO;
4461 pr->local_only = GNUNET_YES;
4464 case GNUNET_BLOCK_TYPE_FS_DBLOCK:
4465 case GNUNET_BLOCK_TYPE_FS_IBLOCK:
4466 if (0 != memcmp (&sm->target,
4468 sizeof (GNUNET_HashCode)))
4469 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
4471 case GNUNET_BLOCK_TYPE_FS_SBLOCK:
4472 pr->namespace = (GNUNET_HashCode*) &pr[1];
4473 memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
4478 GNUNET_break (GNUNET_OK ==
4479 GNUNET_CONTAINER_multihashmap_put (query_request_map,
4482 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
4483 if (type == GNUNET_BLOCK_TYPE_FS_DBLOCK)
4484 type = GNUNET_BLOCK_TYPE_ANY; /* get on-demand blocks too! */
4485 pr->qe = GNUNET_DATASTORE_get (dsh,
4489 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
4490 &process_local_reply,
4495 /* **************************** Startup ************************ */
4498 * Process fs requests.
4500 * @param server the initialized server
4501 * @param c configuration to use
4504 main_init (struct GNUNET_SERVER_Handle *server,
4505 const struct GNUNET_CONFIGURATION_Handle *c)
4507 static const struct GNUNET_CORE_MessageHandler p2p_handlers[] =
4510 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
4512 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
4513 { &handle_p2p_migration_stop,
4514 GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP,
4515 sizeof (struct MigrationStopMessage) },
4518 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
4519 {&GNUNET_FS_handle_index_start, NULL,
4520 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
4521 {&GNUNET_FS_handle_index_list_get, NULL,
4522 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
4523 {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
4524 sizeof (struct UnindexMessage) },
4525 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
4529 unsigned long long enc = 128;
4532 stats = GNUNET_STATISTICS_create ("fs", cfg);
4533 min_migration_delay = GNUNET_TIME_UNIT_SECONDS;
4535 GNUNET_CONFIGURATION_get_value_number (cfg,
4537 "MAX_PENDING_REQUESTS",
4538 &max_pending_requests)) ||
4540 GNUNET_CONFIGURATION_get_value_number (cfg,
4542 "EXPECTED_NEIGHBOUR_COUNT",
4545 GNUNET_CONFIGURATION_get_value_time (cfg,
4547 "MIN_MIGRATION_DELAY",
4548 &min_migration_delay)) )
4550 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4551 _("Configuration fails to specify certain parameters, assuming default values."));
4553 connected_peers = GNUNET_CONTAINER_multihashmap_create (enc);
4554 query_request_map = GNUNET_CONTAINER_multihashmap_create (max_pending_requests);
4555 rt_entry_lifetime = GNUNET_LOAD_value_init (GNUNET_TIME_UNIT_FOREVER_REL);
4556 peer_request_map = GNUNET_CONTAINER_multihashmap_create (enc);
4557 requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
4558 core = GNUNET_CORE_connect (cfg,
4562 &peer_connect_handler,
4563 &peer_disconnect_handler,
4564 &peer_status_handler,
4570 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4571 _("Failed to connect to `%s' service.\n"),
4573 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
4574 connected_peers = NULL;
4575 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
4576 query_request_map = NULL;
4577 GNUNET_LOAD_value_free (rt_entry_lifetime);
4578 rt_entry_lifetime = NULL;
4579 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
4580 requests_by_expiration_heap = NULL;
4581 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
4582 peer_request_map = NULL;
4585 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
4588 return GNUNET_SYSERR;
4590 /* FIXME: distinguish between sending and storing in options? */
4591 if (active_migration)
4593 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4594 _("Content migration is enabled, will start to gather data\n"));
4595 consider_migration_gathering ();
4597 consider_dht_put_gathering (NULL);
4598 GNUNET_SERVER_disconnect_notify (server,
4599 &handle_client_disconnect,
4601 GNUNET_assert (GNUNET_OK ==
4602 GNUNET_CONFIGURATION_get_value_filename (cfg,
4606 GNUNET_DISK_directory_create (trustDirectory);
4607 GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_HIGH,
4608 &cron_flush_trust, NULL);
4611 GNUNET_SERVER_add_handlers (server, handlers);
4612 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4620 * Process fs requests.
4622 * @param cls closure
4623 * @param server the initialized server
4624 * @param cfg configuration to use
4628 struct GNUNET_SERVER_Handle *server,
4629 const struct GNUNET_CONFIGURATION_Handle *cfg)
4631 active_migration = GNUNET_CONFIGURATION_get_value_yesno (cfg,
4634 dsh = GNUNET_DATASTORE_connect (cfg);
4637 GNUNET_SCHEDULER_shutdown ();
4640 datastore_get_load = GNUNET_LOAD_value_init (DATASTORE_LOAD_AUTODECLINE);
4641 datastore_put_load = GNUNET_LOAD_value_init (DATASTORE_LOAD_AUTODECLINE);
4642 block_cfg = GNUNET_CONFIGURATION_create ();
4643 GNUNET_CONFIGURATION_set_value_string (block_cfg,
4647 block_ctx = GNUNET_BLOCK_context_create (block_cfg);
4648 GNUNET_assert (NULL != block_ctx);
4649 dht_handle = GNUNET_DHT_connect (cfg,
4651 if ( (GNUNET_OK != GNUNET_FS_indexing_init (cfg, dsh)) ||
4652 (GNUNET_OK != main_init (server, cfg)) )
4654 GNUNET_SCHEDULER_shutdown ();
4655 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
4657 GNUNET_DHT_disconnect (dht_handle);
4659 GNUNET_BLOCK_context_destroy (block_ctx);
4661 GNUNET_CONFIGURATION_destroy (block_cfg);
4663 GNUNET_LOAD_value_free (datastore_get_load);
4664 datastore_get_load = NULL;
4665 GNUNET_LOAD_value_free (datastore_put_load);
4666 datastore_put_load = NULL;
4673 * The main function for the fs service.
4675 * @param argc number of arguments from the command line
4676 * @param argv command line arguments
4677 * @return 0 ok, 1 on error
4680 main (int argc, char *const *argv)
4682 return (GNUNET_OK ==
4683 GNUNET_SERVICE_run (argc,
4686 GNUNET_SERVICE_OPTION_NONE,
4687 &run, NULL)) ? 0 : 1;
4690 /* end of gnunet-service-fs.c */