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
28 #include "gnunet_constants.h"
29 #include "gnunet_core_service.h"
30 #include "gnunet_dht_service.h"
31 #include "gnunet_datastore_service.h"
32 #include "gnunet_load_lib.h"
33 #include "gnunet_peer_lib.h"
34 #include "gnunet_protocols.h"
35 #include "gnunet_signatures.h"
36 #include "gnunet_statistics_service.h"
37 #include "gnunet_transport_service.h"
38 #include "gnunet_util_lib.h"
39 #include "gnunet-service-fs_indexing.h"
42 #define DEBUG_FS GNUNET_YES
45 * Should we introduce random latency in processing? Required for proper
46 * implementation of GAP, but can be disabled for performance evaluation of
47 * the basic routing algorithm.
49 * Note that with delays enabled, performance can be significantly lower
50 * (several orders of magnitude in 2-peer test runs); if you want to
51 * measure throughput of other components, set this to NO. Also, you
52 * might want to consider changing 'RETRY_PROBABILITY_INV' to 1 for
53 * a rather wasteful mode of operation (that might still get the highest
54 * throughput overall).
56 * Performance measurements (for 50 MB file, 2 peers):
58 * - Without delays: 3300 kb/s
59 * - With delays: 101 kb/s
61 #define SUPPORT_DELAYS GNUNET_NO
64 * Size for the hash map for DHT requests from the FS
65 * service. Should be about the number of concurrent
66 * DHT requests we plan to make.
68 #define FS_DHT_HT_SIZE 1024
71 * At what frequency should our datastore load decrease
72 * automatically (since if we don't use it, clearly the
73 * load must be going down).
75 #define DATASTORE_LOAD_AUTODECLINE GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 250)
78 * How often do we flush trust values to disk?
80 #define TRUST_FLUSH_FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
83 * How quickly do we age cover traffic? At the given
84 * time interval, remaining cover traffic counters are
85 * decremented by 1/16th.
87 #define COVER_AGE_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
90 * How often do we at most PUT content into the DHT?
92 #define MAX_DHT_PUT_FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
95 * How long must content remain valid for us to consider it for migration?
96 * If content will expire too soon, there is clearly no point in pushing
97 * it to other peers. This value gives the threshold for migration. Note
98 * that if this value is increased, the migration testcase may need to be
99 * adjusted as well (especially the CONTENT_LIFETIME in fs_test_lib.c).
101 #define MIN_MIGRATION_CONTENT_LIFETIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 30)
104 * Inverse of the probability that we will submit the same query
105 * to the same peer again. If the same peer already got the query
106 * repeatedly recently, the probability is multiplied by the inverse
107 * of this number each time. Note that we only try about every TTL_DECREMENT/2
108 * plus MAX_CORK_DELAY (so roughly every 3.5s).
110 * Note that this factor is a key influence to performance in small
111 * networks (especially test networks of 2 peers) because if there is
112 * only a single peer with the data, this value will determine how
113 * soon we might re-try. For example, a value of 3 can result in
114 * 1.7 MB/s transfer rates for a 10 MB file when a value of 1 would
115 * give us 5 MB/s. OTOH, obviously re-trying the same peer can be
116 * rather inefficient in larger networks, hence picking 1 is in
117 * general not the best choice.
119 * Performance measurements (for 50 MB file, 2 peers, no delays):
121 * - 1: 3300 kb/s (consistently)
122 * - 3: 2046 kb/s, 754 kb/s, 3490 kb/s
123 * - 5: 759 kb/s, 968 kb/s, 1160 kb/s
125 * Note that this does NOT mean that the value should be 1 since
126 * a 2-peer network is far from representative here (and this fails
127 * to take into consideration bandwidth wasted by repeatedly
128 * sending queries to peers that don't have the content). Also,
129 * it is expected that higher values lead to more inconsistent
130 * measurements since this only affects lost messages towards the
131 * end of the download.
133 * Finally, we should probably consider changing this and making
134 * it dependent on the number of connected peers or a related
135 * metric (bad magic constants...).
137 #define RETRY_PROBABILITY_INV 1
140 * What is the maximum delay for a P2P FS message (in our interaction
141 * with core)? FS-internal delays are another story. The value is
142 * chosen based on the 32k block size. Given that peers typcially
143 * have at least 1 kb/s bandwidth, 45s waits give us a chance to
144 * transmit one message even to the lowest-bandwidth peers.
146 #define MAX_TRANSMIT_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 45)
149 * Maximum number of requests (from other peers, overall) that we're
150 * willing to have pending at any given point in time. Can be changed
151 * via the configuration file (32k is just the default).
153 static unsigned long long max_pending_requests = (32 * 1024);
156 * Information we keep for each pending reply. The
157 * actual message follows at the end of this struct.
159 struct PendingMessage;
162 * Function called upon completion of a transmission.
165 * @param pid ID of receiving peer, 0 on transmission error
167 typedef void (*TransmissionContinuation)(void * cls,
168 GNUNET_PEER_Id tpid);
172 * Information we keep for each pending message (GET/PUT). The
173 * actual message follows at the end of this struct.
175 struct PendingMessage
178 * This is a doubly-linked list of messages to the same peer.
180 struct PendingMessage *next;
183 * This is a doubly-linked list of messages to the same peer.
185 struct PendingMessage *prev;
188 * Entry in pending message list for this pending message.
190 struct PendingMessageList *pml;
193 * Function to call immediately once we have transmitted this
196 TransmissionContinuation cont;
204 * Do not transmit this pending message until this deadline.
206 struct GNUNET_TIME_Absolute delay_until;
209 * Size of the reply; actual reply message follows
210 * at the end of this struct.
215 * How important is this message for us?
223 * Information about a peer that we are connected to.
224 * We track data that is useful for determining which
225 * peers should receive our requests. We also keep
226 * a list of messages to transmit to this peer.
232 * List of the last clients for which this peer successfully
235 struct GNUNET_SERVER_Client *last_client_replies[CS2P_SUCCESS_LIST_SIZE];
238 * List of the last PIDs for which
239 * this peer successfully answered a query;
240 * We use 0 to indicate no successful reply.
242 GNUNET_PEER_Id last_p2p_replies[P2P_SUCCESS_LIST_SIZE];
245 * Average delay between sending the peer a request and
246 * getting a reply (only calculated over the requests for
247 * which we actually got a reply). Calculated
248 * as a moving average: new_delay = ((n-1)*last_delay+curr_delay) / n
250 struct GNUNET_TIME_Relative avg_delay;
253 * Point in time until which this peer does not want us to migrate content
256 struct GNUNET_TIME_Absolute migration_blocked;
259 * Time until when we blocked this peer from migrating
262 struct GNUNET_TIME_Absolute last_migration_block;
265 * Transmission times for the last MAX_QUEUE_PER_PEER
266 * requests for this peer. Used as a ring buffer, current
267 * offset is stored in 'last_request_times_off'. If the
268 * oldest entry is more recent than the 'avg_delay', we should
269 * not send any more requests right now.
271 struct GNUNET_TIME_Absolute last_request_times[MAX_QUEUE_PER_PEER];
274 * Handle for an active request for transmission to this
277 struct GNUNET_CORE_TransmitHandle *cth;
280 * Messages (replies, queries, content migration) we would like to
281 * send to this peer in the near future. Sorted by priority, head.
283 struct PendingMessage *pending_messages_head;
286 * Messages (replies, queries, content migration) we would like to
287 * send to this peer in the near future. Sorted by priority, tail.
289 struct PendingMessage *pending_messages_tail;
292 * How long does it typically take for us to transmit a message
293 * to this peer? (delay between the request being issued and
294 * the callback being invoked).
296 struct GNUNET_LOAD_Value *transmission_delay;
299 * Context of our GNUNET_CORE_peer_change_preference call (or NULL).
301 struct GNUNET_CORE_InformationRequestContext *irc;
304 * Request for which 'irc' is currently active (or NULL).
306 struct PendingRequest *pr;
309 * Time when the last transmission request was issued.
311 struct GNUNET_TIME_Absolute last_transmission_request_start;
314 * ID of delay task for scheduling transmission.
316 GNUNET_SCHEDULER_TaskIdentifier delayed_transmission_request_task;
319 * Average priority of successful replies. Calculated
320 * as a moving average: new_avg = ((n-1)*last_avg+curr_prio) / n
325 * Increase in traffic preference still to be submitted
326 * to the core service for this peer.
328 uint64_t inc_preference;
331 * Trust rating for this peer
336 * Trust rating for this peer on disk.
341 * The peer's identity.
346 * Size of the linked list of 'pending_messages'.
348 unsigned int pending_requests;
351 * Which offset in "last_p2p_replies" will be updated next?
352 * (we go round-robin).
354 unsigned int last_p2p_replies_woff;
357 * Which offset in "last_client_replies" will be updated next?
358 * (we go round-robin).
360 unsigned int last_client_replies_woff;
363 * Current offset into 'last_request_times' ring buffer.
365 unsigned int last_request_times_off;
371 * Information we keep for each pending request. We should try to
372 * keep this struct as small as possible since its memory consumption
373 * is key to how many requests we can have pending at once.
375 struct PendingRequest;
379 * Doubly-linked list of requests we are performing
380 * on behalf of the same client.
382 struct ClientRequestList
386 * This is a doubly-linked list.
388 struct ClientRequestList *next;
391 * This is a doubly-linked list.
393 struct ClientRequestList *prev;
396 * Request this entry represents.
398 struct PendingRequest *req;
401 * Client list this request belongs to.
403 struct ClientList *client_list;
409 * Replies to be transmitted to the client. The actual
410 * response message is allocated after this struct.
412 struct ClientResponseMessage
415 * This is a doubly-linked list.
417 struct ClientResponseMessage *next;
420 * This is a doubly-linked list.
422 struct ClientResponseMessage *prev;
425 * Client list entry this response belongs to.
427 struct ClientList *client_list;
430 * Number of bytes in the response.
437 * Linked list of clients we are performing requests
443 * This is a linked list.
445 struct ClientList *next;
450 struct GNUNET_SERVER_Client *client;
453 * Head of list of requests performed on behalf
454 * of this client right now.
456 struct ClientRequestList *rl_head;
459 * Tail of list of requests performed on behalf
460 * of this client right now.
462 struct ClientRequestList *rl_tail;
465 * Head of linked list of responses.
467 struct ClientResponseMessage *res_head;
470 * Tail of linked list of responses.
472 struct ClientResponseMessage *res_tail;
475 * Context for sending replies.
477 struct GNUNET_CONNECTION_TransmitHandle *th;
483 * Information about a peer that we have forwarded this
484 * request to already.
486 struct UsedTargetEntry
489 * What was the last time we have transmitted this request to this
492 struct GNUNET_TIME_Absolute last_request_time;
495 * How often have we transmitted this request to this peer?
497 unsigned int num_requests;
500 * PID of the target peer.
508 * Doubly-linked list of messages we are performing
509 * due to a pending request.
511 struct PendingMessageList
515 * This is a doubly-linked list of messages on behalf of the same request.
517 struct PendingMessageList *next;
520 * This is a doubly-linked list of messages on behalf of the same request.
522 struct PendingMessageList *prev;
525 * Message this entry represents.
527 struct PendingMessage *pm;
530 * Request this entry belongs to.
532 struct PendingRequest *req;
535 * Peer this message is targeted for.
537 struct ConnectedPeer *target;
543 * Information we keep for each pending request. We should try to
544 * keep this struct as small as possible since its memory consumption
545 * is key to how many requests we can have pending at once.
547 struct PendingRequest
551 * If this request was made by a client, this is our entry in the
552 * client request list; otherwise NULL.
554 struct ClientRequestList *client_request_list;
557 * Entry of peer responsible for this entry (if this request
558 * was made by a peer).
560 struct ConnectedPeer *cp;
563 * If this is a namespace query, pointer to the hash of the public
564 * key of the namespace; otherwise NULL. Pointer will be to the
565 * end of this struct (so no need to free it).
567 const GNUNET_HashCode *namespace;
570 * Bloomfilter we use to filter out replies that we don't care about
571 * (anymore). NULL as long as we are interested in all replies.
573 struct GNUNET_CONTAINER_BloomFilter *bf;
576 * Reference to DHT get operation for this request (or NULL).
578 struct GNUNET_DHT_GetHandle *dht_get;
581 * Context of our GNUNET_CORE_peer_change_preference call.
583 struct ConnectedPeer *pirc;
586 * Hash code of all replies that we have seen so far (only valid
587 * if client is not NULL since we only track replies like this for
590 GNUNET_HashCode *replies_seen;
593 * Node in the heap representing this entry; NULL
594 * if we have no heap node.
596 struct GNUNET_CONTAINER_HeapNode *hnode;
599 * Head of list of messages being performed on behalf of this
602 struct PendingMessageList *pending_head;
605 * Tail of list of messages being performed on behalf of this
608 struct PendingMessageList *pending_tail;
611 * When did we first see this request (form this peer), or, if our
612 * client is initiating, when did we last initiate a search?
614 struct GNUNET_TIME_Absolute start_time;
617 * The query that this request is for.
619 GNUNET_HashCode query;
622 * The task responsible for transmitting queries
625 GNUNET_SCHEDULER_TaskIdentifier task;
628 * (Interned) Peer identifier that identifies a preferred target
631 GNUNET_PEER_Id target_pid;
634 * (Interned) Peer identifiers of peers that have already
635 * received our query for this content.
637 struct UsedTargetEntry *used_targets;
640 * Our entry in the queue (non-NULL while we wait for our
641 * turn to interact with the local database).
643 struct GNUNET_DATASTORE_QueueEntry *qe;
646 * Size of the 'bf' (in bytes).
651 * Desired anonymity level; only valid for requests from a local client.
653 uint32_t anonymity_level;
656 * How many entries in "used_targets" are actually valid?
658 unsigned int used_targets_off;
661 * How long is the "used_targets" array?
663 unsigned int used_targets_size;
666 * Number of results found for this request.
668 unsigned int results_found;
671 * How many entries in "replies_seen" are actually valid?
673 unsigned int replies_seen_off;
676 * How long is the "replies_seen" array?
678 unsigned int replies_seen_size;
681 * Priority with which this request was made. If one of our clients
682 * made the request, then this is the current priority that we are
683 * using when initiating the request. This value is used when
684 * we decide to reward other peers with trust for providing a reply.
689 * Priority points left for us to spend when forwarding this request
692 uint32_t remaining_priority;
695 * Number to mingle hashes for bloom-filter tests with.
700 * TTL with which we saw this request (or, if we initiated, TTL that
701 * we used for the request).
706 * Type of the content that this request is for.
708 enum GNUNET_BLOCK_Type type;
711 * Remove this request after transmission of the current response.
716 * GNUNET_YES if we should not forward this request to other peers.
721 * GNUNET_YES if we should not forward this request to other peers. (HUH?)
729 * Block that is ready for migration to other peers. Actual data is at the end of the block.
731 struct MigrationReadyBlock
735 * This is a doubly-linked list.
737 struct MigrationReadyBlock *next;
740 * This is a doubly-linked list.
742 struct MigrationReadyBlock *prev;
745 * Query for the block.
747 GNUNET_HashCode query;
750 * When does this block expire?
752 struct GNUNET_TIME_Absolute expiration;
755 * Peers we would consider forwarding this
756 * block to. Zero for empty entries.
758 GNUNET_PEER_Id target_list[MIGRATION_LIST_SIZE];
766 * Number of targets already used.
768 unsigned int used_targets;
773 enum GNUNET_BLOCK_Type type;
777 * Identity of this peer.
779 static struct GNUNET_PeerIdentity my_id;
782 * Our connection to the datastore.
784 static struct GNUNET_DATASTORE_Handle *dsh;
789 static struct GNUNET_BLOCK_Context *block_ctx;
792 * Our block configuration.
794 static struct GNUNET_CONFIGURATION_Handle *block_cfg;
799 static const struct GNUNET_CONFIGURATION_Handle *cfg;
802 * Map of peer identifiers to "struct ConnectedPeer" (for that peer).
804 static struct GNUNET_CONTAINER_MultiHashMap *connected_peers;
807 * Map of peer identifiers to "struct PendingRequest" (for that peer).
809 static struct GNUNET_CONTAINER_MultiHashMap *peer_request_map;
812 * Map of query identifiers to "struct PendingRequest" (for that query).
814 static struct GNUNET_CONTAINER_MultiHashMap *query_request_map;
817 * Heap with the request that will expire next at the top. Contains
818 * pointers of type "struct PendingRequest*"; these will *also* be
819 * aliased from the "requests_by_peer" data structures and the
820 * "requests_by_query" table. Note that requests from our clients
821 * don't expire and are thus NOT in the "requests_by_expiration"
822 * (or the "requests_by_peer" tables).
824 static struct GNUNET_CONTAINER_Heap *requests_by_expiration_heap;
827 * Handle for reporting statistics.
829 static struct GNUNET_STATISTICS_Handle *stats;
832 * Linked list of clients we are currently processing requests for.
834 static struct ClientList *client_list;
837 * Pointer to handle to the core service (points to NULL until we've
840 static struct GNUNET_CORE_Handle *core;
843 * Head of linked list of blocks that can be migrated.
845 static struct MigrationReadyBlock *mig_head;
848 * Tail of linked list of blocks that can be migrated.
850 static struct MigrationReadyBlock *mig_tail;
853 * Request to datastore for migration (or NULL).
855 static struct GNUNET_DATASTORE_QueueEntry *mig_qe;
858 * Request to datastore for DHT PUTs (or NULL).
860 static struct GNUNET_DATASTORE_QueueEntry *dht_qe;
863 * Type we will request for the next DHT PUT round from the datastore.
865 static enum GNUNET_BLOCK_Type dht_put_type = GNUNET_BLOCK_TYPE_FS_KBLOCK;
868 * Where do we store trust information?
870 static char *trustDirectory;
873 * ID of task that collects blocks for migration.
875 static GNUNET_SCHEDULER_TaskIdentifier mig_task;
878 * ID of task that collects blocks for DHT PUTs.
880 static GNUNET_SCHEDULER_TaskIdentifier dht_task;
883 * What is the maximum frequency at which we are allowed to
884 * poll the datastore for migration content?
886 static struct GNUNET_TIME_Relative min_migration_delay;
889 * Handle for DHT operations.
891 static struct GNUNET_DHT_Handle *dht_handle;
894 * Size of the doubly-linked list of migration blocks.
896 static unsigned int mig_size;
899 * Are we allowed to migrate content to this peer.
901 static int active_to_migration;
904 * Are we allowed to push out content from this peer.
906 static int active_from_migration;
909 * How many entires with zero anonymity do we currently estimate
910 * to have in the database?
912 static unsigned int zero_anonymity_count_estimate;
915 * Typical priorities we're seeing from other peers right now. Since
916 * most priorities will be zero, this value is the weighted average of
917 * non-zero priorities seen "recently". In order to ensure that new
918 * values do not dramatically change the ratio, values are first
919 * "capped" to a reasonable range (+N of the current value) and then
920 * averaged into the existing value by a ratio of 1:N. Hence
921 * receiving the largest possible priority can still only raise our
922 * "current_priorities" by at most 1.
924 static double current_priorities;
927 * Datastore 'GET' load tracking.
929 static struct GNUNET_LOAD_Value *datastore_get_load;
932 * Datastore 'PUT' load tracking.
934 static struct GNUNET_LOAD_Value *datastore_put_load;
937 * How long do requests typically stay in the routing table?
939 static struct GNUNET_LOAD_Value *rt_entry_lifetime;
942 * How many query messages have we received 'recently' that
943 * have not yet been claimed as cover traffic?
945 static unsigned int cover_query_count;
948 * How many content messages have we received 'recently' that
949 * have not yet been claimed as cover traffic?
951 static unsigned int cover_content_count;
954 * ID of our task that we use to age the cover counters.
956 static GNUNET_SCHEDULER_TaskIdentifier cover_age_task;
959 age_cover_counters (void *cls,
960 const struct GNUNET_SCHEDULER_TaskContext *tc)
962 cover_content_count = (cover_content_count * 15) / 16;
963 cover_query_count = (cover_query_count * 15) / 16;
964 cover_age_task = GNUNET_SCHEDULER_add_delayed (COVER_AGE_FREQUENCY,
970 * We've just now completed a datastore request. Update our
971 * datastore load calculations.
973 * @param start time when the datastore request was issued
976 update_datastore_delays (struct GNUNET_TIME_Absolute start)
978 struct GNUNET_TIME_Relative delay;
980 delay = GNUNET_TIME_absolute_get_duration (start);
981 GNUNET_LOAD_update (datastore_get_load,
987 * Get the filename under which we would store the GNUNET_HELLO_Message
988 * for the given host and protocol.
989 * @return filename of the form DIRECTORY/HOSTID
992 get_trust_filename (const struct GNUNET_PeerIdentity *id)
994 struct GNUNET_CRYPTO_HashAsciiEncoded fil;
997 GNUNET_CRYPTO_hash_to_enc (&id->hashPubKey, &fil);
998 GNUNET_asprintf (&fn, "%s%s%s", trustDirectory, DIR_SEPARATOR_STR, &fil);
1005 * Transmit messages by copying it to the target buffer
1006 * "buf". "buf" will be NULL and "size" zero if the socket was closed
1007 * for writing in the meantime. In that case, do nothing
1008 * (the disconnect or shutdown handler will take care of the rest).
1009 * If we were able to transmit messages and there are still more
1010 * pending, ask core again for further calls to this function.
1012 * @param cls closure, pointer to the 'struct ConnectedPeer*'
1013 * @param size number of bytes available in buf
1014 * @param buf where the callee should write the message
1015 * @return number of bytes written to buf
1018 transmit_to_peer (void *cls,
1019 size_t size, void *buf);
1022 /* ******************* clean up functions ************************ */
1025 * Delete the given migration block.
1027 * @param mb block to delete
1030 delete_migration_block (struct MigrationReadyBlock *mb)
1032 GNUNET_CONTAINER_DLL_remove (mig_head,
1035 GNUNET_PEER_decrement_rcs (mb->target_list,
1036 MIGRATION_LIST_SIZE);
1043 * Compare the distance of two peers to a key.
1046 * @param p1 first peer
1047 * @param p2 second peer
1048 * @return GNUNET_YES if P1 is closer to key than P2
1051 is_closer (const GNUNET_HashCode *key,
1052 const struct GNUNET_PeerIdentity *p1,
1053 const struct GNUNET_PeerIdentity *p2)
1055 return GNUNET_CRYPTO_hash_xorcmp (&p1->hashPubKey,
1062 * Consider migrating content to a given peer.
1064 * @param cls 'struct MigrationReadyBlock*' to select
1065 * targets for (or NULL for none)
1066 * @param key ID of the peer
1067 * @param value 'struct ConnectedPeer' of the peer
1068 * @return GNUNET_YES (always continue iteration)
1071 consider_migration (void *cls,
1072 const GNUNET_HashCode *key,
1075 struct MigrationReadyBlock *mb = cls;
1076 struct ConnectedPeer *cp = value;
1077 struct MigrationReadyBlock *pos;
1078 struct GNUNET_PeerIdentity cppid;
1079 struct GNUNET_PeerIdentity otherpid;
1080 struct GNUNET_PeerIdentity worstpid;
1085 /* consider 'cp' as a migration target for mb */
1086 if (GNUNET_TIME_absolute_get_remaining (cp->migration_blocked).rel_value > 0)
1087 return GNUNET_YES; /* peer has requested no migration! */
1090 GNUNET_PEER_resolve (cp->pid,
1092 repl = MIGRATION_LIST_SIZE;
1093 for (i=0;i<MIGRATION_LIST_SIZE;i++)
1095 if (mb->target_list[i] == 0)
1097 mb->target_list[i] = cp->pid;
1098 GNUNET_PEER_change_rc (mb->target_list[i], 1);
1099 repl = MIGRATION_LIST_SIZE;
1102 GNUNET_PEER_resolve (mb->target_list[i],
1104 if ( (repl == MIGRATION_LIST_SIZE) &&
1105 is_closer (&mb->query,
1110 worstpid = otherpid;
1112 else if ( (repl != MIGRATION_LIST_SIZE) &&
1113 (is_closer (&mb->query,
1118 worstpid = otherpid;
1121 if (repl != MIGRATION_LIST_SIZE)
1123 GNUNET_PEER_change_rc (mb->target_list[repl], -1);
1124 mb->target_list[repl] = cp->pid;
1125 GNUNET_PEER_change_rc (mb->target_list[repl], 1);
1129 /* consider scheduling transmission to cp for content migration */
1130 if (cp->cth != NULL)
1136 for (i=0;i<MIGRATION_LIST_SIZE;i++)
1138 if (cp->pid == pos->target_list[i])
1143 msize = GNUNET_MIN (msize,
1151 return GNUNET_YES; /* no content available */
1153 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1154 "Trying to migrate at least %u bytes to peer `%s'\n",
1158 if (cp->delayed_transmission_request_task != GNUNET_SCHEDULER_NO_TASK)
1160 GNUNET_SCHEDULER_cancel (cp->delayed_transmission_request_task);
1161 cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
1164 = GNUNET_CORE_notify_transmit_ready (core,
1165 0, GNUNET_TIME_UNIT_FOREVER_REL,
1166 (const struct GNUNET_PeerIdentity*) key,
1167 msize + sizeof (struct PutMessage),
1175 * Task that is run periodically to obtain blocks for content
1179 * @param tc scheduler context (also unused)
1182 gather_migration_blocks (void *cls,
1183 const struct GNUNET_SCHEDULER_TaskContext *tc);
1189 * Task that is run periodically to obtain blocks for DHT PUTs.
1191 * @param cls type of blocks to gather
1192 * @param tc scheduler context (unused)
1195 gather_dht_put_blocks (void *cls,
1196 const struct GNUNET_SCHEDULER_TaskContext *tc);
1200 * If the migration task is not currently running, consider
1201 * (re)scheduling it with the appropriate delay.
1204 consider_migration_gathering ()
1206 struct GNUNET_TIME_Relative delay;
1212 if (mig_task != GNUNET_SCHEDULER_NO_TASK)
1214 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
1216 delay = GNUNET_TIME_relative_divide (delay,
1217 MAX_MIGRATION_QUEUE);
1218 delay = GNUNET_TIME_relative_max (delay,
1219 min_migration_delay);
1220 mig_task = GNUNET_SCHEDULER_add_delayed (delay,
1221 &gather_migration_blocks,
1227 * If the DHT PUT gathering task is not currently running, consider
1228 * (re)scheduling it with the appropriate delay.
1231 consider_dht_put_gathering (void *cls)
1233 struct GNUNET_TIME_Relative delay;
1239 if (dht_task != GNUNET_SCHEDULER_NO_TASK)
1241 if (zero_anonymity_count_estimate > 0)
1243 delay = GNUNET_TIME_relative_divide (GNUNET_DHT_DEFAULT_REPUBLISH_FREQUENCY,
1244 zero_anonymity_count_estimate);
1245 delay = GNUNET_TIME_relative_min (delay,
1250 /* if we have NO zero-anonymity content yet, wait 5 minutes for some to
1251 (hopefully) appear */
1252 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5);
1254 dht_task = GNUNET_SCHEDULER_add_delayed (delay,
1255 &gather_dht_put_blocks,
1261 * Process content offered for migration.
1263 * @param cls closure
1264 * @param key key for the content
1265 * @param size number of bytes in data
1266 * @param data content stored
1267 * @param type type of the content
1268 * @param priority priority of the content
1269 * @param anonymity anonymity-level for the content
1270 * @param expiration expiration time for the content
1271 * @param uid unique identifier for the datum;
1272 * maybe 0 if no unique identifier is available
1275 process_migration_content (void *cls,
1276 const GNUNET_HashCode * key,
1279 enum GNUNET_BLOCK_Type type,
1282 struct GNUNET_TIME_Absolute
1283 expiration, uint64_t uid)
1285 struct MigrationReadyBlock *mb;
1290 if (mig_size < MAX_MIGRATION_QUEUE)
1291 consider_migration_gathering ();
1294 if (GNUNET_TIME_absolute_get_remaining (expiration).rel_value <
1295 MIN_MIGRATION_CONTENT_LIFETIME.rel_value)
1297 /* content will expire soon, don't bother */
1298 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1301 if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
1304 GNUNET_FS_handle_on_demand_block (key, size, data,
1305 type, priority, anonymity,
1307 &process_migration_content,
1310 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1315 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1316 "Retrieved block `%s' of type %u for migration\n",
1320 mb = GNUNET_malloc (sizeof (struct MigrationReadyBlock) + size);
1322 mb->expiration = expiration;
1325 memcpy (&mb[1], data, size);
1326 GNUNET_CONTAINER_DLL_insert_after (mig_head,
1331 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1332 &consider_migration,
1334 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1339 * Function called upon completion of the DHT PUT operation.
1342 dht_put_continuation (void *cls,
1343 const struct GNUNET_SCHEDULER_TaskContext *tc)
1345 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1350 * Store content in DHT.
1352 * @param cls closure
1353 * @param key key for the content
1354 * @param size number of bytes in data
1355 * @param data content stored
1356 * @param type type of the content
1357 * @param priority priority of the content
1358 * @param anonymity anonymity-level for the content
1359 * @param expiration expiration time for the content
1360 * @param uid unique identifier for the datum;
1361 * maybe 0 if no unique identifier is available
1364 process_dht_put_content (void *cls,
1365 const GNUNET_HashCode * key,
1368 enum GNUNET_BLOCK_Type type,
1371 struct GNUNET_TIME_Absolute
1372 expiration, uint64_t uid)
1374 static unsigned int counter;
1375 static GNUNET_HashCode last_vhash;
1376 static GNUNET_HashCode vhash;
1381 consider_dht_put_gathering (cls);
1384 /* slightly funky code to estimate the total number of values with zero
1385 anonymity from the maximum observed length of a monotonically increasing
1386 sequence of hashes over the contents */
1387 GNUNET_CRYPTO_hash (data, size, &vhash);
1388 if (GNUNET_CRYPTO_hash_cmp (&vhash, &last_vhash) <= 0)
1390 if (zero_anonymity_count_estimate > 0)
1391 zero_anonymity_count_estimate /= 2;
1397 if (zero_anonymity_count_estimate < (1 << counter))
1398 zero_anonymity_count_estimate = (1 << counter);
1400 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1401 "Retrieved block `%s' of type %u for DHT PUT\n",
1405 GNUNET_DHT_put (dht_handle,
1407 DEFAULT_PUT_REPLICATION,
1413 GNUNET_TIME_UNIT_FOREVER_REL,
1414 &dht_put_continuation,
1420 * Task that is run periodically to obtain blocks for content
1424 * @param tc scheduler context (also unused)
1427 gather_migration_blocks (void *cls,
1428 const struct GNUNET_SCHEDULER_TaskContext *tc)
1430 mig_task = GNUNET_SCHEDULER_NO_TASK;
1433 mig_qe = GNUNET_DATASTORE_get_random (dsh, 0, UINT_MAX,
1434 GNUNET_TIME_UNIT_FOREVER_REL,
1435 &process_migration_content, NULL);
1436 GNUNET_assert (mig_qe != NULL);
1442 * Task that is run periodically to obtain blocks for DHT PUTs.
1444 * @param cls type of blocks to gather
1445 * @param tc scheduler context (unused)
1448 gather_dht_put_blocks (void *cls,
1449 const struct GNUNET_SCHEDULER_TaskContext *tc)
1451 dht_task = GNUNET_SCHEDULER_NO_TASK;
1454 if (dht_put_type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
1455 dht_put_type = GNUNET_BLOCK_TYPE_FS_KBLOCK;
1456 dht_qe = GNUNET_DATASTORE_get_zero_anonymity (dsh, 0, UINT_MAX,
1457 GNUNET_TIME_UNIT_FOREVER_REL,
1459 &process_dht_put_content, NULL);
1460 GNUNET_assert (dht_qe != NULL);
1466 * We're done with a particular message list entry.
1467 * Free all associated resources.
1469 * @param pml entry to destroy
1472 destroy_pending_message_list_entry (struct PendingMessageList *pml)
1474 GNUNET_CONTAINER_DLL_remove (pml->req->pending_head,
1475 pml->req->pending_tail,
1477 GNUNET_CONTAINER_DLL_remove (pml->target->pending_messages_head,
1478 pml->target->pending_messages_tail,
1480 GNUNET_assert (pml->target->pending_requests > 0);
1481 pml->target->pending_requests--;
1482 GNUNET_free (pml->pm);
1488 * Destroy the given pending message (and call the respective
1491 * @param pm message to destroy
1492 * @param tpid id of peer that the message was delivered to, or 0 for none
1495 destroy_pending_message (struct PendingMessage *pm,
1496 GNUNET_PEER_Id tpid)
1498 struct PendingMessageList *pml = pm->pml;
1499 TransmissionContinuation cont;
1503 cont_cls = pm->cont_cls;
1506 GNUNET_assert (pml->pm == pm);
1507 GNUNET_assert ( (tpid == 0) || (tpid == pml->target->pid) );
1508 destroy_pending_message_list_entry (pml);
1515 cont (cont_cls, tpid);
1520 * We're done processing a particular request.
1521 * Free all associated resources.
1523 * @param pr request to destroy
1526 destroy_pending_request (struct PendingRequest *pr)
1528 struct GNUNET_PeerIdentity pid;
1531 if (pr->hnode != NULL)
1533 GNUNET_CONTAINER_heap_remove_node (requests_by_expiration_heap,
1537 if (NULL == pr->client_request_list)
1539 GNUNET_STATISTICS_update (stats,
1540 gettext_noop ("# P2P searches active"),
1546 GNUNET_STATISTICS_update (stats,
1547 gettext_noop ("# client searches active"),
1552 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
1556 GNUNET_LOAD_update (rt_entry_lifetime,
1557 GNUNET_TIME_absolute_get_duration (pr->start_time).rel_value);
1561 GNUNET_DATASTORE_cancel (pr->qe);
1564 if (pr->dht_get != NULL)
1566 GNUNET_DHT_get_stop (pr->dht_get);
1569 if (pr->client_request_list != NULL)
1571 GNUNET_CONTAINER_DLL_remove (pr->client_request_list->client_list->rl_head,
1572 pr->client_request_list->client_list->rl_tail,
1573 pr->client_request_list);
1574 GNUNET_free (pr->client_request_list);
1575 pr->client_request_list = NULL;
1579 GNUNET_PEER_resolve (pr->cp->pid,
1581 (void) GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
1588 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
1591 if (pr->pirc != NULL)
1593 GNUNET_CORE_peer_change_preference_cancel (pr->pirc->irc);
1594 pr->pirc->irc = NULL;
1597 if (pr->replies_seen != NULL)
1599 GNUNET_free (pr->replies_seen);
1600 pr->replies_seen = NULL;
1602 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
1604 GNUNET_SCHEDULER_cancel (pr->task);
1605 pr->task = GNUNET_SCHEDULER_NO_TASK;
1607 while (NULL != pr->pending_head)
1608 destroy_pending_message_list_entry (pr->pending_head);
1609 GNUNET_PEER_change_rc (pr->target_pid, -1);
1610 if (pr->used_targets != NULL)
1612 for (i=0;i<pr->used_targets_off;i++)
1613 GNUNET_PEER_change_rc (pr->used_targets[i].pid, -1);
1614 GNUNET_free (pr->used_targets);
1615 pr->used_targets_off = 0;
1616 pr->used_targets_size = 0;
1617 pr->used_targets = NULL;
1624 * Find latency information in 'atsi'.
1626 * @param atsi performance data
1627 * @return connection latency
1629 static struct GNUNET_TIME_Relative
1630 get_latency (const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1633 return GNUNET_TIME_UNIT_SECONDS;
1634 while ( (ntohl (atsi->type) != GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR) &&
1635 (ntohl (atsi->type) != GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY) )
1637 if (ntohl (atsi->type) == GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR)
1640 /* how can we not have latency data? */
1641 return GNUNET_TIME_UNIT_SECONDS;
1643 return GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1644 ntohl (atsi->value));
1649 * Method called whenever a given peer connects.
1651 * @param cls closure, not used
1652 * @param peer peer identity this notification is about
1653 * @param atsi performance information
1656 peer_connect_handler (void *cls,
1658 GNUNET_PeerIdentity * peer,
1659 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1661 struct ConnectedPeer *cp;
1662 struct MigrationReadyBlock *pos;
1665 struct GNUNET_TIME_Relative latency;
1667 if (0 == memcmp (&my_id, peer, sizeof (struct GNUNET_PeerIdentity)))
1669 latency = get_latency (atsi);
1670 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1677 cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
1678 cp->transmission_delay = GNUNET_LOAD_value_init (latency);
1679 cp->pid = GNUNET_PEER_intern (peer);
1681 fn = get_trust_filename (peer);
1682 if ((GNUNET_DISK_file_test (fn) == GNUNET_YES) &&
1683 (sizeof (trust) == GNUNET_DISK_fn_read (fn, &trust, sizeof (trust))))
1684 cp->disk_trust = cp->trust = ntohl (trust);
1687 GNUNET_break (GNUNET_OK ==
1688 GNUNET_CONTAINER_multihashmap_put (connected_peers,
1691 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1696 (void) consider_migration (pos, &peer->hashPubKey, cp);
1703 * Method called whenever a given peer has a status change.
1705 * @param cls closure
1706 * @param peer peer identity this notification is about
1707 * @param bandwidth_in available amount of inbound bandwidth
1708 * @param bandwidth_out available amount of outbound bandwidth
1709 * @param timeout absolute time when this peer will time out
1710 * unless we see some further activity from it
1711 * @param atsi status information
1714 peer_status_handler (void *cls,
1716 GNUNET_PeerIdentity * peer,
1717 struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
1718 struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
1719 struct GNUNET_TIME_Absolute timeout,
1720 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1722 struct ConnectedPeer *cp;
1723 struct GNUNET_TIME_Relative latency;
1725 latency = get_latency (atsi);
1726 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1733 GNUNET_LOAD_value_set_decline (cp->transmission_delay,
1740 * Increase the host credit by a value.
1742 * @param host which peer to change the trust value on
1743 * @param value is the int value by which the
1744 * host credit is to be increased or decreased
1745 * @returns the actual change in trust (positive or negative)
1748 change_host_trust (struct ConnectedPeer *host, int value)
1752 GNUNET_assert (host != NULL);
1755 if (host->trust + value < host->trust)
1757 value = UINT32_MAX - host->trust;
1758 host->trust = UINT32_MAX;
1761 host->trust += value;
1765 if (host->trust < -value)
1767 value = -host->trust;
1771 host->trust += value;
1778 * Write host-trust information to a file - flush the buffer entry!
1781 flush_trust (void *cls,
1782 const GNUNET_HashCode *key,
1785 struct ConnectedPeer *host = value;
1788 struct GNUNET_PeerIdentity pid;
1790 if (host->trust == host->disk_trust)
1791 return GNUNET_OK; /* unchanged */
1792 GNUNET_PEER_resolve (host->pid,
1794 fn = get_trust_filename (&pid);
1795 if (host->trust == 0)
1797 if ((0 != UNLINK (fn)) && (errno != ENOENT))
1798 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
1799 GNUNET_ERROR_TYPE_BULK, "unlink", fn);
1803 trust = htonl (host->trust);
1804 if (sizeof(uint32_t) == GNUNET_DISK_fn_write (fn, &trust,
1806 GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE
1807 | GNUNET_DISK_PERM_GROUP_READ | GNUNET_DISK_PERM_OTHER_READ))
1808 host->disk_trust = host->trust;
1815 * Call this method periodically to scan data/hosts for new hosts.
1818 cron_flush_trust (void *cls,
1819 const struct GNUNET_SCHEDULER_TaskContext *tc)
1822 if (NULL == connected_peers)
1824 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1829 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1831 GNUNET_SCHEDULER_add_delayed (TRUST_FLUSH_FREQ, &cron_flush_trust, NULL);
1836 * Free (each) request made by the peer.
1838 * @param cls closure, points to peer that the request belongs to
1839 * @param key current key code
1840 * @param value value in the hash map
1841 * @return GNUNET_YES (we should continue to iterate)
1844 destroy_request (void *cls,
1845 const GNUNET_HashCode * key,
1848 const struct GNUNET_PeerIdentity * peer = cls;
1849 struct PendingRequest *pr = value;
1851 GNUNET_break (GNUNET_YES ==
1852 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
1855 destroy_pending_request (pr);
1861 * Method called whenever a peer disconnects.
1863 * @param cls closure, not used
1864 * @param peer peer identity this notification is about
1867 peer_disconnect_handler (void *cls,
1869 GNUNET_PeerIdentity * peer)
1871 struct ConnectedPeer *cp;
1872 struct PendingMessage *pm;
1874 struct MigrationReadyBlock *pos;
1875 struct MigrationReadyBlock *next;
1877 if (0 == memcmp (&my_id, peer, sizeof (struct GNUNET_PeerIdentity)))
1879 GNUNET_CONTAINER_multihashmap_get_multiple (peer_request_map,
1883 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1887 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1889 if (NULL != cp->last_client_replies[i])
1891 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1892 cp->last_client_replies[i] = NULL;
1895 GNUNET_break (GNUNET_YES ==
1896 GNUNET_CONTAINER_multihashmap_remove (connected_peers,
1899 if (cp->irc != NULL)
1901 GNUNET_CORE_peer_change_preference_cancel (cp->irc);
1903 cp->pr->pirc = NULL;
1907 /* remove this peer from migration considerations; schedule
1910 while (NULL != (pos = next))
1913 for (i=0;i<MIGRATION_LIST_SIZE;i++)
1915 if (pos->target_list[i] == cp->pid)
1917 GNUNET_PEER_change_rc (pos->target_list[i], -1);
1918 pos->target_list[i] = 0;
1921 if (pos->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers))
1923 delete_migration_block (pos);
1924 consider_migration_gathering ();
1927 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1928 &consider_migration,
1931 GNUNET_PEER_change_rc (cp->pid, -1);
1932 GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
1933 if (NULL != cp->cth)
1935 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
1938 if (cp->delayed_transmission_request_task != GNUNET_SCHEDULER_NO_TASK)
1940 GNUNET_SCHEDULER_cancel (cp->delayed_transmission_request_task);
1941 cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
1943 while (NULL != (pm = cp->pending_messages_head))
1944 destroy_pending_message (pm, 0 /* delivery failed */);
1945 GNUNET_LOAD_value_free (cp->transmission_delay);
1946 GNUNET_break (0 == cp->pending_requests);
1952 * Iterator over hash map entries that removes all occurences
1953 * of the given 'client' from the 'last_client_replies' of the
1954 * given connected peer.
1956 * @param cls closure, the 'struct GNUNET_SERVER_Client*' to remove
1957 * @param key current key code (unused)
1958 * @param value value in the hash map (the 'struct ConnectedPeer*' to change)
1959 * @return GNUNET_YES (we should continue to iterate)
1962 remove_client_from_last_client_replies (void *cls,
1963 const GNUNET_HashCode * key,
1966 struct GNUNET_SERVER_Client *client = cls;
1967 struct ConnectedPeer *cp = value;
1970 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1972 if (cp->last_client_replies[i] == client)
1974 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1975 cp->last_client_replies[i] = NULL;
1983 * A client disconnected. Remove all of its pending queries.
1985 * @param cls closure, NULL
1986 * @param client identification of the client
1989 handle_client_disconnect (void *cls,
1990 struct GNUNET_SERVER_Client
1993 struct ClientList *pos;
1994 struct ClientList *prev;
1995 struct ClientRequestList *rcl;
1996 struct ClientResponseMessage *creply;
2002 while ( (NULL != pos) &&
2003 (pos->client != client) )
2009 return; /* no requests pending for this client */
2010 while (NULL != (rcl = pos->rl_head))
2012 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2013 "Destroying pending request `%s' on disconnect\n",
2014 GNUNET_h2s (&rcl->req->query));
2015 destroy_pending_request (rcl->req);
2018 client_list = pos->next;
2020 prev->next = pos->next;
2021 if (pos->th != NULL)
2023 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
2026 while (NULL != (creply = pos->res_head))
2028 GNUNET_CONTAINER_DLL_remove (pos->res_head,
2031 GNUNET_free (creply);
2033 GNUNET_SERVER_client_drop (pos->client);
2035 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
2036 &remove_client_from_last_client_replies,
2042 * Iterator to free peer entries.
2044 * @param cls closure, unused
2045 * @param key current key code
2046 * @param value value in the hash map (peer entry)
2047 * @return GNUNET_YES (we should continue to iterate)
2050 clean_peer (void *cls,
2051 const GNUNET_HashCode * key,
2054 peer_disconnect_handler (NULL, (const struct GNUNET_PeerIdentity*) key);
2060 * Task run during shutdown.
2066 shutdown_task (void *cls,
2067 const struct GNUNET_SCHEDULER_TaskContext *tc)
2071 GNUNET_DATASTORE_cancel (mig_qe);
2076 GNUNET_DATASTORE_cancel (dht_qe);
2079 if (GNUNET_SCHEDULER_NO_TASK != mig_task)
2081 GNUNET_SCHEDULER_cancel (mig_task);
2082 mig_task = GNUNET_SCHEDULER_NO_TASK;
2084 if (GNUNET_SCHEDULER_NO_TASK != dht_task)
2086 GNUNET_SCHEDULER_cancel (dht_task);
2087 dht_task = GNUNET_SCHEDULER_NO_TASK;
2089 while (client_list != NULL)
2090 handle_client_disconnect (NULL,
2091 client_list->client);
2092 cron_flush_trust (NULL, NULL);
2093 GNUNET_assert (NULL != core);
2094 GNUNET_CORE_disconnect (core);
2096 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
2099 GNUNET_break (0 == GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap));
2100 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
2101 requests_by_expiration_heap = 0;
2102 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
2103 connected_peers = NULL;
2104 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (query_request_map));
2105 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
2106 query_request_map = NULL;
2107 GNUNET_LOAD_value_free (rt_entry_lifetime);
2108 rt_entry_lifetime = NULL;
2109 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (peer_request_map));
2110 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
2111 peer_request_map = NULL;
2114 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
2119 GNUNET_DATASTORE_disconnect (dsh,
2123 while (mig_head != NULL)
2124 delete_migration_block (mig_head);
2125 GNUNET_assert (0 == mig_size);
2126 GNUNET_DHT_disconnect (dht_handle);
2128 GNUNET_LOAD_value_free (datastore_get_load);
2129 datastore_get_load = NULL;
2130 GNUNET_LOAD_value_free (datastore_put_load);
2131 datastore_put_load = NULL;
2132 GNUNET_BLOCK_context_destroy (block_ctx);
2134 GNUNET_CONFIGURATION_destroy (block_cfg);
2137 GNUNET_free_non_null (trustDirectory);
2138 trustDirectory = NULL;
2139 GNUNET_SCHEDULER_cancel (cover_age_task);
2140 cover_age_task = GNUNET_SCHEDULER_NO_TASK;
2144 /* ******************* Utility functions ******************** */
2148 * We've had to delay a request for transmission to core, but now
2149 * we should be ready. Run it.
2151 * @param cls the 'struct ConnectedPeer' for which a request was delayed
2152 * @param tc task context (unused)
2155 delayed_transmission_request (void *cls,
2156 const struct GNUNET_SCHEDULER_TaskContext *tc)
2158 struct ConnectedPeer *cp = cls;
2159 struct GNUNET_PeerIdentity pid;
2160 struct PendingMessage *pm;
2162 pm = cp->pending_messages_head;
2163 cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
2164 GNUNET_assert (cp->cth == NULL);
2167 GNUNET_PEER_resolve (cp->pid,
2169 cp->last_transmission_request_start = GNUNET_TIME_absolute_get ();
2170 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
2172 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
2181 * Transmit messages by copying it to the target buffer
2182 * "buf". "buf" will be NULL and "size" zero if the socket was closed
2183 * for writing in the meantime. In that case, do nothing
2184 * (the disconnect or shutdown handler will take care of the rest).
2185 * If we were able to transmit messages and there are still more
2186 * pending, ask core again for further calls to this function.
2188 * @param cls closure, pointer to the 'struct ConnectedPeer*'
2189 * @param size number of bytes available in buf
2190 * @param buf where the callee should write the message
2191 * @return number of bytes written to buf
2194 transmit_to_peer (void *cls,
2195 size_t size, void *buf)
2197 struct ConnectedPeer *cp = cls;
2199 struct PendingMessage *pm;
2200 struct PendingMessage *next_pm;
2201 struct GNUNET_TIME_Absolute now;
2202 struct GNUNET_TIME_Relative min_delay;
2203 struct MigrationReadyBlock *mb;
2204 struct MigrationReadyBlock *next;
2205 struct PutMessage migm;
2208 struct GNUNET_PeerIdentity pid;
2214 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2215 "Dropping message, core too busy.\n");
2217 GNUNET_LOAD_update (cp->transmission_delay,
2220 if (NULL != (pm = cp->pending_messages_head))
2222 GNUNET_CONTAINER_DLL_remove (cp->pending_messages_head,
2223 cp->pending_messages_tail,
2225 GNUNET_assert (cp->pending_requests > 0);
2226 cp->pending_requests--;
2227 destroy_pending_message (pm, 0);
2229 if (NULL != (pm = cp->pending_messages_head))
2231 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == cp->delayed_transmission_request_task);
2232 min_delay = GNUNET_TIME_absolute_get_remaining (pm->delay_until);
2233 cp->delayed_transmission_request_task
2234 = GNUNET_SCHEDULER_add_delayed (min_delay,
2235 &delayed_transmission_request,
2240 GNUNET_LOAD_update (cp->transmission_delay,
2241 GNUNET_TIME_absolute_get_duration (cp->last_transmission_request_start).rel_value);
2242 now = GNUNET_TIME_absolute_get ();
2244 min_delay = GNUNET_TIME_UNIT_FOREVER_REL;
2245 next_pm = cp->pending_messages_head;
2246 while ( (NULL != (pm = next_pm) ) &&
2247 (pm->msize <= size) )
2250 if (pm->delay_until.abs_value > now.abs_value)
2252 min_delay = GNUNET_TIME_relative_min (min_delay,
2253 GNUNET_TIME_absolute_get_remaining (pm->delay_until));
2256 memcpy (&cbuf[msize], &pm[1], pm->msize);
2259 if (NULL == pm->pml)
2261 GNUNET_CONTAINER_DLL_remove (cp->pending_messages_head,
2262 cp->pending_messages_tail,
2264 GNUNET_assert (cp->pending_requests > 0);
2265 cp->pending_requests--;
2267 destroy_pending_message (pm, cp->pid);
2270 min_delay = GNUNET_TIME_UNIT_ZERO;
2271 if (NULL != cp->pending_messages_head)
2273 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == cp->delayed_transmission_request_task);
2274 cp->delayed_transmission_request_task
2275 = GNUNET_SCHEDULER_add_delayed (min_delay,
2276 &delayed_transmission_request,
2281 GNUNET_PEER_resolve (cp->pid,
2284 while (NULL != (mb = next))
2287 for (i=0;i<MIGRATION_LIST_SIZE;i++)
2289 if ( (cp->pid == mb->target_list[i]) &&
2290 (mb->size + sizeof (migm) <= size) )
2292 GNUNET_PEER_change_rc (mb->target_list[i], -1);
2293 mb->target_list[i] = 0;
2295 memset (&migm, 0, sizeof (migm));
2296 migm.header.size = htons (sizeof (migm) + mb->size);
2297 migm.header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2298 migm.type = htonl (mb->type);
2299 migm.expiration = GNUNET_TIME_absolute_hton (mb->expiration);
2300 memcpy (&cbuf[msize], &migm, sizeof (migm));
2301 msize += sizeof (migm);
2302 size -= sizeof (migm);
2303 memcpy (&cbuf[msize], &mb[1], mb->size);
2307 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2308 "Pushing migration block `%s' (%u bytes) to `%s'\n",
2309 GNUNET_h2s (&mb->query),
2310 (unsigned int) mb->size,
2318 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2319 "Migration block `%s' (%u bytes) is not on migration list for peer `%s'\n",
2320 GNUNET_h2s (&mb->query),
2321 (unsigned int) mb->size,
2326 if ( (mb->used_targets >= MIGRATION_TARGET_COUNT) ||
2327 (mb->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers)) )
2329 delete_migration_block (mb);
2330 consider_migration_gathering ();
2333 consider_migration (NULL,
2338 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2339 "Transmitting %u bytes to peer with PID %u\n",
2340 (unsigned int) msize,
2341 (unsigned int) cp->pid);
2348 * Add a message to the set of pending messages for the given peer.
2350 * @param cp peer to send message to
2351 * @param pm message to queue
2352 * @param pr request on which behalf this message is being queued
2355 add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
2356 struct PendingMessage *pm,
2357 struct PendingRequest *pr)
2359 struct PendingMessage *pos;
2360 struct PendingMessageList *pml;
2361 struct GNUNET_PeerIdentity pid;
2363 GNUNET_assert (pm->next == NULL);
2364 GNUNET_assert (pm->pml == NULL);
2367 pml = GNUNET_malloc (sizeof (struct PendingMessageList));
2372 GNUNET_CONTAINER_DLL_insert (pr->pending_head,
2376 pos = cp->pending_messages_head;
2377 while ( (pos != NULL) &&
2378 (pm->priority < pos->priority) )
2380 GNUNET_CONTAINER_DLL_insert_after (cp->pending_messages_head,
2381 cp->pending_messages_tail,
2384 cp->pending_requests++;
2385 if (cp->pending_requests > MAX_QUEUE_PER_PEER)
2387 GNUNET_STATISTICS_update (stats,
2388 gettext_noop ("# P2P searches discarded (queue length bound)"),
2391 destroy_pending_message (cp->pending_messages_tail, 0);
2393 GNUNET_PEER_resolve (cp->pid, &pid);
2394 if (NULL != cp->cth)
2396 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
2399 if (cp->delayed_transmission_request_task != GNUNET_SCHEDULER_NO_TASK)
2401 GNUNET_SCHEDULER_cancel (cp->delayed_transmission_request_task);
2402 cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
2404 /* need to schedule transmission */
2405 cp->last_transmission_request_start = GNUNET_TIME_absolute_get ();
2406 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
2407 cp->pending_messages_head->priority,
2410 cp->pending_messages_head->msize,
2413 if (cp->cth == NULL)
2416 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2417 "Failed to schedule transmission with core!\n");
2419 GNUNET_STATISTICS_update (stats,
2420 gettext_noop ("# CORE transmission failures"),
2428 * Test if the DATABASE (GET) load on this peer is too high
2429 * to even consider processing the query at
2432 * @return GNUNET_YES if the load is too high to do anything (load high)
2433 * GNUNET_NO to process normally (load normal)
2434 * GNUNET_SYSERR to process for free (load low)
2437 test_get_load_too_high (uint32_t priority)
2441 ld = GNUNET_LOAD_get_load (datastore_get_load);
2443 return GNUNET_SYSERR;
2453 * Test if the DATABASE (PUT) load on this peer is too high
2454 * to even consider processing the query at
2457 * @return GNUNET_YES if the load is too high to do anything (load high)
2458 * GNUNET_NO to process normally (load normal or low)
2461 test_put_load_too_high (uint32_t priority)
2465 if (GNUNET_LOAD_get_average (datastore_put_load) < 50)
2466 return GNUNET_NO; /* very fast */
2467 ld = GNUNET_LOAD_get_load (datastore_put_load);
2468 if (ld < 2.0 * (1 + priority))
2470 GNUNET_STATISTICS_update (stats,
2471 gettext_noop ("# storage requests dropped due to high load"),
2478 /* ******************* Pending Request Refresh Task ******************** */
2483 * We use a random delay to make the timing of requests less
2484 * predictable. This function returns such a random delay. We add a base
2485 * delay of MAX_CORK_DELAY (1s).
2487 * FIXME: make schedule dependent on the specifics of the request?
2488 * Or bandwidth and number of connected peers and load?
2490 * @return random delay to use for some request, between 1s and 1000+TTL_DECREMENT ms
2492 static struct GNUNET_TIME_Relative
2493 get_processing_delay ()
2496 GNUNET_TIME_relative_add (GNUNET_CONSTANTS_MAX_CORK_DELAY,
2497 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
2498 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2504 * We're processing a GET request from another peer and have decided
2505 * to forward it to other peers. This function is called periodically
2506 * and should forward the request to other peers until we have all
2507 * possible replies. If we have transmitted the *only* reply to
2508 * the initiator we should destroy the pending request. If we have
2509 * many replies in the queue to the initiator, we should delay sending
2510 * out more queries until the reply queue has shrunk some.
2512 * @param cls our "struct ProcessGetContext *"
2516 forward_request_task (void *cls,
2517 const struct GNUNET_SCHEDULER_TaskContext *tc);
2521 * Function called after we either failed or succeeded
2522 * at transmitting a query to a peer.
2524 * @param cls the requests "struct PendingRequest*"
2525 * @param tpid ID of receiving peer, 0 on transmission error
2528 transmit_query_continuation (void *cls,
2529 GNUNET_PEER_Id tpid)
2531 struct PendingRequest *pr = cls;
2534 GNUNET_STATISTICS_update (stats,
2535 gettext_noop ("# queries scheduled for forwarding"),
2541 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2542 "Transmission of request failed, will try again later.\n");
2544 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2545 pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2546 &forward_request_task,
2551 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2552 "Transmitted query `%s'\n",
2553 GNUNET_h2s (&pr->query));
2555 GNUNET_STATISTICS_update (stats,
2556 gettext_noop ("# queries forwarded"),
2559 for (i=0;i<pr->used_targets_off;i++)
2560 if (pr->used_targets[i].pid == tpid)
2561 break; /* found match! */
2562 if (i == pr->used_targets_off)
2564 /* need to create new entry */
2565 if (pr->used_targets_off == pr->used_targets_size)
2566 GNUNET_array_grow (pr->used_targets,
2567 pr->used_targets_size,
2568 pr->used_targets_size * 2 + 2);
2569 GNUNET_PEER_change_rc (tpid, 1);
2570 pr->used_targets[pr->used_targets_off].pid = tpid;
2571 pr->used_targets[pr->used_targets_off].num_requests = 0;
2572 i = pr->used_targets_off++;
2574 pr->used_targets[i].last_request_time = GNUNET_TIME_absolute_get ();
2575 pr->used_targets[i].num_requests++;
2576 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2577 pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2578 &forward_request_task,
2584 * How many bytes should a bloomfilter be if we have already seen
2585 * entry_count responses? Note that BLOOMFILTER_K gives us the number
2586 * of bits set per entry. Furthermore, we should not re-size the
2587 * filter too often (to keep it cheap).
2589 * Since other peers will also add entries but not resize the filter,
2590 * we should generally pick a slightly larger size than what the
2591 * strict math would suggest.
2593 * @return must be a power of two and smaller or equal to 2^15.
2596 compute_bloomfilter_size (unsigned int entry_count)
2599 unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
2600 uint16_t max = 1 << 15;
2602 if (entry_count > max)
2605 while ((size < max) && (size < ideal))
2614 * Recalculate our bloom filter for filtering replies. This function
2615 * will create a new bloom filter from scratch, so it should only be
2616 * called if we have no bloomfilter at all (and hence can create a
2617 * fresh one of minimal size without problems) OR if our peer is the
2618 * initiator (in which case we may resize to larger than mimimum size).
2620 * @param pr request for which the BF is to be recomputed
2623 refresh_bloomfilter (struct PendingRequest *pr)
2627 GNUNET_HashCode mhash;
2629 nsize = compute_bloomfilter_size (pr->replies_seen_off);
2630 if (nsize == pr->bf_size)
2631 return; /* size not changed */
2633 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
2634 pr->bf_size = nsize;
2635 pr->mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
2636 pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
2639 for (i=0;i<pr->replies_seen_off;i++)
2641 GNUNET_BLOCK_mingle_hash (&pr->replies_seen[i],
2644 GNUNET_CONTAINER_bloomfilter_add (pr->bf, &mhash);
2650 * Function called after we've tried to reserve a certain amount of
2651 * bandwidth for a reply. Check if we succeeded and if so send our
2654 * @param cls the requests "struct PendingRequest*"
2655 * @param peer identifies the peer
2656 * @param bpm_out set to the current bandwidth limit (sending) for this peer
2657 * @param amount set to the amount that was actually reserved or unreserved
2658 * @param preference current traffic preference for the given peer
2661 target_reservation_cb (void *cls,
2663 GNUNET_PeerIdentity * peer,
2664 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
2666 uint64_t preference)
2668 struct PendingRequest *pr = cls;
2669 struct ConnectedPeer *cp;
2670 struct PendingMessage *pm;
2671 struct GetMessage *gm;
2672 GNUNET_HashCode *ext;
2681 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2682 "Core called back... for query `%s'.\n",
2683 GNUNET_h2s (&pr->query));
2685 /* (3) transmit, update ttl/priority */
2686 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2690 /* Peer must have just left */
2692 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2693 "Selected peer disconnected!\n");
2695 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2696 pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2697 &forward_request_task,
2705 /* error in communication with core, try again later */
2706 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2707 pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2708 &forward_request_task,
2712 no_route = GNUNET_NO;
2718 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2719 "Failed to reserve bandwidth for reply (got %d/%u bytes only)!\n",
2723 GNUNET_STATISTICS_update (stats,
2724 gettext_noop ("# reply bandwidth reservation requests failed"),
2727 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2728 pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2729 &forward_request_task,
2731 return; /* this target round failed */
2733 no_route = GNUNET_YES;
2736 GNUNET_STATISTICS_update (stats,
2737 gettext_noop ("# queries scheduled for forwarding"),
2740 for (i=0;i<pr->used_targets_off;i++)
2741 if (pr->used_targets[i].pid == cp->pid)
2743 GNUNET_STATISTICS_update (stats,
2744 gettext_noop ("# queries retransmitted to same target"),
2750 /* build message and insert message into priority queue */
2752 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2753 "Forwarding request `%s' to `%4s'!\n",
2754 GNUNET_h2s (&pr->query),
2759 if (GNUNET_YES == no_route)
2761 bm |= GET_MESSAGE_BIT_RETURN_TO;
2764 if (pr->namespace != NULL)
2766 bm |= GET_MESSAGE_BIT_SKS_NAMESPACE;
2769 if (pr->target_pid != 0)
2771 bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
2774 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
2775 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
2776 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
2778 gm = (struct GetMessage*) &pm[1];
2779 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
2780 gm->header.size = htons (msize);
2781 gm->type = htonl (pr->type);
2782 pr->remaining_priority /= 2;
2783 gm->priority = htonl (pr->remaining_priority);
2784 gm->ttl = htonl (pr->ttl);
2785 gm->filter_mutator = htonl(pr->mingle);
2786 gm->hash_bitmap = htonl (bm);
2787 gm->query = pr->query;
2788 ext = (GNUNET_HashCode*) &gm[1];
2790 if (GNUNET_YES == no_route)
2791 GNUNET_PEER_resolve (pr->cp->pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
2792 if (pr->namespace != NULL)
2793 memcpy (&ext[k++], pr->namespace, sizeof (GNUNET_HashCode));
2794 if (pr->target_pid != 0)
2795 GNUNET_PEER_resolve (pr->target_pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
2796 bfdata = (char *) &ext[k];
2798 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
2801 pm->cont = &transmit_query_continuation;
2803 cp->last_request_times[(cp->last_request_times_off++) % MAX_QUEUE_PER_PEER] = GNUNET_TIME_absolute_get ();
2804 add_to_pending_messages_for_peer (cp, pm, pr);
2809 * Closure used for "target_peer_select_cb".
2811 struct PeerSelectionContext
2814 * The request for which we are selecting
2817 struct PendingRequest *pr;
2820 * Current "prime" target.
2822 struct GNUNET_PeerIdentity target;
2825 * How much do we like this target?
2827 double target_score;
2830 * Does it make sense to we re-try quickly again?
2838 * Function called for each connected peer to determine
2839 * which one(s) would make good targets for forwarding.
2841 * @param cls closure (struct PeerSelectionContext)
2842 * @param key current key code (peer identity)
2843 * @param value value in the hash map (struct ConnectedPeer)
2844 * @return GNUNET_YES if we should continue to
2849 target_peer_select_cb (void *cls,
2850 const GNUNET_HashCode * key,
2853 struct PeerSelectionContext *psc = cls;
2854 struct ConnectedPeer *cp = value;
2855 struct PendingRequest *pr = psc->pr;
2856 struct GNUNET_TIME_Relative delay;
2861 /* 1) check that this peer is not the initiator */
2865 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2866 "Skipping initiator in forwarding selection\n");
2868 return GNUNET_YES; /* skip */
2870 if (cp->irc != NULL)
2872 psc->fast_retry = GNUNET_YES;
2873 return GNUNET_YES; /* skip: already querying core about this peer for other reasons */
2876 /* 2) check if we have already (recently) forwarded to this peer */
2877 /* 2a) this particular request */
2879 for (i=0;i<pr->used_targets_off;i++)
2880 if (pr->used_targets[i].pid == cp->pid)
2882 pc = pr->used_targets[i].num_requests;
2883 GNUNET_assert (pc > 0);
2884 /* FIXME: make re-enabling a peer independent of how often
2885 this function is called??? */
2886 if (0 != GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2887 RETRY_PROBABILITY_INV * pc))
2890 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2891 "NOT re-trying query that was previously transmitted %u times\n",
2894 return GNUNET_YES; /* skip */
2901 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2902 "Re-trying query that was previously transmitted %u times to this peer\n",
2906 /* 2b) many other requests to this peer */
2907 delay = GNUNET_TIME_absolute_get_duration (cp->last_request_times[cp->last_request_times_off % MAX_QUEUE_PER_PEER]);
2908 if (delay.rel_value <= cp->avg_delay.rel_value)
2911 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2912 "NOT sending query since we send %u others to this peer in the last %llums\n",
2914 cp->avg_delay.rel_value);
2916 return GNUNET_YES; /* skip */
2919 /* 3) calculate how much we'd like to forward to this peer,
2920 starting with a random value that is strong enough
2921 to at least give any peer a chance sometimes
2922 (compared to the other factors that come later) */
2923 /* 3a) count successful (recent) routes from cp for same source */
2926 score = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2927 P2P_SUCCESS_LIST_SIZE);
2928 for (i=0;i<P2P_SUCCESS_LIST_SIZE;i++)
2929 if (cp->last_p2p_replies[i] == pr->cp->pid)
2930 score += 1.0; /* likely successful based on hot path */
2934 score = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2935 CS2P_SUCCESS_LIST_SIZE);
2936 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
2937 if (cp->last_client_replies[i] == pr->client_request_list->client_list->client)
2938 score += 1.0; /* likely successful based on hot path */
2940 /* 3b) include latency */
2941 if (cp->avg_delay.rel_value < 4 * TTL_DECREMENT)
2942 score += 1.0; /* likely fast based on latency */
2943 /* 3c) include priorities */
2944 if (cp->avg_priority <= pr->remaining_priority / 2.0)
2945 score += 1.0; /* likely successful based on priorities */
2946 /* 3d) penalize for queue size */
2947 score -= (2.0 * cp->pending_requests / (double) MAX_QUEUE_PER_PEER);
2948 /* 3e) include peer proximity */
2949 score -= (2.0 * (GNUNET_CRYPTO_hash_distance_u32 (key,
2950 &pr->query)) / (double) UINT32_MAX);
2951 /* 4) super-bonus for being the known target */
2952 if (pr->target_pid == cp->pid)
2954 /* store best-fit in closure */
2955 score++; /* avoid zero */
2956 if (score > psc->target_score)
2958 psc->target_score = score;
2959 psc->target.hashPubKey = *key;
2962 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2963 "Peer `%s' gets score %f for forwarding query, max is %8f\n",
2973 * The priority level imposes a bound on the maximum
2974 * value for the ttl that can be requested.
2976 * @param ttl_in requested ttl
2977 * @param prio given priority
2978 * @return ttl_in if ttl_in is below the limit,
2979 * otherwise the ttl-limit for the given priority
2982 bound_ttl (int32_t ttl_in, uint32_t prio)
2984 unsigned long long allowed;
2988 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
2989 if (ttl_in > allowed)
2991 if (allowed >= (1 << 30))
3000 * Iterator called on each result obtained for a DHT
3001 * operation that expects a reply
3003 * @param cls closure
3004 * @param exp when will this value expire
3005 * @param key key of the result
3006 * @param get_path NULL-terminated array of pointers
3007 * to the peers on reverse GET path (or NULL if not recorded)
3008 * @param put_path NULL-terminated array of pointers
3009 * to the peers on the PUT path (or NULL if not recorded)
3010 * @param type type of the result
3011 * @param size number of bytes in data
3012 * @param data pointer to the result data
3015 process_dht_reply (void *cls,
3016 struct GNUNET_TIME_Absolute exp,
3017 const GNUNET_HashCode * key,
3018 const struct GNUNET_PeerIdentity * const *get_path,
3019 const struct GNUNET_PeerIdentity * const *put_path,
3020 enum GNUNET_BLOCK_Type type,
3026 * We're processing a GET request and have decided
3027 * to forward it to other peers. This function is called periodically
3028 * and should forward the request to other peers until we have all
3029 * possible replies. If we have transmitted the *only* reply to
3030 * the initiator we should destroy the pending request. If we have
3031 * many replies in the queue to the initiator, we should delay sending
3032 * out more queries until the reply queue has shrunk some.
3034 * @param cls our "struct ProcessGetContext *"
3038 forward_request_task (void *cls,
3039 const struct GNUNET_SCHEDULER_TaskContext *tc)
3041 struct PendingRequest *pr = cls;
3042 struct PeerSelectionContext psc;
3043 struct ConnectedPeer *cp;
3044 struct GNUNET_TIME_Relative delay;
3046 pr->task = GNUNET_SCHEDULER_NO_TASK;
3047 if (pr->pirc != NULL)
3050 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3051 "Forwarding of query `%s' not attempted due to pending local lookup!\n",
3052 GNUNET_h2s (&pr->query));
3054 return; /* already pending */
3056 if (GNUNET_YES == pr->local_only)
3057 return; /* configured to not do P2P search */
3059 if ( (0 == pr->anonymity_level) &&
3060 (GNUNET_YES != pr->forward_only) &&
3061 (pr->type != GNUNET_BLOCK_TYPE_FS_DBLOCK) &&
3062 (pr->type != GNUNET_BLOCK_TYPE_FS_IBLOCK) )
3064 pr->dht_get = GNUNET_DHT_get_start (dht_handle,
3065 GNUNET_TIME_UNIT_FOREVER_REL,
3068 DEFAULT_GET_REPLICATION,
3073 (pr->namespace != NULL) ? sizeof (GNUNET_HashCode) : 0,
3078 if ( (pr->anonymity_level > 1) &&
3079 (cover_query_count < pr->anonymity_level - 1) )
3081 delay = get_processing_delay ();
3083 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3084 "Not enough cover traffic to forward query `%s', will try again in %llu ms!\n",
3085 GNUNET_h2s (&pr->query),
3088 pr->task = GNUNET_SCHEDULER_add_delayed (delay,
3089 &forward_request_task,
3093 /* consume cover traffic */
3094 if (pr->anonymity_level > 1)
3095 cover_query_count -= pr->anonymity_level - 1;
3097 /* (1) select target */
3099 psc.target_score = -DBL_MAX;
3100 psc.fast_retry = GNUNET_NO;
3101 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
3102 &target_peer_select_cb,
3104 if (psc.target_score == -DBL_MAX)
3106 if (psc.fast_retry == GNUNET_YES)
3107 delay = GNUNET_TIME_UNIT_MILLISECONDS; /* FIXME: store adaptive fast-retry value in 'pr' */
3109 delay = get_processing_delay ();
3111 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3112 "No peer selected for forwarding of query `%s', will try again in %llu ms!\n",
3113 GNUNET_h2s (&pr->query),
3116 pr->task = GNUNET_SCHEDULER_add_delayed (delay,
3117 &forward_request_task,
3119 return; /* nobody selected */
3121 /* (3) update TTL/priority */
3122 if (pr->client_request_list != NULL)
3124 /* FIXME: use better algorithm!? */
3125 if (0 == GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3128 /* bound priority we use by priorities we see from other peers
3129 rounded up (must round up so that we can see non-zero
3130 priorities, but round up as little as possible to make it
3131 plausible that we forwarded another peers request) */
3132 if (pr->priority > current_priorities + 1.0)
3133 pr->priority = (uint32_t) current_priorities + 1.0;
3134 pr->ttl = bound_ttl (pr->ttl + TTL_DECREMENT * 2,
3137 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3138 "Trying query `%s' with priority %u and TTL %d.\n",
3139 GNUNET_h2s (&pr->query),
3145 /* (3) reserve reply bandwidth */
3146 if (GNUNET_NO == pr->forward_only)
3148 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3149 &psc.target.hashPubKey);
3150 GNUNET_assert (NULL != cp);
3151 GNUNET_assert (cp->irc == NULL);
3155 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3156 "Asking core for bandwidth for query `%s'.\n",
3157 GNUNET_h2s (&pr->query));
3159 cp->irc = GNUNET_CORE_peer_change_preference (core,
3161 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
3162 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
3165 &target_reservation_cb,
3167 GNUNET_assert (cp->irc != NULL);
3168 cp->inc_preference = 0;
3172 /* force forwarding */
3173 static struct GNUNET_BANDWIDTH_Value32NBO zerobw;
3174 target_reservation_cb (pr, &psc.target,
3180 /* **************************** P2P PUT Handling ************************ */
3184 * Function called after we either failed or succeeded
3185 * at transmitting a reply to a peer.
3187 * @param cls the requests "struct PendingRequest*"
3188 * @param tpid ID of receiving peer, 0 on transmission error
3191 transmit_reply_continuation (void *cls,
3192 GNUNET_PEER_Id tpid)
3194 struct PendingRequest *pr = cls;
3198 case GNUNET_BLOCK_TYPE_FS_DBLOCK:
3199 case GNUNET_BLOCK_TYPE_FS_IBLOCK:
3200 /* only one reply expected, done with the request! */
3201 destroy_pending_request (pr);
3203 case GNUNET_BLOCK_TYPE_ANY:
3204 case GNUNET_BLOCK_TYPE_FS_KBLOCK:
3205 case GNUNET_BLOCK_TYPE_FS_SBLOCK:
3215 * Transmit the given message by copying it to the target buffer
3216 * "buf". "buf" will be NULL and "size" zero if the socket was closed
3217 * for writing in the meantime. In that case, do nothing
3218 * (the disconnect or shutdown handler will take care of the rest).
3219 * If we were able to transmit messages and there are still more
3220 * pending, ask core again for further calls to this function.
3222 * @param cls closure, pointer to the 'struct ClientList*'
3223 * @param size number of bytes available in buf
3224 * @param buf where the callee should write the message
3225 * @return number of bytes written to buf
3228 transmit_to_client (void *cls,
3229 size_t size, void *buf)
3231 struct ClientList *cl = cls;
3233 struct ClientResponseMessage *creply;
3240 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3241 "Not sending reply, client communication problem.\n");
3246 while ( (NULL != (creply = cl->res_head) ) &&
3247 (creply->msize <= size) )
3249 memcpy (&cbuf[msize], &creply[1], creply->msize);
3250 msize += creply->msize;
3251 size -= creply->msize;
3252 GNUNET_CONTAINER_DLL_remove (cl->res_head,
3255 GNUNET_free (creply);
3258 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
3260 GNUNET_TIME_UNIT_FOREVER_REL,
3261 &transmit_to_client,
3264 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3265 "Transmitted %u bytes to client\n",
3266 (unsigned int) msize);
3273 * Closure for "process_reply" function.
3275 struct ProcessReplyClosure
3278 * The data for the reply.
3283 * Who gave us this reply? NULL for local host (or DHT)
3285 struct ConnectedPeer *sender;
3288 * When the reply expires.
3290 struct GNUNET_TIME_Absolute expiration;
3298 * Type of the block.
3300 enum GNUNET_BLOCK_Type type;
3303 * How much was this reply worth to us?
3308 * Anonymity requirements for this reply.
3310 uint32_t anonymity_level;
3313 * Evaluation result (returned).
3315 enum GNUNET_BLOCK_EvaluationResult eval;
3318 * Did we finish processing the associated request?
3323 * Did we find a matching request?
3330 * We have received a reply; handle it!
3332 * @param cls response (struct ProcessReplyClosure)
3333 * @param key our query
3334 * @param value value in the hash map (info about the query)
3335 * @return GNUNET_YES (we should continue to iterate)
3338 process_reply (void *cls,
3339 const GNUNET_HashCode * key,
3342 struct ProcessReplyClosure *prq = cls;
3343 struct PendingRequest *pr = value;
3344 struct PendingMessage *reply;
3345 struct ClientResponseMessage *creply;
3346 struct ClientList *cl;
3347 struct PutMessage *pm;
3348 struct ConnectedPeer *cp;
3349 struct GNUNET_TIME_Relative cur_delay;
3351 struct GNUNET_TIME_Relative art_delay;
3356 if (NULL == pr->client_request_list)
3358 /* reply will go over the network, check for cover traffic */
3359 if ( (prq->anonymity_level > 1) &&
3360 (cover_content_count < prq->anonymity_level - 1) )
3362 /* insufficient cover traffic, skip */
3363 GNUNET_STATISTICS_update (stats,
3364 gettext_noop ("# replies suppressed due to lack of cover traffic"),
3369 if (prq->anonymity_level > 1)
3370 cover_content_count -= prq->anonymity_level - 1;
3373 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3374 "Matched result (type %u) for query `%s' with pending request\n",
3375 (unsigned int) prq->type,
3378 GNUNET_STATISTICS_update (stats,
3379 gettext_noop ("# replies received and matched"),
3382 if (prq->sender != NULL)
3384 for (i=0;i<pr->used_targets_off;i++)
3385 if (pr->used_targets[i].pid == prq->sender->pid)
3387 if (i < pr->used_targets_off)
3389 cur_delay = GNUNET_TIME_absolute_get_duration (pr->used_targets[i].last_request_time);
3390 prq->sender->avg_delay.rel_value
3391 = (prq->sender->avg_delay.rel_value *
3392 (RUNAVG_DELAY_N - 1) + cur_delay.rel_value) / RUNAVG_DELAY_N;
3393 prq->sender->avg_priority
3394 = (prq->sender->avg_priority *
3395 (RUNAVG_DELAY_N - 1) + pr->priority) / (double) RUNAVG_DELAY_N;
3399 GNUNET_PEER_change_rc (prq->sender->last_p2p_replies
3400 [prq->sender->last_p2p_replies_woff % P2P_SUCCESS_LIST_SIZE],
3402 GNUNET_PEER_change_rc (pr->cp->pid, 1);
3403 prq->sender->last_p2p_replies
3404 [(prq->sender->last_p2p_replies_woff++) % P2P_SUCCESS_LIST_SIZE]
3409 if (NULL != prq->sender->last_client_replies
3410 [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE])
3411 GNUNET_SERVER_client_drop (prq->sender->last_client_replies
3412 [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE]);
3413 prq->sender->last_client_replies
3414 [(prq->sender->last_client_replies_woff++) % CS2P_SUCCESS_LIST_SIZE]
3415 = pr->client_request_list->client_list->client;
3416 GNUNET_SERVER_client_keep (pr->client_request_list->client_list->client);
3419 prq->eval = GNUNET_BLOCK_evaluate (block_ctx,
3424 pr->namespace, (pr->namespace != NULL) ? sizeof (GNUNET_HashCode) : 0,
3429 case GNUNET_BLOCK_EVALUATION_OK_MORE:
3431 case GNUNET_BLOCK_EVALUATION_OK_LAST:
3432 while (NULL != pr->pending_head)
3433 destroy_pending_message_list_entry (pr->pending_head);
3436 if (pr->client_request_list != NULL)
3437 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
3439 GNUNET_DATASTORE_cancel (pr->qe);
3442 pr->do_remove = GNUNET_YES;
3443 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
3445 GNUNET_SCHEDULER_cancel (pr->task);
3446 pr->task = GNUNET_SCHEDULER_NO_TASK;
3448 GNUNET_break (GNUNET_YES ==
3449 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
3452 GNUNET_LOAD_update (rt_entry_lifetime,
3453 GNUNET_TIME_absolute_get_duration (pr->start_time).rel_value);
3455 case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
3456 GNUNET_STATISTICS_update (stats,
3457 gettext_noop ("# duplicate replies discarded (bloomfilter)"),
3461 /* GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3462 "Duplicate response `%s', discarding.\n",
3463 GNUNET_h2s (&mhash));*/
3465 return GNUNET_YES; /* duplicate */
3466 case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
3467 return GNUNET_YES; /* wrong namespace */
3468 case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
3471 case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
3474 case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
3475 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3476 _("Unsupported block type %u\n"),
3480 if (pr->client_request_list != NULL)
3482 if (pr->replies_seen_size == pr->replies_seen_off)
3483 GNUNET_array_grow (pr->replies_seen,
3484 pr->replies_seen_size,
3485 pr->replies_seen_size * 2 + 4);
3486 GNUNET_CRYPTO_hash (prq->data,
3488 &pr->replies_seen[pr->replies_seen_off++]);
3489 refresh_bloomfilter (pr);
3491 if (NULL == prq->sender)
3494 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3495 "Found result for query `%s' in local datastore\n",
3498 GNUNET_STATISTICS_update (stats,
3499 gettext_noop ("# results found locally"),
3503 prq->priority += pr->remaining_priority;
3504 pr->remaining_priority = 0;
3505 pr->results_found++;
3506 prq->request_found = GNUNET_YES;
3507 if (NULL != pr->client_request_list)
3509 GNUNET_STATISTICS_update (stats,
3510 gettext_noop ("# replies received for local clients"),
3513 cl = pr->client_request_list->client_list;
3514 msize = sizeof (struct PutMessage) + prq->size;
3515 creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
3516 creply->msize = msize;
3517 creply->client_list = cl;
3518 GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
3522 pm = (struct PutMessage*) &creply[1];
3523 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
3524 pm->header.size = htons (msize);
3525 pm->type = htonl (prq->type);
3526 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
3527 memcpy (&pm[1], prq->data, prq->size);
3531 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3532 "Transmitting result for query `%s' to client\n",
3535 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
3537 GNUNET_TIME_UNIT_FOREVER_REL,
3538 &transmit_to_client,
3541 GNUNET_break (cl->th != NULL);
3544 prq->finished = GNUNET_YES;
3545 destroy_pending_request (pr);
3552 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3553 "Transmitting result for query `%s' to other peer (PID=%u)\n",
3555 (unsigned int) cp->pid);
3557 GNUNET_STATISTICS_update (stats,
3558 gettext_noop ("# replies received for other peers"),
3561 msize = sizeof (struct PutMessage) + prq->size;
3562 reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
3563 reply->cont = &transmit_reply_continuation;
3564 reply->cont_cls = pr;
3566 art_delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
3567 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3570 = GNUNET_TIME_relative_to_absolute (art_delay);
3571 GNUNET_STATISTICS_update (stats,
3572 gettext_noop ("cummulative artificial delay introduced (ms)"),
3573 art_delay.abs_value,
3576 reply->msize = msize;
3577 reply->priority = UINT32_MAX; /* send replies first! */
3578 pm = (struct PutMessage*) &reply[1];
3579 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
3580 pm->header.size = htons (msize);
3581 pm->type = htonl (prq->type);
3582 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
3583 memcpy (&pm[1], prq->data, prq->size);
3584 add_to_pending_messages_for_peer (cp, reply, pr);
3591 * Iterator called on each result obtained for a DHT
3592 * operation that expects a reply
3594 * @param cls closure
3595 * @param exp when will this value expire
3596 * @param key key of the result
3597 * @param get_path NULL-terminated array of pointers
3598 * to the peers on reverse GET path (or NULL if not recorded)
3599 * @param put_path NULL-terminated array of pointers
3600 * to the peers on the PUT path (or NULL if not recorded)
3601 * @param type type of the result
3602 * @param size number of bytes in data
3603 * @param data pointer to the result data
3606 process_dht_reply (void *cls,
3607 struct GNUNET_TIME_Absolute exp,
3608 const GNUNET_HashCode * key,
3609 const struct GNUNET_PeerIdentity * const *get_path,
3610 const struct GNUNET_PeerIdentity * const *put_path,
3611 enum GNUNET_BLOCK_Type type,
3615 struct PendingRequest *pr = cls;
3616 struct ProcessReplyClosure prq;
3618 memset (&prq, 0, sizeof (prq));
3620 prq.expiration = exp;
3623 process_reply (&prq, key, pr);
3629 * Continuation called to notify client about result of the
3632 * @param cls closure
3633 * @param success GNUNET_SYSERR on failure
3634 * @param msg NULL on success, otherwise an error message
3637 put_migration_continuation (void *cls,
3641 struct GNUNET_TIME_Absolute *start = cls;
3642 struct GNUNET_TIME_Relative delay;
3644 delay = GNUNET_TIME_absolute_get_duration (*start);
3645 GNUNET_free (start);
3646 GNUNET_LOAD_update (datastore_put_load,
3648 if (GNUNET_OK == success)
3650 GNUNET_STATISTICS_update (stats,
3651 gettext_noop ("# datastore 'put' failures"),
3658 * Handle P2P "PUT" message.
3660 * @param cls closure, always NULL
3661 * @param other the other peer involved (sender or receiver, NULL
3662 * for loopback messages where we are both sender and receiver)
3663 * @param message the actual message
3664 * @param atsi performance information
3665 * @return GNUNET_OK to keep the connection open,
3666 * GNUNET_SYSERR to close it (signal serious error)
3669 handle_p2p_put (void *cls,
3670 const struct GNUNET_PeerIdentity *other,
3671 const struct GNUNET_MessageHeader *message,
3672 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
3674 const struct PutMessage *put;
3677 enum GNUNET_BLOCK_Type type;
3678 struct GNUNET_TIME_Absolute expiration;
3679 GNUNET_HashCode query;
3680 struct ProcessReplyClosure prq;
3681 struct GNUNET_TIME_Absolute *start;
3682 struct GNUNET_TIME_Relative block_time;
3684 struct ConnectedPeer *cp;
3685 struct PendingMessage *pm;
3686 struct MigrationStopMessage *msm;
3688 msize = ntohs (message->size);
3689 if (msize < sizeof (struct PutMessage))
3692 return GNUNET_SYSERR;
3694 put = (const struct PutMessage*) message;
3695 dsize = msize - sizeof (struct PutMessage);
3696 type = ntohl (put->type);
3697 expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
3699 if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
3700 return GNUNET_SYSERR;
3702 GNUNET_BLOCK_get_key (block_ctx,
3708 GNUNET_break_op (0);
3709 return GNUNET_SYSERR;
3711 cover_content_count++;
3713 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3714 "Received result for query `%s' from peer `%4s'\n",
3715 GNUNET_h2s (&query),
3716 GNUNET_i2s (other));
3718 GNUNET_STATISTICS_update (stats,
3719 gettext_noop ("# replies received (overall)"),
3722 /* now, lookup 'query' */
3723 prq.data = (const void*) &put[1];
3725 prq.sender = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3726 &other->hashPubKey);
3731 prq.expiration = expiration;
3733 prq.anonymity_level = 1;
3734 prq.finished = GNUNET_NO;
3735 prq.request_found = GNUNET_NO;
3736 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
3740 if (prq.sender != NULL)
3742 prq.sender->inc_preference += CONTENT_BANDWIDTH_VALUE + 1000 * prq.priority;
3743 change_host_trust (prq.sender, prq.priority);
3745 if ( (GNUNET_YES == active_to_migration) &&
3746 (GNUNET_NO == test_put_load_too_high (prq.priority)) )
3749 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3750 "Replicating result for query `%s' with priority %u\n",
3751 GNUNET_h2s (&query),
3754 start = GNUNET_malloc (sizeof (struct GNUNET_TIME_Absolute));
3755 *start = GNUNET_TIME_absolute_get ();
3756 GNUNET_DATASTORE_put (dsh,
3757 0, &query, dsize, &put[1],
3758 type, prq.priority, 1 /* anonymity */,
3760 1 + prq.priority, MAX_DATASTORE_QUEUE,
3761 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
3762 &put_migration_continuation,
3765 putl = GNUNET_LOAD_get_load (datastore_put_load);
3766 if ( (NULL != (cp = prq.sender)) &&
3767 (GNUNET_NO == prq.request_found) &&
3768 ( (GNUNET_YES != active_to_migration) ||
3769 (putl > 2.5 * (1 + prq.priority)) ) )
3771 if (GNUNET_TIME_absolute_get_duration (cp->last_migration_block).rel_value < 5000)
3772 return GNUNET_OK; /* already blocked */
3773 /* We're too busy; send MigrationStop message! */
3774 if (GNUNET_YES != active_to_migration)
3775 putl = 1.0 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 5);
3776 block_time = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
3777 5000 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3778 (unsigned int) (60000 * putl * putl)));
3780 cp->last_migration_block = GNUNET_TIME_relative_to_absolute (block_time);
3781 pm = GNUNET_malloc (sizeof (struct PendingMessage) +
3782 sizeof (struct MigrationStopMessage));
3783 pm->msize = sizeof (struct MigrationStopMessage);
3784 pm->priority = UINT32_MAX;
3785 msm = (struct MigrationStopMessage*) &pm[1];
3786 msm->header.size = htons (sizeof (struct MigrationStopMessage));
3787 msm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP);
3788 msm->duration = GNUNET_TIME_relative_hton (block_time);
3789 add_to_pending_messages_for_peer (cp,
3798 * Handle P2P "MIGRATION_STOP" message.
3800 * @param cls closure, always NULL
3801 * @param other the other peer involved (sender or receiver, NULL
3802 * for loopback messages where we are both sender and receiver)
3803 * @param message the actual message
3804 * @param atsi performance information
3805 * @return GNUNET_OK to keep the connection open,
3806 * GNUNET_SYSERR to close it (signal serious error)
3809 handle_p2p_migration_stop (void *cls,
3810 const struct GNUNET_PeerIdentity *other,
3811 const struct GNUNET_MessageHeader *message,
3812 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
3814 struct ConnectedPeer *cp;
3815 const struct MigrationStopMessage *msm;
3817 msm = (const struct MigrationStopMessage*) message;
3818 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3819 &other->hashPubKey);
3825 cp->migration_blocked = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (msm->duration));
3831 /* **************************** P2P GET Handling ************************ */
3835 * Closure for 'check_duplicate_request_{peer,client}'.
3837 struct CheckDuplicateRequestClosure
3840 * The new request we should check if it already exists.
3842 const struct PendingRequest *pr;
3845 * Existing request found by the checker, NULL if none.
3847 struct PendingRequest *have;
3852 * Iterator over entries in the 'query_request_map' that
3853 * tries to see if we have the same request pending from
3854 * the same client already.
3856 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
3857 * @param key current key code (query, ignored, must match)
3858 * @param value value in the hash map (a 'struct PendingRequest'
3859 * that already exists)
3860 * @return GNUNET_YES if we should continue to
3861 * iterate (no match yet)
3862 * GNUNET_NO if not (match found).
3865 check_duplicate_request_client (void *cls,
3866 const GNUNET_HashCode * key,
3869 struct CheckDuplicateRequestClosure *cdc = cls;
3870 struct PendingRequest *have = value;
3872 if (have->client_request_list == NULL)
3874 if ( (cdc->pr->client_request_list->client_list->client == have->client_request_list->client_list->client) &&
3885 * We're processing (local) results for a search request
3886 * from another peer. Pass applicable results to the
3887 * peer and if we are done either clean up (operation
3888 * complete) or forward to other peers (more results possible).
3890 * @param cls our closure (struct LocalGetContext)
3891 * @param key key for the content
3892 * @param size number of bytes in data
3893 * @param data content stored
3894 * @param type type of the content
3895 * @param priority priority of the content
3896 * @param anonymity anonymity-level for the content
3897 * @param expiration expiration time for the content
3898 * @param uid unique identifier for the datum;
3899 * maybe 0 if no unique identifier is available
3902 process_local_reply (void *cls,
3903 const GNUNET_HashCode * key,
3906 enum GNUNET_BLOCK_Type type,
3909 struct GNUNET_TIME_Absolute
3913 struct PendingRequest *pr = cls;
3914 struct ProcessReplyClosure prq;
3915 struct CheckDuplicateRequestClosure cdrc;
3916 GNUNET_HashCode query;
3917 unsigned int old_rf;
3922 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3923 "Done processing local replies, forwarding request to other peers.\n");
3926 if (pr->client_request_list != NULL)
3928 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
3930 /* Figure out if this is a duplicate request and possibly
3931 merge 'struct PendingRequest' entries */
3934 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
3936 &check_duplicate_request_client,
3938 if (cdrc.have != NULL)
3941 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3942 "Received request for block `%s' twice from client, will only request once.\n",
3943 GNUNET_h2s (&pr->query));
3946 destroy_pending_request (pr);
3950 if (pr->local_only == GNUNET_YES)
3952 destroy_pending_request (pr);
3955 /* no more results */
3956 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
3957 pr->task = GNUNET_SCHEDULER_add_now (&forward_request_task,
3962 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3963 "New local response to `%s' of type %u.\n",
3967 if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
3970 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3971 "Found ONDEMAND block, performing on-demand encoding\n");
3973 GNUNET_STATISTICS_update (stats,
3974 gettext_noop ("# on-demand blocks matched requests"),
3978 GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
3979 anonymity, expiration, uid,
3980 &process_local_reply,
3984 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3988 old_rf = pr->results_found;
3989 memset (&prq, 0, sizeof (prq));
3991 prq.expiration = expiration;
3994 GNUNET_BLOCK_get_key (block_ctx,
4001 GNUNET_DATASTORE_remove (dsh,
4005 GNUNET_TIME_UNIT_FOREVER_REL,
4007 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
4011 prq.priority = priority;
4012 prq.finished = GNUNET_NO;
4013 prq.request_found = GNUNET_NO;
4014 prq.anonymity_level = anonymity;
4015 if ( (old_rf == 0) &&
4016 (pr->results_found == 0) )
4017 update_datastore_delays (pr->start_time);
4018 process_reply (&prq, key, pr);
4019 if (prq.finished == GNUNET_YES)
4022 return; /* done here */
4023 if (prq.eval == GNUNET_BLOCK_EVALUATION_OK_LAST)
4025 pr->local_only = GNUNET_YES; /* do not forward */
4026 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
4029 if ( (pr->client_request_list == NULL) &&
4030 ( (GNUNET_YES == test_get_load_too_high (0)) ||
4031 (pr->results_found > 5 + 2 * pr->priority) ) )
4034 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4035 "Load too high, done with request\n");
4037 GNUNET_STATISTICS_update (stats,
4038 gettext_noop ("# processing result set cut short due to load"),
4041 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
4044 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
4049 * We've received a request with the specified priority. Bound it
4050 * according to how much we trust the given peer.
4052 * @param prio_in requested priority
4053 * @param cp the peer making the request
4054 * @return effective priority
4057 bound_priority (uint32_t prio_in,
4058 struct ConnectedPeer *cp)
4060 #define N ((double)128.0)
4065 ld = test_get_load_too_high (0);
4066 if (ld == GNUNET_SYSERR)
4068 GNUNET_STATISTICS_update (stats,
4069 gettext_noop ("# requests done for free (low load)"),
4072 return 0; /* excess resources */
4074 if (prio_in > INT32_MAX)
4075 prio_in = INT32_MAX;
4076 ret = - change_host_trust (cp, - (int) prio_in);
4079 if (ret > current_priorities + N)
4080 rret = current_priorities + N;
4084 = (current_priorities * (N-1) + rret)/N;
4086 if ( (ld == GNUNET_YES) && (ret > 0) )
4088 /* try with charging */
4089 ld = test_get_load_too_high (ret);
4091 if (ld == GNUNET_YES)
4093 GNUNET_STATISTICS_update (stats,
4094 gettext_noop ("# request dropped, priority insufficient"),
4098 change_host_trust (cp, (int) ret);
4099 return -1; /* not enough resources */
4103 GNUNET_STATISTICS_update (stats,
4104 gettext_noop ("# requests done for a price (normal load)"),
4114 * Iterator over entries in the 'query_request_map' that
4115 * tries to see if we have the same request pending from
4116 * the same peer already.
4118 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
4119 * @param key current key code (query, ignored, must match)
4120 * @param value value in the hash map (a 'struct PendingRequest'
4121 * that already exists)
4122 * @return GNUNET_YES if we should continue to
4123 * iterate (no match yet)
4124 * GNUNET_NO if not (match found).
4127 check_duplicate_request_peer (void *cls,
4128 const GNUNET_HashCode * key,
4131 struct CheckDuplicateRequestClosure *cdc = cls;
4132 struct PendingRequest *have = value;
4134 if (cdc->pr->target_pid == have->target_pid)
4144 * Handle P2P "GET" request.
4146 * @param cls closure, always NULL
4147 * @param other the other peer involved (sender or receiver, NULL
4148 * for loopback messages where we are both sender and receiver)
4149 * @param message the actual message
4150 * @param atsi performance information
4151 * @return GNUNET_OK to keep the connection open,
4152 * GNUNET_SYSERR to close it (signal serious error)
4155 handle_p2p_get (void *cls,
4156 const struct GNUNET_PeerIdentity *other,
4157 const struct GNUNET_MessageHeader *message,
4158 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
4160 struct PendingRequest *pr;
4161 struct ConnectedPeer *cp;
4162 struct ConnectedPeer *cps;
4163 struct CheckDuplicateRequestClosure cdc;
4164 struct GNUNET_TIME_Relative timeout;
4166 const struct GetMessage *gm;
4168 const GNUNET_HashCode *opt;
4171 uint32_t ttl_decrement;
4173 enum GNUNET_BLOCK_Type type;
4176 msize = ntohs(message->size);
4177 if (msize < sizeof (struct GetMessage))
4179 GNUNET_break_op (0);
4180 return GNUNET_SYSERR;
4182 gm = (const struct GetMessage*) message;
4184 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4185 "Received request for `%s'\n",
4186 GNUNET_h2s (&gm->query));
4188 type = ntohl (gm->type);
4189 bm = ntohl (gm->hash_bitmap);
4197 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
4199 GNUNET_break_op (0);
4200 return GNUNET_SYSERR;
4202 opt = (const GNUNET_HashCode*) &gm[1];
4203 bfsize = msize - sizeof (struct GetMessage) - bits * sizeof (GNUNET_HashCode);
4204 /* bfsize must be power of 2, check! */
4205 if (0 != ( (bfsize - 1) & bfsize))
4207 GNUNET_break_op (0);
4208 return GNUNET_SYSERR;
4210 cover_query_count++;
4211 bm = ntohl (gm->hash_bitmap);
4213 cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
4214 &other->hashPubKey);
4217 /* peer must have just disconnected */
4218 GNUNET_STATISTICS_update (stats,
4219 gettext_noop ("# requests dropped due to initiator not being connected"),
4222 return GNUNET_SYSERR;
4224 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
4225 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
4232 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
4233 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4234 "Failed to find RETURN-TO peer `%4s' in connection set. Dropping query.\n",
4235 GNUNET_i2s ((const struct GNUNET_PeerIdentity*) &opt[bits-1]));
4238 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4239 "Failed to find peer `%4s' in connection set. Dropping query.\n",
4240 GNUNET_i2s (other));
4242 GNUNET_STATISTICS_update (stats,
4243 gettext_noop ("# requests dropped due to missing reverse route"),
4246 /* FIXME: try connect? */
4249 /* note that we can really only check load here since otherwise
4250 peers could find out that we are overloaded by not being
4251 disconnected after sending us a malformed query... */
4252 priority = bound_priority (ntohl (gm->priority), cps);
4256 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4257 "Dropping query from `%s', this peer is too busy.\n",
4258 GNUNET_i2s (other));
4263 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4264 "Received request for `%s' of type %u from peer `%4s' with flags %u\n",
4265 GNUNET_h2s (&gm->query),
4266 (unsigned int) type,
4270 have_ns = (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE));
4271 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
4272 (have_ns ? sizeof(GNUNET_HashCode) : 0));
4275 pr->namespace = (GNUNET_HashCode*) &pr[1];
4276 memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
4278 if ( (GNUNET_LOAD_get_load (cp->transmission_delay) > 3 * (1 + priority)) ||
4279 (GNUNET_LOAD_get_average (cp->transmission_delay) >
4280 GNUNET_CONSTANTS_MAX_CORK_DELAY.rel_value * 2 + GNUNET_LOAD_get_average (rt_entry_lifetime)) )
4282 /* don't have BW to send to peer, or would likely take longer than we have for it,
4283 so at best indirect the query */
4285 pr->forward_only = GNUNET_YES;
4288 pr->mingle = ntohl (gm->filter_mutator);
4289 if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
4290 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
4291 pr->anonymity_level = 1;
4292 pr->priority = (uint32_t) priority;
4293 pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
4294 pr->query = gm->query;
4295 /* decrement ttl (always) */
4296 ttl_decrement = 2 * TTL_DECREMENT +
4297 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
4299 if ( (pr->ttl < 0) &&
4300 (((int32_t)(pr->ttl - ttl_decrement)) > 0) )
4303 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4304 "Dropping query from `%s' due to TTL underflow (%d - %u).\n",
4309 GNUNET_STATISTICS_update (stats,
4310 gettext_noop ("# requests dropped due TTL underflow"),
4313 /* integer underflow => drop (should be very rare)! */
4317 pr->ttl -= ttl_decrement;
4318 pr->start_time = GNUNET_TIME_absolute_get ();
4320 /* get bloom filter */
4323 pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
4326 pr->bf_size = bfsize;
4330 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
4332 &check_duplicate_request_peer,
4334 if (cdc.have != NULL)
4336 if (cdc.have->start_time.abs_value + cdc.have->ttl >=
4337 pr->start_time.abs_value + pr->ttl)
4339 /* existing request has higher TTL, drop new one! */
4340 cdc.have->priority += pr->priority;
4341 destroy_pending_request (pr);
4343 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4344 "Have existing request with higher TTL, dropping new request.\n",
4345 GNUNET_i2s (other));
4347 GNUNET_STATISTICS_update (stats,
4348 gettext_noop ("# requests dropped due to higher-TTL request"),
4355 /* existing request has lower TTL, drop old one! */
4356 pr->priority += cdc.have->priority;
4357 /* Possible optimization: if we have applicable pending
4358 replies in 'cdc.have', we might want to move those over
4359 (this is a really rare special-case, so it is not clear
4360 that this would be worth it) */
4361 destroy_pending_request (cdc.have);
4362 /* keep processing 'pr'! */
4367 GNUNET_break (GNUNET_OK ==
4368 GNUNET_CONTAINER_multihashmap_put (query_request_map,
4371 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
4372 GNUNET_break (GNUNET_OK ==
4373 GNUNET_CONTAINER_multihashmap_put (peer_request_map,
4376 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
4378 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
4380 pr->start_time.abs_value + pr->ttl);
4382 GNUNET_STATISTICS_update (stats,
4383 gettext_noop ("# P2P searches received"),
4386 GNUNET_STATISTICS_update (stats,
4387 gettext_noop ("# P2P searches active"),
4391 /* calculate change in traffic preference */
4392 cps->inc_preference += pr->priority * 1000 + QUERY_BANDWIDTH_VALUE;
4393 /* process locally */
4394 if (type == GNUNET_BLOCK_TYPE_FS_DBLOCK)
4395 type = GNUNET_BLOCK_TYPE_ANY; /* to get on-demand as well */
4396 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
4397 (pr->priority + 1));
4398 if (GNUNET_YES != pr->forward_only)
4401 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4402 "Handing request for `%s' to datastore\n",
4403 GNUNET_h2s (&gm->query));
4405 pr->qe = GNUNET_DATASTORE_get (dsh,
4409 MAX_DATASTORE_QUEUE,
4411 &process_local_reply,
4415 GNUNET_STATISTICS_update (stats,
4416 gettext_noop ("# requests dropped by datastore (queue length limit)"),
4423 GNUNET_STATISTICS_update (stats,
4424 gettext_noop ("# requests forwarded due to high load"),
4429 /* Are multiple results possible (and did we look locally)? If so, start processing remotely now! */
4432 case GNUNET_BLOCK_TYPE_FS_DBLOCK:
4433 case GNUNET_BLOCK_TYPE_FS_IBLOCK:
4434 /* only one result, wait for datastore */
4435 if (GNUNET_YES != pr->forward_only)
4437 GNUNET_STATISTICS_update (stats,
4438 gettext_noop ("# requests not instantly forwarded (waiting for datastore)"),
4444 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
4445 pr->task = GNUNET_SCHEDULER_add_now (&forward_request_task,
4449 /* make sure we don't track too many requests */
4450 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
4452 pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
4453 GNUNET_assert (pr != NULL);
4454 destroy_pending_request (pr);
4460 /* **************************** CS GET Handling ************************ */
4464 * Handle START_SEARCH-message (search request from client).
4466 * @param cls closure
4467 * @param client identification of the client
4468 * @param message the actual message
4471 handle_start_search (void *cls,
4472 struct GNUNET_SERVER_Client *client,
4473 const struct GNUNET_MessageHeader *message)
4475 static GNUNET_HashCode all_zeros;
4476 const struct SearchMessage *sm;
4477 struct ClientList *cl;
4478 struct ClientRequestList *crl;
4479 struct PendingRequest *pr;
4482 enum GNUNET_BLOCK_Type type;
4484 msize = ntohs (message->size);
4485 if ( (msize < sizeof (struct SearchMessage)) ||
4486 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
4489 GNUNET_SERVER_receive_done (client,
4493 GNUNET_STATISTICS_update (stats,
4494 gettext_noop ("# client searches received"),
4497 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
4498 sm = (const struct SearchMessage*) message;
4499 type = ntohl (sm->type);
4501 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4502 "Received request for `%s' of type %u from local client\n",
4503 GNUNET_h2s (&sm->query),
4504 (unsigned int) type);
4507 while ( (cl != NULL) &&
4508 (cl->client != client) )
4512 cl = GNUNET_malloc (sizeof (struct ClientList));
4513 cl->client = client;
4514 GNUNET_SERVER_client_keep (client);
4515 cl->next = client_list;
4518 /* detect duplicate KBLOCK requests */
4519 if ( (type == GNUNET_BLOCK_TYPE_FS_KBLOCK) ||
4520 (type == GNUNET_BLOCK_TYPE_FS_NBLOCK) ||
4521 (type == GNUNET_BLOCK_TYPE_ANY) )
4524 while ( (crl != NULL) &&
4525 ( (0 != memcmp (&crl->req->query,
4527 sizeof (GNUNET_HashCode))) ||
4528 (crl->req->type != type) ) )
4533 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4534 "Have existing request, merging content-seen lists.\n");
4537 /* Duplicate request (used to send long list of
4538 known/blocked results); merge 'pr->replies_seen'
4539 and update bloom filter */
4540 GNUNET_array_grow (pr->replies_seen,
4541 pr->replies_seen_size,
4542 pr->replies_seen_off + sc);
4543 memcpy (&pr->replies_seen[pr->replies_seen_off],
4545 sc * sizeof (GNUNET_HashCode));
4546 pr->replies_seen_off += sc;
4547 refresh_bloomfilter (pr);
4548 GNUNET_STATISTICS_update (stats,
4549 gettext_noop ("# client searches updated (merged content seen list)"),
4552 GNUNET_SERVER_receive_done (client,
4557 GNUNET_STATISTICS_update (stats,
4558 gettext_noop ("# client searches active"),
4561 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
4562 ((type == GNUNET_BLOCK_TYPE_FS_SBLOCK) ? sizeof(GNUNET_HashCode) : 0));
4563 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
4564 memset (crl, 0, sizeof (struct ClientRequestList));
4565 crl->client_list = cl;
4566 GNUNET_CONTAINER_DLL_insert (cl->rl_head,
4571 pr->client_request_list = crl;
4572 GNUNET_array_grow (pr->replies_seen,
4573 pr->replies_seen_size,
4575 memcpy (pr->replies_seen,
4577 sc * sizeof (GNUNET_HashCode));
4578 pr->replies_seen_off = sc;
4579 pr->anonymity_level = ntohl (sm->anonymity_level);
4580 pr->start_time = GNUNET_TIME_absolute_get ();
4581 refresh_bloomfilter (pr);
4582 pr->query = sm->query;
4583 if (0 == (1 & ntohl (sm->options)))
4584 pr->local_only = GNUNET_NO;
4586 pr->local_only = GNUNET_YES;
4589 case GNUNET_BLOCK_TYPE_FS_DBLOCK:
4590 case GNUNET_BLOCK_TYPE_FS_IBLOCK:
4591 if (0 != memcmp (&sm->target,
4593 sizeof (GNUNET_HashCode)))
4594 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
4596 case GNUNET_BLOCK_TYPE_FS_SBLOCK:
4597 pr->namespace = (GNUNET_HashCode*) &pr[1];
4598 memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
4603 GNUNET_break (GNUNET_OK ==
4604 GNUNET_CONTAINER_multihashmap_put (query_request_map,
4607 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
4608 if (type == GNUNET_BLOCK_TYPE_FS_DBLOCK)
4609 type = GNUNET_BLOCK_TYPE_ANY; /* get on-demand blocks too! */
4610 pr->qe = GNUNET_DATASTORE_get (dsh,
4614 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
4615 &process_local_reply,
4620 /* **************************** Startup ************************ */
4625 * Function called after GNUNET_CORE_connect has succeeded
4626 * (or failed for good). Note that the private key of the
4627 * peer is intentionally not exposed here; if you need it,
4628 * your process should try to read the private key file
4629 * directly (which should work if you are authorized...).
4631 * @param cls closure
4632 * @param server handle to the server, NULL if we failed
4633 * @param my_identity ID of this peer, NULL if we failed
4634 * @param publicKey public key of this peer, NULL if we failed
4637 peer_init_handler (void *cls,
4638 struct GNUNET_CORE_Handle * server,
4639 const struct GNUNET_PeerIdentity *
4642 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *
4645 my_id = *my_identity;
4652 * Process fs requests.
4654 * @param server the initialized server
4655 * @param c configuration to use
4658 main_init (struct GNUNET_SERVER_Handle *server,
4659 const struct GNUNET_CONFIGURATION_Handle *c)
4661 static const struct GNUNET_CORE_MessageHandler p2p_handlers[] =
4664 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
4666 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
4667 { &handle_p2p_migration_stop,
4668 GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP,
4669 sizeof (struct MigrationStopMessage) },
4672 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
4673 {&GNUNET_FS_handle_index_start, NULL,
4674 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
4675 {&GNUNET_FS_handle_index_list_get, NULL,
4676 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
4677 {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
4678 sizeof (struct UnindexMessage) },
4679 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
4683 unsigned long long enc = 128;
4686 stats = GNUNET_STATISTICS_create ("fs", cfg);
4687 min_migration_delay = GNUNET_TIME_UNIT_SECONDS;
4689 GNUNET_CONFIGURATION_get_value_number (cfg,
4691 "MAX_PENDING_REQUESTS",
4692 &max_pending_requests)) ||
4694 GNUNET_CONFIGURATION_get_value_number (cfg,
4696 "EXPECTED_NEIGHBOUR_COUNT",
4699 GNUNET_CONFIGURATION_get_value_time (cfg,
4701 "MIN_MIGRATION_DELAY",
4702 &min_migration_delay)) )
4704 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4705 _("Configuration fails to specify certain parameters, assuming default values."));
4707 connected_peers = GNUNET_CONTAINER_multihashmap_create (enc);
4708 query_request_map = GNUNET_CONTAINER_multihashmap_create (max_pending_requests);
4709 rt_entry_lifetime = GNUNET_LOAD_value_init (GNUNET_TIME_UNIT_FOREVER_REL);
4710 peer_request_map = GNUNET_CONTAINER_multihashmap_create (enc);
4711 requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
4712 core = GNUNET_CORE_connect (cfg,
4716 &peer_connect_handler,
4717 &peer_disconnect_handler,
4718 &peer_status_handler,
4724 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4725 _("Failed to connect to `%s' service.\n"),
4727 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
4728 connected_peers = NULL;
4729 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
4730 query_request_map = NULL;
4731 GNUNET_LOAD_value_free (rt_entry_lifetime);
4732 rt_entry_lifetime = NULL;
4733 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
4734 requests_by_expiration_heap = NULL;
4735 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
4736 peer_request_map = NULL;
4739 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
4742 return GNUNET_SYSERR;
4744 if (active_from_migration)
4746 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4747 _("Content migration is enabled, will start to gather data\n"));
4748 consider_migration_gathering ();
4750 consider_dht_put_gathering (NULL);
4751 GNUNET_SERVER_disconnect_notify (server,
4752 &handle_client_disconnect,
4754 GNUNET_assert (GNUNET_OK ==
4755 GNUNET_CONFIGURATION_get_value_filename (cfg,
4759 GNUNET_DISK_directory_create (trustDirectory);
4760 GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_HIGH,
4761 &cron_flush_trust, NULL);
4764 GNUNET_SERVER_add_handlers (server, handlers);
4765 cover_age_task = GNUNET_SCHEDULER_add_delayed (COVER_AGE_FREQUENCY,
4766 &age_cover_counters,
4768 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4776 * Process fs requests.
4778 * @param cls closure
4779 * @param server the initialized server
4780 * @param cfg configuration to use
4784 struct GNUNET_SERVER_Handle *server,
4785 const struct GNUNET_CONFIGURATION_Handle *cfg)
4787 active_to_migration = GNUNET_CONFIGURATION_get_value_yesno (cfg,
4790 active_from_migration = GNUNET_CONFIGURATION_get_value_yesno (cfg,
4793 dsh = GNUNET_DATASTORE_connect (cfg);
4796 GNUNET_SCHEDULER_shutdown ();
4799 datastore_get_load = GNUNET_LOAD_value_init (DATASTORE_LOAD_AUTODECLINE);
4800 datastore_put_load = GNUNET_LOAD_value_init (DATASTORE_LOAD_AUTODECLINE);
4801 block_cfg = GNUNET_CONFIGURATION_create ();
4802 GNUNET_CONFIGURATION_set_value_string (block_cfg,
4806 block_ctx = GNUNET_BLOCK_context_create (block_cfg);
4807 GNUNET_assert (NULL != block_ctx);
4808 dht_handle = GNUNET_DHT_connect (cfg,
4810 if ( (GNUNET_OK != GNUNET_FS_indexing_init (cfg, dsh)) ||
4811 (GNUNET_OK != main_init (server, cfg)) )
4813 GNUNET_SCHEDULER_shutdown ();
4814 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
4816 GNUNET_DHT_disconnect (dht_handle);
4818 GNUNET_BLOCK_context_destroy (block_ctx);
4820 GNUNET_CONFIGURATION_destroy (block_cfg);
4822 GNUNET_LOAD_value_free (datastore_get_load);
4823 datastore_get_load = NULL;
4824 GNUNET_LOAD_value_free (datastore_put_load);
4825 datastore_put_load = NULL;
4832 * The main function for the fs service.
4834 * @param argc number of arguments from the command line
4835 * @param argv command line arguments
4836 * @return 0 ok, 1 on error
4839 main (int argc, char *const *argv)
4841 return (GNUNET_OK ==
4842 GNUNET_SERVICE_run (argc,
4845 GNUNET_SERVICE_OPTION_NONE,
4846 &run, NULL)) ? 0 : 1;
4849 /* end of gnunet-service-fs.c */