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;
960 age_cover_counters (void *cls,
961 const struct GNUNET_SCHEDULER_TaskContext *tc)
963 cover_content_count = (cover_content_count * 15) / 16;
964 cover_query_count = (cover_query_count * 15) / 16;
965 cover_age_task = GNUNET_SCHEDULER_add_delayed (COVER_AGE_FREQUENCY,
971 * We've just now completed a datastore request. Update our
972 * datastore load calculations.
974 * @param start time when the datastore request was issued
977 update_datastore_delays (struct GNUNET_TIME_Absolute start)
979 struct GNUNET_TIME_Relative delay;
981 delay = GNUNET_TIME_absolute_get_duration (start);
982 GNUNET_LOAD_update (datastore_get_load,
988 * Get the filename under which we would store the GNUNET_HELLO_Message
989 * for the given host and protocol.
990 * @return filename of the form DIRECTORY/HOSTID
993 get_trust_filename (const struct GNUNET_PeerIdentity *id)
995 struct GNUNET_CRYPTO_HashAsciiEncoded fil;
998 GNUNET_CRYPTO_hash_to_enc (&id->hashPubKey, &fil);
999 GNUNET_asprintf (&fn, "%s%s%s", trustDirectory, DIR_SEPARATOR_STR, &fil);
1006 * Transmit messages by copying it to the target buffer
1007 * "buf". "buf" will be NULL and "size" zero if the socket was closed
1008 * for writing in the meantime. In that case, do nothing
1009 * (the disconnect or shutdown handler will take care of the rest).
1010 * If we were able to transmit messages and there are still more
1011 * pending, ask core again for further calls to this function.
1013 * @param cls closure, pointer to the 'struct ConnectedPeer*'
1014 * @param size number of bytes available in buf
1015 * @param buf where the callee should write the message
1016 * @return number of bytes written to buf
1019 transmit_to_peer (void *cls,
1020 size_t size, void *buf);
1023 /* ******************* clean up functions ************************ */
1026 * Delete the given migration block.
1028 * @param mb block to delete
1031 delete_migration_block (struct MigrationReadyBlock *mb)
1033 GNUNET_CONTAINER_DLL_remove (mig_head,
1036 GNUNET_PEER_decrement_rcs (mb->target_list,
1037 MIGRATION_LIST_SIZE);
1044 * Compare the distance of two peers to a key.
1047 * @param p1 first peer
1048 * @param p2 second peer
1049 * @return GNUNET_YES if P1 is closer to key than P2
1052 is_closer (const GNUNET_HashCode *key,
1053 const struct GNUNET_PeerIdentity *p1,
1054 const struct GNUNET_PeerIdentity *p2)
1056 return GNUNET_CRYPTO_hash_xorcmp (&p1->hashPubKey,
1063 * Consider migrating content to a given peer.
1065 * @param cls 'struct MigrationReadyBlock*' to select
1066 * targets for (or NULL for none)
1067 * @param key ID of the peer
1068 * @param value 'struct ConnectedPeer' of the peer
1069 * @return GNUNET_YES (always continue iteration)
1072 consider_migration (void *cls,
1073 const GNUNET_HashCode *key,
1076 struct MigrationReadyBlock *mb = cls;
1077 struct ConnectedPeer *cp = value;
1078 struct MigrationReadyBlock *pos;
1079 struct GNUNET_PeerIdentity cppid;
1080 struct GNUNET_PeerIdentity otherpid;
1081 struct GNUNET_PeerIdentity worstpid;
1086 /* consider 'cp' as a migration target for mb */
1087 if (GNUNET_TIME_absolute_get_remaining (cp->migration_blocked).rel_value > 0)
1088 return GNUNET_YES; /* peer has requested no migration! */
1091 GNUNET_PEER_resolve (cp->pid,
1093 repl = MIGRATION_LIST_SIZE;
1094 for (i=0;i<MIGRATION_LIST_SIZE;i++)
1096 if (mb->target_list[i] == 0)
1098 mb->target_list[i] = cp->pid;
1099 GNUNET_PEER_change_rc (mb->target_list[i], 1);
1100 repl = MIGRATION_LIST_SIZE;
1103 GNUNET_PEER_resolve (mb->target_list[i],
1105 if ( (repl == MIGRATION_LIST_SIZE) &&
1106 is_closer (&mb->query,
1111 worstpid = otherpid;
1113 else if ( (repl != MIGRATION_LIST_SIZE) &&
1114 (is_closer (&mb->query,
1119 worstpid = otherpid;
1122 if (repl != MIGRATION_LIST_SIZE)
1124 GNUNET_PEER_change_rc (mb->target_list[repl], -1);
1125 mb->target_list[repl] = cp->pid;
1126 GNUNET_PEER_change_rc (mb->target_list[repl], 1);
1130 /* consider scheduling transmission to cp for content migration */
1131 if (cp->cth != NULL)
1137 for (i=0;i<MIGRATION_LIST_SIZE;i++)
1139 if (cp->pid == pos->target_list[i])
1144 msize = GNUNET_MIN (msize,
1152 return GNUNET_YES; /* no content available */
1154 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1155 "Trying to migrate at least %u bytes to peer `%s'\n",
1159 if (cp->delayed_transmission_request_task != GNUNET_SCHEDULER_NO_TASK)
1161 GNUNET_SCHEDULER_cancel (cp->delayed_transmission_request_task);
1162 cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
1165 = GNUNET_CORE_notify_transmit_ready (core,
1167 0, GNUNET_TIME_UNIT_FOREVER_REL,
1168 (const struct GNUNET_PeerIdentity*) key,
1169 msize + sizeof (struct PutMessage),
1177 * Task that is run periodically to obtain blocks for content
1181 * @param tc scheduler context (also unused)
1184 gather_migration_blocks (void *cls,
1185 const struct GNUNET_SCHEDULER_TaskContext *tc);
1191 * Task that is run periodically to obtain blocks for DHT PUTs.
1193 * @param cls type of blocks to gather
1194 * @param tc scheduler context (unused)
1197 gather_dht_put_blocks (void *cls,
1198 const struct GNUNET_SCHEDULER_TaskContext *tc);
1202 * If the migration task is not currently running, consider
1203 * (re)scheduling it with the appropriate delay.
1206 consider_migration_gathering ()
1208 struct GNUNET_TIME_Relative delay;
1214 if (mig_task != GNUNET_SCHEDULER_NO_TASK)
1216 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
1218 delay = GNUNET_TIME_relative_divide (delay,
1219 MAX_MIGRATION_QUEUE);
1220 delay = GNUNET_TIME_relative_max (delay,
1221 min_migration_delay);
1222 mig_task = GNUNET_SCHEDULER_add_delayed (delay,
1223 &gather_migration_blocks,
1229 * If the DHT PUT gathering task is not currently running, consider
1230 * (re)scheduling it with the appropriate delay.
1233 consider_dht_put_gathering (void *cls)
1235 struct GNUNET_TIME_Relative delay;
1241 if (dht_task != GNUNET_SCHEDULER_NO_TASK)
1243 if (zero_anonymity_count_estimate > 0)
1245 delay = GNUNET_TIME_relative_divide (GNUNET_DHT_DEFAULT_REPUBLISH_FREQUENCY,
1246 zero_anonymity_count_estimate);
1247 delay = GNUNET_TIME_relative_min (delay,
1252 /* if we have NO zero-anonymity content yet, wait 5 minutes for some to
1253 (hopefully) appear */
1254 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5);
1256 dht_task = GNUNET_SCHEDULER_add_delayed (delay,
1257 &gather_dht_put_blocks,
1263 * Process content offered for migration.
1265 * @param cls closure
1266 * @param key key for the content
1267 * @param size number of bytes in data
1268 * @param data content stored
1269 * @param type type of the content
1270 * @param priority priority of the content
1271 * @param anonymity anonymity-level for the content
1272 * @param expiration expiration time for the content
1273 * @param uid unique identifier for the datum;
1274 * maybe 0 if no unique identifier is available
1277 process_migration_content (void *cls,
1278 const GNUNET_HashCode * key,
1281 enum GNUNET_BLOCK_Type type,
1284 struct GNUNET_TIME_Absolute
1285 expiration, uint64_t uid)
1287 struct MigrationReadyBlock *mb;
1292 if (mig_size < MAX_MIGRATION_QUEUE)
1293 consider_migration_gathering ();
1296 if (GNUNET_TIME_absolute_get_remaining (expiration).rel_value <
1297 MIN_MIGRATION_CONTENT_LIFETIME.rel_value)
1299 /* content will expire soon, don't bother */
1300 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1303 if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
1306 GNUNET_FS_handle_on_demand_block (key, size, data,
1307 type, priority, anonymity,
1309 &process_migration_content,
1312 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1317 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1318 "Retrieved block `%s' of type %u for migration\n",
1322 mb = GNUNET_malloc (sizeof (struct MigrationReadyBlock) + size);
1324 mb->expiration = expiration;
1327 memcpy (&mb[1], data, size);
1328 GNUNET_CONTAINER_DLL_insert_after (mig_head,
1333 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1334 &consider_migration,
1336 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1341 * Function called upon completion of the DHT PUT operation.
1344 dht_put_continuation (void *cls,
1345 const struct GNUNET_SCHEDULER_TaskContext *tc)
1347 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1352 * Store content in DHT.
1354 * @param cls closure
1355 * @param key key for the content
1356 * @param size number of bytes in data
1357 * @param data content stored
1358 * @param type type of the content
1359 * @param priority priority of the content
1360 * @param anonymity anonymity-level for the content
1361 * @param expiration expiration time for the content
1362 * @param uid unique identifier for the datum;
1363 * maybe 0 if no unique identifier is available
1366 process_dht_put_content (void *cls,
1367 const GNUNET_HashCode * key,
1370 enum GNUNET_BLOCK_Type type,
1373 struct GNUNET_TIME_Absolute
1374 expiration, uint64_t uid)
1376 static unsigned int counter;
1377 static GNUNET_HashCode last_vhash;
1378 static GNUNET_HashCode vhash;
1383 consider_dht_put_gathering (cls);
1386 /* slightly funky code to estimate the total number of values with zero
1387 anonymity from the maximum observed length of a monotonically increasing
1388 sequence of hashes over the contents */
1389 GNUNET_CRYPTO_hash (data, size, &vhash);
1390 if (GNUNET_CRYPTO_hash_cmp (&vhash, &last_vhash) <= 0)
1392 if (zero_anonymity_count_estimate > 0)
1393 zero_anonymity_count_estimate /= 2;
1399 if (zero_anonymity_count_estimate < (1 << counter))
1400 zero_anonymity_count_estimate = (1 << counter);
1402 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1403 "Retrieved block `%s' of type %u for DHT PUT\n",
1407 GNUNET_DHT_put (dht_handle,
1409 DEFAULT_PUT_REPLICATION,
1415 GNUNET_TIME_UNIT_FOREVER_REL,
1416 &dht_put_continuation,
1422 * Task that is run periodically to obtain blocks for content
1426 * @param tc scheduler context (also unused)
1429 gather_migration_blocks (void *cls,
1430 const struct GNUNET_SCHEDULER_TaskContext *tc)
1432 mig_task = GNUNET_SCHEDULER_NO_TASK;
1435 mig_qe = GNUNET_DATASTORE_get_random (dsh, 0, UINT_MAX,
1436 GNUNET_TIME_UNIT_FOREVER_REL,
1437 &process_migration_content, NULL);
1438 GNUNET_assert (mig_qe != NULL);
1444 * Task that is run periodically to obtain blocks for DHT PUTs.
1446 * @param cls type of blocks to gather
1447 * @param tc scheduler context (unused)
1450 gather_dht_put_blocks (void *cls,
1451 const struct GNUNET_SCHEDULER_TaskContext *tc)
1453 dht_task = GNUNET_SCHEDULER_NO_TASK;
1456 if (dht_put_type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
1457 dht_put_type = GNUNET_BLOCK_TYPE_FS_KBLOCK;
1458 dht_qe = GNUNET_DATASTORE_get_zero_anonymity (dsh, 0, UINT_MAX,
1459 GNUNET_TIME_UNIT_FOREVER_REL,
1461 &process_dht_put_content, NULL);
1462 GNUNET_assert (dht_qe != NULL);
1468 * We're done with a particular message list entry.
1469 * Free all associated resources.
1471 * @param pml entry to destroy
1474 destroy_pending_message_list_entry (struct PendingMessageList *pml)
1476 GNUNET_CONTAINER_DLL_remove (pml->req->pending_head,
1477 pml->req->pending_tail,
1479 GNUNET_CONTAINER_DLL_remove (pml->target->pending_messages_head,
1480 pml->target->pending_messages_tail,
1482 GNUNET_assert (pml->target->pending_requests > 0);
1483 pml->target->pending_requests--;
1484 GNUNET_free (pml->pm);
1490 * Destroy the given pending message (and call the respective
1493 * @param pm message to destroy
1494 * @param tpid id of peer that the message was delivered to, or 0 for none
1497 destroy_pending_message (struct PendingMessage *pm,
1498 GNUNET_PEER_Id tpid)
1500 struct PendingMessageList *pml = pm->pml;
1501 TransmissionContinuation cont;
1505 cont_cls = pm->cont_cls;
1508 GNUNET_assert (pml->pm == pm);
1509 GNUNET_assert ( (tpid == 0) || (tpid == pml->target->pid) );
1510 destroy_pending_message_list_entry (pml);
1517 cont (cont_cls, tpid);
1522 * We're done processing a particular request.
1523 * Free all associated resources.
1525 * @param pr request to destroy
1528 destroy_pending_request (struct PendingRequest *pr)
1530 struct GNUNET_PeerIdentity pid;
1533 if (pr->hnode != NULL)
1535 GNUNET_CONTAINER_heap_remove_node (pr->hnode);
1538 if (NULL == pr->client_request_list)
1540 GNUNET_STATISTICS_update (stats,
1541 gettext_noop ("# P2P searches active"),
1547 GNUNET_STATISTICS_update (stats,
1548 gettext_noop ("# client searches active"),
1553 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
1557 GNUNET_LOAD_update (rt_entry_lifetime,
1558 GNUNET_TIME_absolute_get_duration (pr->start_time).rel_value);
1562 GNUNET_DATASTORE_cancel (pr->qe);
1565 if (pr->dht_get != NULL)
1567 GNUNET_DHT_get_stop (pr->dht_get);
1570 if (pr->client_request_list != NULL)
1572 GNUNET_CONTAINER_DLL_remove (pr->client_request_list->client_list->rl_head,
1573 pr->client_request_list->client_list->rl_tail,
1574 pr->client_request_list);
1575 GNUNET_free (pr->client_request_list);
1576 pr->client_request_list = NULL;
1580 GNUNET_PEER_resolve (pr->cp->pid,
1582 (void) GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
1589 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
1592 if (pr->pirc != NULL)
1594 GNUNET_CORE_peer_change_preference_cancel (pr->pirc->irc);
1595 pr->pirc->irc = NULL;
1598 if (pr->replies_seen != NULL)
1600 GNUNET_free (pr->replies_seen);
1601 pr->replies_seen = NULL;
1603 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
1605 GNUNET_SCHEDULER_cancel (pr->task);
1606 pr->task = GNUNET_SCHEDULER_NO_TASK;
1608 while (NULL != pr->pending_head)
1609 destroy_pending_message_list_entry (pr->pending_head);
1610 GNUNET_PEER_change_rc (pr->target_pid, -1);
1611 if (pr->used_targets != NULL)
1613 for (i=0;i<pr->used_targets_off;i++)
1614 GNUNET_PEER_change_rc (pr->used_targets[i].pid, -1);
1615 GNUNET_free (pr->used_targets);
1616 pr->used_targets_off = 0;
1617 pr->used_targets_size = 0;
1618 pr->used_targets = NULL;
1625 * Find latency information in 'atsi'.
1627 * @param atsi performance data
1628 * @return connection latency
1630 static struct GNUNET_TIME_Relative
1631 get_latency (const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1634 return GNUNET_TIME_UNIT_SECONDS;
1635 while ( (ntohl (atsi->type) != GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR) &&
1636 (ntohl (atsi->type) != GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY) )
1638 if (ntohl (atsi->type) == GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR)
1641 /* how can we not have latency data? */
1642 return GNUNET_TIME_UNIT_SECONDS;
1644 return GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1645 ntohl (atsi->value));
1650 * Method called whenever a given peer connects.
1652 * @param cls closure, not used
1653 * @param peer peer identity this notification is about
1654 * @param atsi performance information
1657 peer_connect_handler (void *cls,
1659 GNUNET_PeerIdentity * peer,
1660 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1662 struct ConnectedPeer *cp;
1663 struct MigrationReadyBlock *pos;
1666 struct GNUNET_TIME_Relative latency;
1668 if (0 == memcmp (&my_id, peer, sizeof (struct GNUNET_PeerIdentity)))
1670 latency = get_latency (atsi);
1671 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1678 cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
1679 cp->transmission_delay = GNUNET_LOAD_value_init (latency);
1680 cp->pid = GNUNET_PEER_intern (peer);
1682 fn = get_trust_filename (peer);
1683 if ((GNUNET_DISK_file_test (fn) == GNUNET_YES) &&
1684 (sizeof (trust) == GNUNET_DISK_fn_read (fn, &trust, sizeof (trust))))
1685 cp->disk_trust = cp->trust = ntohl (trust);
1688 GNUNET_break (GNUNET_OK ==
1689 GNUNET_CONTAINER_multihashmap_put (connected_peers,
1692 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1697 (void) consider_migration (pos, &peer->hashPubKey, cp);
1704 * Method called whenever a given peer has a status change.
1706 * @param cls closure
1707 * @param peer peer identity this notification is about
1708 * @param bandwidth_in available amount of inbound bandwidth
1709 * @param bandwidth_out available amount of outbound bandwidth
1710 * @param timeout absolute time when this peer will time out
1711 * unless we see some further activity from it
1712 * @param atsi status information
1715 peer_status_handler (void *cls,
1717 GNUNET_PeerIdentity * peer,
1718 struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
1719 struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
1720 struct GNUNET_TIME_Absolute timeout,
1721 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1723 struct ConnectedPeer *cp;
1724 struct GNUNET_TIME_Relative latency;
1726 latency = get_latency (atsi);
1727 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1734 GNUNET_LOAD_value_set_decline (cp->transmission_delay,
1741 * Increase the host credit by a value.
1743 * @param host which peer to change the trust value on
1744 * @param value is the int value by which the
1745 * host credit is to be increased or decreased
1746 * @returns the actual change in trust (positive or negative)
1749 change_host_trust (struct ConnectedPeer *host, int value)
1753 GNUNET_assert (host != NULL);
1756 if (host->trust + value < host->trust)
1758 value = UINT32_MAX - host->trust;
1759 host->trust = UINT32_MAX;
1762 host->trust += value;
1766 if (host->trust < -value)
1768 value = -host->trust;
1772 host->trust += value;
1779 * Write host-trust information to a file - flush the buffer entry!
1782 flush_trust (void *cls,
1783 const GNUNET_HashCode *key,
1786 struct ConnectedPeer *host = value;
1789 struct GNUNET_PeerIdentity pid;
1791 if (host->trust == host->disk_trust)
1792 return GNUNET_OK; /* unchanged */
1793 GNUNET_PEER_resolve (host->pid,
1795 fn = get_trust_filename (&pid);
1796 if (host->trust == 0)
1798 if ((0 != UNLINK (fn)) && (errno != ENOENT))
1799 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
1800 GNUNET_ERROR_TYPE_BULK, "unlink", fn);
1804 trust = htonl (host->trust);
1805 if (sizeof(uint32_t) == GNUNET_DISK_fn_write (fn, &trust,
1807 GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE
1808 | GNUNET_DISK_PERM_GROUP_READ | GNUNET_DISK_PERM_OTHER_READ))
1809 host->disk_trust = host->trust;
1816 * Call this method periodically to scan data/hosts for new hosts.
1819 cron_flush_trust (void *cls,
1820 const struct GNUNET_SCHEDULER_TaskContext *tc)
1823 if (NULL == connected_peers)
1825 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1830 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1832 GNUNET_SCHEDULER_add_delayed (TRUST_FLUSH_FREQ, &cron_flush_trust, NULL);
1837 * Free (each) request made by the peer.
1839 * @param cls closure, points to peer that the request belongs to
1840 * @param key current key code
1841 * @param value value in the hash map
1842 * @return GNUNET_YES (we should continue to iterate)
1845 destroy_request (void *cls,
1846 const GNUNET_HashCode * key,
1849 const struct GNUNET_PeerIdentity * peer = cls;
1850 struct PendingRequest *pr = value;
1852 GNUNET_break (GNUNET_YES ==
1853 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
1856 destroy_pending_request (pr);
1862 * Method called whenever a peer disconnects.
1864 * @param cls closure, not used
1865 * @param peer peer identity this notification is about
1868 peer_disconnect_handler (void *cls,
1870 GNUNET_PeerIdentity * peer)
1872 struct ConnectedPeer *cp;
1873 struct PendingMessage *pm;
1875 struct MigrationReadyBlock *pos;
1876 struct MigrationReadyBlock *next;
1878 if (0 == memcmp (&my_id, peer, sizeof (struct GNUNET_PeerIdentity)))
1880 GNUNET_CONTAINER_multihashmap_get_multiple (peer_request_map,
1884 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1888 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1890 if (NULL != cp->last_client_replies[i])
1892 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1893 cp->last_client_replies[i] = NULL;
1896 GNUNET_break (GNUNET_YES ==
1897 GNUNET_CONTAINER_multihashmap_remove (connected_peers,
1900 if (cp->irc != NULL)
1902 GNUNET_CORE_peer_change_preference_cancel (cp->irc);
1904 cp->pr->pirc = NULL;
1908 /* remove this peer from migration considerations; schedule
1911 while (NULL != (pos = next))
1914 for (i=0;i<MIGRATION_LIST_SIZE;i++)
1916 if (pos->target_list[i] == cp->pid)
1918 GNUNET_PEER_change_rc (pos->target_list[i], -1);
1919 pos->target_list[i] = 0;
1922 if (pos->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers))
1924 delete_migration_block (pos);
1925 consider_migration_gathering ();
1928 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1929 &consider_migration,
1932 GNUNET_PEER_change_rc (cp->pid, -1);
1933 GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
1934 if (NULL != cp->cth)
1936 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
1939 if (cp->delayed_transmission_request_task != GNUNET_SCHEDULER_NO_TASK)
1941 GNUNET_SCHEDULER_cancel (cp->delayed_transmission_request_task);
1942 cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
1944 while (NULL != (pm = cp->pending_messages_head))
1945 destroy_pending_message (pm, 0 /* delivery failed */);
1946 GNUNET_LOAD_value_free (cp->transmission_delay);
1947 GNUNET_break (0 == cp->pending_requests);
1953 * Iterator over hash map entries that removes all occurences
1954 * of the given 'client' from the 'last_client_replies' of the
1955 * given connected peer.
1957 * @param cls closure, the 'struct GNUNET_SERVER_Client*' to remove
1958 * @param key current key code (unused)
1959 * @param value value in the hash map (the 'struct ConnectedPeer*' to change)
1960 * @return GNUNET_YES (we should continue to iterate)
1963 remove_client_from_last_client_replies (void *cls,
1964 const GNUNET_HashCode * key,
1967 struct GNUNET_SERVER_Client *client = cls;
1968 struct ConnectedPeer *cp = value;
1971 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1973 if (cp->last_client_replies[i] == client)
1975 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1976 cp->last_client_replies[i] = NULL;
1984 * A client disconnected. Remove all of its pending queries.
1986 * @param cls closure, NULL
1987 * @param client identification of the client
1990 handle_client_disconnect (void *cls,
1991 struct GNUNET_SERVER_Client
1994 struct ClientList *pos;
1995 struct ClientList *prev;
1996 struct ClientRequestList *rcl;
1997 struct ClientResponseMessage *creply;
2003 while ( (NULL != pos) &&
2004 (pos->client != client) )
2010 return; /* no requests pending for this client */
2011 while (NULL != (rcl = pos->rl_head))
2013 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2014 "Destroying pending request `%s' on disconnect\n",
2015 GNUNET_h2s (&rcl->req->query));
2016 destroy_pending_request (rcl->req);
2019 client_list = pos->next;
2021 prev->next = pos->next;
2022 if (pos->th != NULL)
2024 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
2027 while (NULL != (creply = pos->res_head))
2029 GNUNET_CONTAINER_DLL_remove (pos->res_head,
2032 GNUNET_free (creply);
2034 GNUNET_SERVER_client_drop (pos->client);
2036 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
2037 &remove_client_from_last_client_replies,
2043 * Iterator to free peer entries.
2045 * @param cls closure, unused
2046 * @param key current key code
2047 * @param value value in the hash map (peer entry)
2048 * @return GNUNET_YES (we should continue to iterate)
2051 clean_peer (void *cls,
2052 const GNUNET_HashCode * key,
2055 peer_disconnect_handler (NULL, (const struct GNUNET_PeerIdentity*) key);
2061 * Task run during shutdown.
2067 shutdown_task (void *cls,
2068 const struct GNUNET_SCHEDULER_TaskContext *tc)
2072 GNUNET_DATASTORE_cancel (mig_qe);
2077 GNUNET_DATASTORE_cancel (dht_qe);
2080 if (GNUNET_SCHEDULER_NO_TASK != mig_task)
2082 GNUNET_SCHEDULER_cancel (mig_task);
2083 mig_task = GNUNET_SCHEDULER_NO_TASK;
2085 if (GNUNET_SCHEDULER_NO_TASK != dht_task)
2087 GNUNET_SCHEDULER_cancel (dht_task);
2088 dht_task = GNUNET_SCHEDULER_NO_TASK;
2090 while (client_list != NULL)
2091 handle_client_disconnect (NULL,
2092 client_list->client);
2093 cron_flush_trust (NULL, NULL);
2094 GNUNET_assert (NULL != core);
2095 GNUNET_CORE_disconnect (core);
2097 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
2100 GNUNET_break (0 == GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap));
2101 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
2102 requests_by_expiration_heap = 0;
2103 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
2104 connected_peers = NULL;
2105 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (query_request_map));
2106 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
2107 query_request_map = NULL;
2108 GNUNET_LOAD_value_free (rt_entry_lifetime);
2109 rt_entry_lifetime = NULL;
2110 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (peer_request_map));
2111 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
2112 peer_request_map = NULL;
2115 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
2120 GNUNET_DATASTORE_disconnect (dsh,
2124 while (mig_head != NULL)
2125 delete_migration_block (mig_head);
2126 GNUNET_assert (0 == mig_size);
2127 GNUNET_DHT_disconnect (dht_handle);
2129 GNUNET_LOAD_value_free (datastore_get_load);
2130 datastore_get_load = NULL;
2131 GNUNET_LOAD_value_free (datastore_put_load);
2132 datastore_put_load = NULL;
2133 GNUNET_BLOCK_context_destroy (block_ctx);
2135 GNUNET_CONFIGURATION_destroy (block_cfg);
2138 GNUNET_free_non_null (trustDirectory);
2139 trustDirectory = NULL;
2140 GNUNET_SCHEDULER_cancel (cover_age_task);
2141 cover_age_task = GNUNET_SCHEDULER_NO_TASK;
2145 /* ******************* Utility functions ******************** */
2149 * We've had to delay a request for transmission to core, but now
2150 * we should be ready. Run it.
2152 * @param cls the 'struct ConnectedPeer' for which a request was delayed
2153 * @param tc task context (unused)
2156 delayed_transmission_request (void *cls,
2157 const struct GNUNET_SCHEDULER_TaskContext *tc)
2159 struct ConnectedPeer *cp = cls;
2160 struct GNUNET_PeerIdentity pid;
2161 struct PendingMessage *pm;
2163 pm = cp->pending_messages_head;
2164 cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
2165 GNUNET_assert (cp->cth == NULL);
2168 GNUNET_PEER_resolve (cp->pid,
2170 cp->last_transmission_request_start = GNUNET_TIME_absolute_get ();
2171 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
2174 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
2183 * Transmit messages by copying it to the target buffer
2184 * "buf". "buf" will be NULL and "size" zero if the socket was closed
2185 * for writing in the meantime. In that case, do nothing
2186 * (the disconnect or shutdown handler will take care of the rest).
2187 * If we were able to transmit messages and there are still more
2188 * pending, ask core again for further calls to this function.
2190 * @param cls closure, pointer to the 'struct ConnectedPeer*'
2191 * @param size number of bytes available in buf
2192 * @param buf where the callee should write the message
2193 * @return number of bytes written to buf
2196 transmit_to_peer (void *cls,
2197 size_t size, void *buf)
2199 struct ConnectedPeer *cp = cls;
2201 struct PendingMessage *pm;
2202 struct PendingMessage *next_pm;
2203 struct GNUNET_TIME_Absolute now;
2204 struct GNUNET_TIME_Relative min_delay;
2205 struct MigrationReadyBlock *mb;
2206 struct MigrationReadyBlock *next;
2207 struct PutMessage migm;
2210 struct GNUNET_PeerIdentity pid;
2216 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2217 "Dropping message, core too busy.\n");
2219 GNUNET_LOAD_update (cp->transmission_delay,
2222 if (NULL != (pm = cp->pending_messages_head))
2224 GNUNET_CONTAINER_DLL_remove (cp->pending_messages_head,
2225 cp->pending_messages_tail,
2227 GNUNET_assert (cp->pending_requests > 0);
2228 cp->pending_requests--;
2229 destroy_pending_message (pm, 0);
2231 if (NULL != (pm = cp->pending_messages_head))
2233 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == cp->delayed_transmission_request_task);
2234 min_delay = GNUNET_TIME_absolute_get_remaining (pm->delay_until);
2235 cp->delayed_transmission_request_task
2236 = GNUNET_SCHEDULER_add_delayed (min_delay,
2237 &delayed_transmission_request,
2242 GNUNET_LOAD_update (cp->transmission_delay,
2243 GNUNET_TIME_absolute_get_duration (cp->last_transmission_request_start).rel_value);
2244 now = GNUNET_TIME_absolute_get ();
2246 min_delay = GNUNET_TIME_UNIT_FOREVER_REL;
2247 next_pm = cp->pending_messages_head;
2248 while ( (NULL != (pm = next_pm) ) &&
2249 (pm->msize <= size) )
2252 if (pm->delay_until.abs_value > now.abs_value)
2254 min_delay = GNUNET_TIME_relative_min (min_delay,
2255 GNUNET_TIME_absolute_get_remaining (pm->delay_until));
2258 memcpy (&cbuf[msize], &pm[1], pm->msize);
2261 if (NULL == pm->pml)
2263 GNUNET_CONTAINER_DLL_remove (cp->pending_messages_head,
2264 cp->pending_messages_tail,
2266 GNUNET_assert (cp->pending_requests > 0);
2267 cp->pending_requests--;
2269 destroy_pending_message (pm, cp->pid);
2272 min_delay = GNUNET_TIME_UNIT_ZERO;
2273 if (NULL != cp->pending_messages_head)
2275 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == cp->delayed_transmission_request_task);
2276 cp->delayed_transmission_request_task
2277 = GNUNET_SCHEDULER_add_delayed (min_delay,
2278 &delayed_transmission_request,
2283 GNUNET_PEER_resolve (cp->pid,
2286 while (NULL != (mb = next))
2289 for (i=0;i<MIGRATION_LIST_SIZE;i++)
2291 if ( (cp->pid == mb->target_list[i]) &&
2292 (mb->size + sizeof (migm) <= size) )
2294 GNUNET_PEER_change_rc (mb->target_list[i], -1);
2295 mb->target_list[i] = 0;
2297 memset (&migm, 0, sizeof (migm));
2298 migm.header.size = htons (sizeof (migm) + mb->size);
2299 migm.header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2300 migm.type = htonl (mb->type);
2301 migm.expiration = GNUNET_TIME_absolute_hton (mb->expiration);
2302 memcpy (&cbuf[msize], &migm, sizeof (migm));
2303 msize += sizeof (migm);
2304 size -= sizeof (migm);
2305 memcpy (&cbuf[msize], &mb[1], mb->size);
2309 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2310 "Pushing migration block `%s' (%u bytes) to `%s'\n",
2311 GNUNET_h2s (&mb->query),
2312 (unsigned int) mb->size,
2320 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2321 "Migration block `%s' (%u bytes) is not on migration list for peer `%s'\n",
2322 GNUNET_h2s (&mb->query),
2323 (unsigned int) mb->size,
2328 if ( (mb->used_targets >= MIGRATION_TARGET_COUNT) ||
2329 (mb->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers)) )
2331 delete_migration_block (mb);
2332 consider_migration_gathering ();
2335 consider_migration (NULL,
2340 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2341 "Transmitting %u bytes to peer with PID %u\n",
2342 (unsigned int) msize,
2343 (unsigned int) cp->pid);
2350 * Add a message to the set of pending messages for the given peer.
2352 * @param cp peer to send message to
2353 * @param pm message to queue
2354 * @param pr request on which behalf this message is being queued
2357 add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
2358 struct PendingMessage *pm,
2359 struct PendingRequest *pr)
2361 struct PendingMessage *pos;
2362 struct PendingMessageList *pml;
2363 struct GNUNET_PeerIdentity pid;
2365 GNUNET_assert (pm->next == NULL);
2366 GNUNET_assert (pm->pml == NULL);
2369 pml = GNUNET_malloc (sizeof (struct PendingMessageList));
2374 GNUNET_CONTAINER_DLL_insert (pr->pending_head,
2378 pos = cp->pending_messages_head;
2379 while ( (pos != NULL) &&
2380 (pm->priority < pos->priority) )
2382 GNUNET_CONTAINER_DLL_insert_after (cp->pending_messages_head,
2383 cp->pending_messages_tail,
2386 cp->pending_requests++;
2387 if (cp->pending_requests > MAX_QUEUE_PER_PEER)
2389 GNUNET_STATISTICS_update (stats,
2390 gettext_noop ("# P2P searches discarded (queue length bound)"),
2393 destroy_pending_message (cp->pending_messages_tail, 0);
2395 GNUNET_PEER_resolve (cp->pid, &pid);
2396 if (NULL != cp->cth)
2398 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
2401 if (cp->delayed_transmission_request_task != GNUNET_SCHEDULER_NO_TASK)
2403 GNUNET_SCHEDULER_cancel (cp->delayed_transmission_request_task);
2404 cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
2406 /* need to schedule transmission */
2407 cp->last_transmission_request_start = GNUNET_TIME_absolute_get ();
2408 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
2410 cp->pending_messages_head->priority,
2413 cp->pending_messages_head->msize,
2416 if (cp->cth == NULL)
2419 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2420 "Failed to schedule transmission with core!\n");
2422 GNUNET_STATISTICS_update (stats,
2423 gettext_noop ("# CORE transmission failures"),
2431 * Test if the DATABASE (GET) load on this peer is too high
2432 * to even consider processing the query at
2435 * @return GNUNET_YES if the load is too high to do anything (load high)
2436 * GNUNET_NO to process normally (load normal)
2437 * GNUNET_SYSERR to process for free (load low)
2440 test_get_load_too_high (uint32_t priority)
2444 ld = GNUNET_LOAD_get_load (datastore_get_load);
2446 return GNUNET_SYSERR;
2456 * Test if the DATABASE (PUT) load on this peer is too high
2457 * to even consider processing the query at
2460 * @return GNUNET_YES if the load is too high to do anything (load high)
2461 * GNUNET_NO to process normally (load normal or low)
2464 test_put_load_too_high (uint32_t priority)
2468 if (GNUNET_LOAD_get_average (datastore_put_load) < 50)
2469 return GNUNET_NO; /* very fast */
2470 ld = GNUNET_LOAD_get_load (datastore_put_load);
2471 if (ld < 2.0 * (1 + priority))
2473 GNUNET_STATISTICS_update (stats,
2474 gettext_noop ("# storage requests dropped due to high load"),
2481 /* ******************* Pending Request Refresh Task ******************** */
2486 * We use a random delay to make the timing of requests less
2487 * predictable. This function returns such a random delay. We add a base
2488 * delay of MAX_CORK_DELAY (1s).
2490 * FIXME: make schedule dependent on the specifics of the request?
2491 * Or bandwidth and number of connected peers and load?
2493 * @return random delay to use for some request, between 1s and 1000+TTL_DECREMENT ms
2495 static struct GNUNET_TIME_Relative
2496 get_processing_delay ()
2499 GNUNET_TIME_relative_add (GNUNET_CONSTANTS_MAX_CORK_DELAY,
2500 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
2501 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2507 * We're processing a GET request from another peer and have decided
2508 * to forward it to other peers. This function is called periodically
2509 * and should forward the request to other peers until we have all
2510 * possible replies. If we have transmitted the *only* reply to
2511 * the initiator we should destroy the pending request. If we have
2512 * many replies in the queue to the initiator, we should delay sending
2513 * out more queries until the reply queue has shrunk some.
2515 * @param cls our "struct ProcessGetContext *"
2519 forward_request_task (void *cls,
2520 const struct GNUNET_SCHEDULER_TaskContext *tc);
2524 * Function called after we either failed or succeeded
2525 * at transmitting a query to a peer.
2527 * @param cls the requests "struct PendingRequest*"
2528 * @param tpid ID of receiving peer, 0 on transmission error
2531 transmit_query_continuation (void *cls,
2532 GNUNET_PEER_Id tpid)
2534 struct PendingRequest *pr = cls;
2537 GNUNET_STATISTICS_update (stats,
2538 gettext_noop ("# queries scheduled for forwarding"),
2544 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2545 "Transmission of request failed, will try again later.\n");
2547 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2548 pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2549 &forward_request_task,
2554 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2555 "Transmitted query `%s'\n",
2556 GNUNET_h2s (&pr->query));
2558 GNUNET_STATISTICS_update (stats,
2559 gettext_noop ("# queries forwarded"),
2562 for (i=0;i<pr->used_targets_off;i++)
2563 if (pr->used_targets[i].pid == tpid)
2564 break; /* found match! */
2565 if (i == pr->used_targets_off)
2567 /* need to create new entry */
2568 if (pr->used_targets_off == pr->used_targets_size)
2569 GNUNET_array_grow (pr->used_targets,
2570 pr->used_targets_size,
2571 pr->used_targets_size * 2 + 2);
2572 GNUNET_PEER_change_rc (tpid, 1);
2573 pr->used_targets[pr->used_targets_off].pid = tpid;
2574 pr->used_targets[pr->used_targets_off].num_requests = 0;
2575 i = pr->used_targets_off++;
2577 pr->used_targets[i].last_request_time = GNUNET_TIME_absolute_get ();
2578 pr->used_targets[i].num_requests++;
2579 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2580 pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2581 &forward_request_task,
2587 * How many bytes should a bloomfilter be if we have already seen
2588 * entry_count responses? Note that BLOOMFILTER_K gives us the number
2589 * of bits set per entry. Furthermore, we should not re-size the
2590 * filter too often (to keep it cheap).
2592 * Since other peers will also add entries but not resize the filter,
2593 * we should generally pick a slightly larger size than what the
2594 * strict math would suggest.
2596 * @return must be a power of two and smaller or equal to 2^15.
2599 compute_bloomfilter_size (unsigned int entry_count)
2602 unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
2603 uint16_t max = 1 << 15;
2605 if (entry_count > max)
2608 while ((size < max) && (size < ideal))
2617 * Recalculate our bloom filter for filtering replies. This function
2618 * will create a new bloom filter from scratch, so it should only be
2619 * called if we have no bloomfilter at all (and hence can create a
2620 * fresh one of minimal size without problems) OR if our peer is the
2621 * initiator (in which case we may resize to larger than mimimum size).
2623 * @param pr request for which the BF is to be recomputed
2626 refresh_bloomfilter (struct PendingRequest *pr)
2630 GNUNET_HashCode mhash;
2632 nsize = compute_bloomfilter_size (pr->replies_seen_off);
2633 if (nsize == pr->bf_size)
2634 return; /* size not changed */
2636 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
2637 pr->bf_size = nsize;
2638 pr->mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
2639 pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
2642 for (i=0;i<pr->replies_seen_off;i++)
2644 GNUNET_BLOCK_mingle_hash (&pr->replies_seen[i],
2647 GNUNET_CONTAINER_bloomfilter_add (pr->bf, &mhash);
2653 * Function called after we've tried to reserve a certain amount of
2654 * bandwidth for a reply. Check if we succeeded and if so send our
2657 * @param cls the requests "struct PendingRequest*"
2658 * @param peer identifies the peer
2659 * @param bpm_out set to the current bandwidth limit (sending) for this peer
2660 * @param amount set to the amount that was actually reserved or unreserved
2661 * @param preference current traffic preference for the given peer
2664 target_reservation_cb (void *cls,
2666 GNUNET_PeerIdentity * peer,
2667 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
2669 uint64_t preference)
2671 struct PendingRequest *pr = cls;
2672 struct ConnectedPeer *cp;
2673 struct PendingMessage *pm;
2674 struct GetMessage *gm;
2675 GNUNET_HashCode *ext;
2684 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2685 "Core called back... for query `%s'.\n",
2686 GNUNET_h2s (&pr->query));
2688 /* (3) transmit, update ttl/priority */
2689 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2693 /* Peer must have just left */
2695 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2696 "Selected peer disconnected!\n");
2698 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2699 pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2700 &forward_request_task,
2708 /* error in communication with core, try again later */
2709 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2710 pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2711 &forward_request_task,
2715 no_route = GNUNET_NO;
2721 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2722 "Failed to reserve bandwidth for reply (got %d/%u bytes only)!\n",
2726 GNUNET_STATISTICS_update (stats,
2727 gettext_noop ("# reply bandwidth reservation requests failed"),
2730 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2731 pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2732 &forward_request_task,
2734 return; /* this target round failed */
2736 no_route = GNUNET_YES;
2739 GNUNET_STATISTICS_update (stats,
2740 gettext_noop ("# queries scheduled for forwarding"),
2743 for (i=0;i<pr->used_targets_off;i++)
2744 if (pr->used_targets[i].pid == cp->pid)
2746 GNUNET_STATISTICS_update (stats,
2747 gettext_noop ("# queries retransmitted to same target"),
2753 /* build message and insert message into priority queue */
2755 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2756 "Forwarding request `%s' to `%4s'!\n",
2757 GNUNET_h2s (&pr->query),
2762 if (GNUNET_YES == no_route)
2764 bm |= GET_MESSAGE_BIT_RETURN_TO;
2767 if (pr->namespace != NULL)
2769 bm |= GET_MESSAGE_BIT_SKS_NAMESPACE;
2772 if (pr->target_pid != 0)
2774 bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
2777 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
2778 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
2779 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
2781 gm = (struct GetMessage*) &pm[1];
2782 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
2783 gm->header.size = htons (msize);
2784 gm->type = htonl (pr->type);
2785 pr->remaining_priority /= 2;
2786 gm->priority = htonl (pr->remaining_priority);
2787 gm->ttl = htonl (pr->ttl);
2788 gm->filter_mutator = htonl(pr->mingle);
2789 gm->hash_bitmap = htonl (bm);
2790 gm->query = pr->query;
2791 ext = (GNUNET_HashCode*) &gm[1];
2793 if (GNUNET_YES == no_route)
2794 GNUNET_PEER_resolve (pr->cp->pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
2795 if (pr->namespace != NULL)
2796 memcpy (&ext[k++], pr->namespace, sizeof (GNUNET_HashCode));
2797 if (pr->target_pid != 0)
2798 GNUNET_PEER_resolve (pr->target_pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
2799 bfdata = (char *) &ext[k];
2801 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
2804 pm->cont = &transmit_query_continuation;
2806 cp->last_request_times[(cp->last_request_times_off++) % MAX_QUEUE_PER_PEER] = GNUNET_TIME_absolute_get ();
2807 add_to_pending_messages_for_peer (cp, pm, pr);
2812 * Closure used for "target_peer_select_cb".
2814 struct PeerSelectionContext
2817 * The request for which we are selecting
2820 struct PendingRequest *pr;
2823 * Current "prime" target.
2825 struct GNUNET_PeerIdentity target;
2828 * How much do we like this target?
2830 double target_score;
2833 * Does it make sense to we re-try quickly again?
2841 * Function called for each connected peer to determine
2842 * which one(s) would make good targets for forwarding.
2844 * @param cls closure (struct PeerSelectionContext)
2845 * @param key current key code (peer identity)
2846 * @param value value in the hash map (struct ConnectedPeer)
2847 * @return GNUNET_YES if we should continue to
2852 target_peer_select_cb (void *cls,
2853 const GNUNET_HashCode * key,
2856 struct PeerSelectionContext *psc = cls;
2857 struct ConnectedPeer *cp = value;
2858 struct PendingRequest *pr = psc->pr;
2859 struct GNUNET_TIME_Relative delay;
2864 /* 1) check that this peer is not the initiator */
2868 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2869 "Skipping initiator in forwarding selection\n");
2871 return GNUNET_YES; /* skip */
2873 if (cp->irc != NULL)
2875 psc->fast_retry = GNUNET_YES;
2876 return GNUNET_YES; /* skip: already querying core about this peer for other reasons */
2879 /* 2) check if we have already (recently) forwarded to this peer */
2880 /* 2a) this particular request */
2882 for (i=0;i<pr->used_targets_off;i++)
2883 if (pr->used_targets[i].pid == cp->pid)
2885 pc = pr->used_targets[i].num_requests;
2886 GNUNET_assert (pc > 0);
2887 /* FIXME: make re-enabling a peer independent of how often
2888 this function is called??? */
2889 if (0 != GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2890 RETRY_PROBABILITY_INV * pc))
2893 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2894 "NOT re-trying query that was previously transmitted %u times\n",
2897 return GNUNET_YES; /* skip */
2904 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2905 "Re-trying query that was previously transmitted %u times to this peer\n",
2909 /* 2b) many other requests to this peer */
2910 delay = GNUNET_TIME_absolute_get_duration (cp->last_request_times[cp->last_request_times_off % MAX_QUEUE_PER_PEER]);
2911 if (delay.rel_value <= cp->avg_delay.rel_value)
2914 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2915 "NOT sending query since we send %u others to this peer in the last %llums\n",
2917 cp->avg_delay.rel_value);
2919 return GNUNET_YES; /* skip */
2922 /* 3) calculate how much we'd like to forward to this peer,
2923 starting with a random value that is strong enough
2924 to at least give any peer a chance sometimes
2925 (compared to the other factors that come later) */
2926 /* 3a) count successful (recent) routes from cp for same source */
2929 score = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2930 P2P_SUCCESS_LIST_SIZE);
2931 for (i=0;i<P2P_SUCCESS_LIST_SIZE;i++)
2932 if (cp->last_p2p_replies[i] == pr->cp->pid)
2933 score += 1.0; /* likely successful based on hot path */
2937 score = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2938 CS2P_SUCCESS_LIST_SIZE);
2939 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
2940 if (cp->last_client_replies[i] == pr->client_request_list->client_list->client)
2941 score += 1.0; /* likely successful based on hot path */
2943 /* 3b) include latency */
2944 if (cp->avg_delay.rel_value < 4 * TTL_DECREMENT)
2945 score += 1.0; /* likely fast based on latency */
2946 /* 3c) include priorities */
2947 if (cp->avg_priority <= pr->remaining_priority / 2.0)
2948 score += 1.0; /* likely successful based on priorities */
2949 /* 3d) penalize for queue size */
2950 score -= (2.0 * cp->pending_requests / (double) MAX_QUEUE_PER_PEER);
2951 /* 3e) include peer proximity */
2952 score -= (2.0 * (GNUNET_CRYPTO_hash_distance_u32 (key,
2953 &pr->query)) / (double) UINT32_MAX);
2954 /* 4) super-bonus for being the known target */
2955 if (pr->target_pid == cp->pid)
2957 /* store best-fit in closure */
2958 score++; /* avoid zero */
2959 if (score > psc->target_score)
2961 psc->target_score = score;
2962 psc->target.hashPubKey = *key;
2965 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2966 "Peer `%s' gets score %f for forwarding query, max is %8f\n",
2976 * The priority level imposes a bound on the maximum
2977 * value for the ttl that can be requested.
2979 * @param ttl_in requested ttl
2980 * @param prio given priority
2981 * @return ttl_in if ttl_in is below the limit,
2982 * otherwise the ttl-limit for the given priority
2985 bound_ttl (int32_t ttl_in, uint32_t prio)
2987 unsigned long long allowed;
2991 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
2992 if (ttl_in > allowed)
2994 if (allowed >= (1 << 30))
3003 * Iterator called on each result obtained for a DHT
3004 * operation that expects a reply
3006 * @param cls closure
3007 * @param exp when will this value expire
3008 * @param key key of the result
3009 * @param get_path NULL-terminated array of pointers
3010 * to the peers on reverse GET path (or NULL if not recorded)
3011 * @param put_path NULL-terminated array of pointers
3012 * to the peers on the PUT path (or NULL if not recorded)
3013 * @param type type of the result
3014 * @param size number of bytes in data
3015 * @param data pointer to the result data
3018 process_dht_reply (void *cls,
3019 struct GNUNET_TIME_Absolute exp,
3020 const GNUNET_HashCode * key,
3021 const struct GNUNET_PeerIdentity * const *get_path,
3022 const struct GNUNET_PeerIdentity * const *put_path,
3023 enum GNUNET_BLOCK_Type type,
3029 * We're processing a GET request and have decided
3030 * to forward it to other peers. This function is called periodically
3031 * and should forward the request to other peers until we have all
3032 * possible replies. If we have transmitted the *only* reply to
3033 * the initiator we should destroy the pending request. If we have
3034 * many replies in the queue to the initiator, we should delay sending
3035 * out more queries until the reply queue has shrunk some.
3037 * @param cls our "struct ProcessGetContext *"
3041 forward_request_task (void *cls,
3042 const struct GNUNET_SCHEDULER_TaskContext *tc)
3044 struct PendingRequest *pr = cls;
3045 struct PeerSelectionContext psc;
3046 struct ConnectedPeer *cp;
3047 struct GNUNET_TIME_Relative delay;
3049 pr->task = GNUNET_SCHEDULER_NO_TASK;
3050 if (pr->pirc != NULL)
3053 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3054 "Forwarding of query `%s' not attempted due to pending local lookup!\n",
3055 GNUNET_h2s (&pr->query));
3057 return; /* already pending */
3059 if (GNUNET_YES == pr->local_only)
3060 return; /* configured to not do P2P search */
3062 if ( (0 == pr->anonymity_level) &&
3063 (GNUNET_YES != pr->forward_only) &&
3064 (pr->type != GNUNET_BLOCK_TYPE_FS_DBLOCK) &&
3065 (pr->type != GNUNET_BLOCK_TYPE_FS_IBLOCK) )
3067 pr->dht_get = GNUNET_DHT_get_start (dht_handle,
3068 GNUNET_TIME_UNIT_FOREVER_REL,
3071 DEFAULT_GET_REPLICATION,
3076 (pr->namespace != NULL) ? sizeof (GNUNET_HashCode) : 0,
3081 if ( (pr->anonymity_level > 1) &&
3082 (cover_query_count < pr->anonymity_level - 1) )
3084 delay = get_processing_delay ();
3086 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3087 "Not enough cover traffic to forward query `%s', will try again in %llu ms!\n",
3088 GNUNET_h2s (&pr->query),
3091 pr->task = GNUNET_SCHEDULER_add_delayed (delay,
3092 &forward_request_task,
3096 /* consume cover traffic */
3097 if (pr->anonymity_level > 1)
3098 cover_query_count -= pr->anonymity_level - 1;
3100 /* (1) select target */
3102 psc.target_score = -DBL_MAX;
3103 psc.fast_retry = GNUNET_NO;
3104 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
3105 &target_peer_select_cb,
3107 if (psc.target_score == -DBL_MAX)
3109 if (psc.fast_retry == GNUNET_YES)
3110 delay = GNUNET_TIME_UNIT_MILLISECONDS; /* FIXME: store adaptive fast-retry value in 'pr' */
3112 delay = get_processing_delay ();
3114 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3115 "No peer selected for forwarding of query `%s', will try again in %llu ms!\n",
3116 GNUNET_h2s (&pr->query),
3119 pr->task = GNUNET_SCHEDULER_add_delayed (delay,
3120 &forward_request_task,
3122 return; /* nobody selected */
3124 /* (3) update TTL/priority */
3125 if (pr->client_request_list != NULL)
3127 /* FIXME: use better algorithm!? */
3128 if (0 == GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3131 /* bound priority we use by priorities we see from other peers
3132 rounded up (must round up so that we can see non-zero
3133 priorities, but round up as little as possible to make it
3134 plausible that we forwarded another peers request) */
3135 if (pr->priority > current_priorities + 1.0)
3136 pr->priority = (uint32_t) current_priorities + 1.0;
3137 pr->ttl = bound_ttl (pr->ttl + TTL_DECREMENT * 2,
3140 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3141 "Trying query `%s' with priority %u and TTL %d.\n",
3142 GNUNET_h2s (&pr->query),
3148 /* (3) reserve reply bandwidth */
3149 if (GNUNET_NO == pr->forward_only)
3151 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3152 &psc.target.hashPubKey);
3153 GNUNET_assert (NULL != cp);
3154 GNUNET_assert (cp->irc == NULL);
3158 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3159 "Asking core for bandwidth for query `%s'.\n",
3160 GNUNET_h2s (&pr->query));
3162 cp->irc = GNUNET_CORE_peer_change_preference (core,
3164 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
3165 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
3168 &target_reservation_cb,
3170 GNUNET_assert (cp->irc != NULL);
3171 cp->inc_preference = 0;
3175 /* force forwarding */
3176 static struct GNUNET_BANDWIDTH_Value32NBO zerobw;
3177 target_reservation_cb (pr, &psc.target,
3183 /* **************************** P2P PUT Handling ************************ */
3187 * Function called after we either failed or succeeded
3188 * at transmitting a reply to a peer.
3190 * @param cls the requests "struct PendingRequest*"
3191 * @param tpid ID of receiving peer, 0 on transmission error
3194 transmit_reply_continuation (void *cls,
3195 GNUNET_PEER_Id tpid)
3197 struct PendingRequest *pr = cls;
3201 case GNUNET_BLOCK_TYPE_FS_DBLOCK:
3202 case GNUNET_BLOCK_TYPE_FS_IBLOCK:
3203 /* only one reply expected, done with the request! */
3204 destroy_pending_request (pr);
3206 case GNUNET_BLOCK_TYPE_ANY:
3207 case GNUNET_BLOCK_TYPE_FS_KBLOCK:
3208 case GNUNET_BLOCK_TYPE_FS_SBLOCK:
3218 * Transmit the given message by copying it to the target buffer
3219 * "buf". "buf" will be NULL and "size" zero if the socket was closed
3220 * for writing in the meantime. In that case, do nothing
3221 * (the disconnect or shutdown handler will take care of the rest).
3222 * If we were able to transmit messages and there are still more
3223 * pending, ask core again for further calls to this function.
3225 * @param cls closure, pointer to the 'struct ClientList*'
3226 * @param size number of bytes available in buf
3227 * @param buf where the callee should write the message
3228 * @return number of bytes written to buf
3231 transmit_to_client (void *cls,
3232 size_t size, void *buf)
3234 struct ClientList *cl = cls;
3236 struct ClientResponseMessage *creply;
3243 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3244 "Not sending reply, client communication problem.\n");
3249 while ( (NULL != (creply = cl->res_head) ) &&
3250 (creply->msize <= size) )
3252 memcpy (&cbuf[msize], &creply[1], creply->msize);
3253 msize += creply->msize;
3254 size -= creply->msize;
3255 GNUNET_CONTAINER_DLL_remove (cl->res_head,
3258 GNUNET_free (creply);
3261 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
3263 GNUNET_TIME_UNIT_FOREVER_REL,
3264 &transmit_to_client,
3267 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3268 "Transmitted %u bytes to client\n",
3269 (unsigned int) msize);
3276 * Closure for "process_reply" function.
3278 struct ProcessReplyClosure
3281 * The data for the reply.
3286 * Who gave us this reply? NULL for local host (or DHT)
3288 struct ConnectedPeer *sender;
3291 * When the reply expires.
3293 struct GNUNET_TIME_Absolute expiration;
3301 * Type of the block.
3303 enum GNUNET_BLOCK_Type type;
3306 * How much was this reply worth to us?
3311 * Anonymity requirements for this reply.
3313 uint32_t anonymity_level;
3316 * Evaluation result (returned).
3318 enum GNUNET_BLOCK_EvaluationResult eval;
3321 * Did we finish processing the associated request?
3326 * Did we find a matching request?
3333 * We have received a reply; handle it!
3335 * @param cls response (struct ProcessReplyClosure)
3336 * @param key our query
3337 * @param value value in the hash map (info about the query)
3338 * @return GNUNET_YES (we should continue to iterate)
3341 process_reply (void *cls,
3342 const GNUNET_HashCode * key,
3345 struct ProcessReplyClosure *prq = cls;
3346 struct PendingRequest *pr = value;
3347 struct PendingMessage *reply;
3348 struct ClientResponseMessage *creply;
3349 struct ClientList *cl;
3350 struct PutMessage *pm;
3351 struct ConnectedPeer *cp;
3352 struct GNUNET_TIME_Relative cur_delay;
3354 struct GNUNET_TIME_Relative art_delay;
3359 if (NULL == pr->client_request_list)
3361 /* reply will go over the network, check for cover traffic */
3362 if ( (prq->anonymity_level > 1) &&
3363 (cover_content_count < prq->anonymity_level - 1) )
3365 /* insufficient cover traffic, skip */
3366 GNUNET_STATISTICS_update (stats,
3367 gettext_noop ("# replies suppressed due to lack of cover traffic"),
3372 if (prq->anonymity_level > 1)
3373 cover_content_count -= prq->anonymity_level - 1;
3376 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3377 "Matched result (type %u) for query `%s' with pending request\n",
3378 (unsigned int) prq->type,
3381 GNUNET_STATISTICS_update (stats,
3382 gettext_noop ("# replies received and matched"),
3385 if (prq->sender != NULL)
3387 for (i=0;i<pr->used_targets_off;i++)
3388 if (pr->used_targets[i].pid == prq->sender->pid)
3390 if (i < pr->used_targets_off)
3392 cur_delay = GNUNET_TIME_absolute_get_duration (pr->used_targets[i].last_request_time);
3393 prq->sender->avg_delay.rel_value
3394 = (prq->sender->avg_delay.rel_value *
3395 (RUNAVG_DELAY_N - 1) + cur_delay.rel_value) / RUNAVG_DELAY_N;
3396 prq->sender->avg_priority
3397 = (prq->sender->avg_priority *
3398 (RUNAVG_DELAY_N - 1) + pr->priority) / (double) RUNAVG_DELAY_N;
3402 GNUNET_PEER_change_rc (prq->sender->last_p2p_replies
3403 [prq->sender->last_p2p_replies_woff % P2P_SUCCESS_LIST_SIZE],
3405 GNUNET_PEER_change_rc (pr->cp->pid, 1);
3406 prq->sender->last_p2p_replies
3407 [(prq->sender->last_p2p_replies_woff++) % P2P_SUCCESS_LIST_SIZE]
3412 if (NULL != prq->sender->last_client_replies
3413 [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE])
3414 GNUNET_SERVER_client_drop (prq->sender->last_client_replies
3415 [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE]);
3416 prq->sender->last_client_replies
3417 [(prq->sender->last_client_replies_woff++) % CS2P_SUCCESS_LIST_SIZE]
3418 = pr->client_request_list->client_list->client;
3419 GNUNET_SERVER_client_keep (pr->client_request_list->client_list->client);
3422 prq->eval = GNUNET_BLOCK_evaluate (block_ctx,
3427 pr->namespace, (pr->namespace != NULL) ? sizeof (GNUNET_HashCode) : 0,
3432 case GNUNET_BLOCK_EVALUATION_OK_MORE:
3434 case GNUNET_BLOCK_EVALUATION_OK_LAST:
3435 while (NULL != pr->pending_head)
3436 destroy_pending_message_list_entry (pr->pending_head);
3439 if (pr->client_request_list != NULL)
3440 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
3442 GNUNET_DATASTORE_cancel (pr->qe);
3445 pr->do_remove = GNUNET_YES;
3446 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
3448 GNUNET_SCHEDULER_cancel (pr->task);
3449 pr->task = GNUNET_SCHEDULER_NO_TASK;
3451 GNUNET_break (GNUNET_YES ==
3452 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
3455 GNUNET_LOAD_update (rt_entry_lifetime,
3456 GNUNET_TIME_absolute_get_duration (pr->start_time).rel_value);
3458 case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
3459 GNUNET_STATISTICS_update (stats,
3460 gettext_noop ("# duplicate replies discarded (bloomfilter)"),
3464 /* GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3465 "Duplicate response `%s', discarding.\n",
3466 GNUNET_h2s (&mhash));*/
3468 return GNUNET_YES; /* duplicate */
3469 case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
3470 return GNUNET_YES; /* wrong namespace */
3471 case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
3474 case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
3477 case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
3478 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3479 _("Unsupported block type %u\n"),
3483 if (pr->client_request_list != NULL)
3485 if (pr->replies_seen_size == pr->replies_seen_off)
3486 GNUNET_array_grow (pr->replies_seen,
3487 pr->replies_seen_size,
3488 pr->replies_seen_size * 2 + 4);
3489 GNUNET_CRYPTO_hash (prq->data,
3491 &pr->replies_seen[pr->replies_seen_off++]);
3492 refresh_bloomfilter (pr);
3494 if (NULL == prq->sender)
3497 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3498 "Found result for query `%s' in local datastore\n",
3501 GNUNET_STATISTICS_update (stats,
3502 gettext_noop ("# results found locally"),
3506 prq->priority += pr->remaining_priority;
3507 pr->remaining_priority = 0;
3508 pr->results_found++;
3509 prq->request_found = GNUNET_YES;
3510 if (NULL != pr->client_request_list)
3512 GNUNET_STATISTICS_update (stats,
3513 gettext_noop ("# replies received for local clients"),
3516 cl = pr->client_request_list->client_list;
3517 msize = sizeof (struct PutMessage) + prq->size;
3518 creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
3519 creply->msize = msize;
3520 creply->client_list = cl;
3521 GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
3525 pm = (struct PutMessage*) &creply[1];
3526 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
3527 pm->header.size = htons (msize);
3528 pm->type = htonl (prq->type);
3529 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
3530 memcpy (&pm[1], prq->data, prq->size);
3534 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3535 "Transmitting result for query `%s' to client\n",
3538 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
3540 GNUNET_TIME_UNIT_FOREVER_REL,
3541 &transmit_to_client,
3544 GNUNET_break (cl->th != NULL);
3547 prq->finished = GNUNET_YES;
3548 destroy_pending_request (pr);
3555 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3556 "Transmitting result for query `%s' to other peer (PID=%u)\n",
3558 (unsigned int) cp->pid);
3560 GNUNET_STATISTICS_update (stats,
3561 gettext_noop ("# replies received for other peers"),
3564 msize = sizeof (struct PutMessage) + prq->size;
3565 reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
3566 reply->cont = &transmit_reply_continuation;
3567 reply->cont_cls = pr;
3569 art_delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
3570 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3573 = GNUNET_TIME_relative_to_absolute (art_delay);
3574 GNUNET_STATISTICS_update (stats,
3575 gettext_noop ("cummulative artificial delay introduced (ms)"),
3576 art_delay.abs_value,
3579 reply->msize = msize;
3580 reply->priority = UINT32_MAX; /* send replies first! */
3581 pm = (struct PutMessage*) &reply[1];
3582 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
3583 pm->header.size = htons (msize);
3584 pm->type = htonl (prq->type);
3585 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
3586 memcpy (&pm[1], prq->data, prq->size);
3587 add_to_pending_messages_for_peer (cp, reply, pr);
3594 * Iterator called on each result obtained for a DHT
3595 * operation that expects a reply
3597 * @param cls closure
3598 * @param exp when will this value expire
3599 * @param key key of the result
3600 * @param get_path NULL-terminated array of pointers
3601 * to the peers on reverse GET path (or NULL if not recorded)
3602 * @param put_path NULL-terminated array of pointers
3603 * to the peers on the PUT path (or NULL if not recorded)
3604 * @param type type of the result
3605 * @param size number of bytes in data
3606 * @param data pointer to the result data
3609 process_dht_reply (void *cls,
3610 struct GNUNET_TIME_Absolute exp,
3611 const GNUNET_HashCode * key,
3612 const struct GNUNET_PeerIdentity * const *get_path,
3613 const struct GNUNET_PeerIdentity * const *put_path,
3614 enum GNUNET_BLOCK_Type type,
3618 struct PendingRequest *pr = cls;
3619 struct ProcessReplyClosure prq;
3621 memset (&prq, 0, sizeof (prq));
3623 prq.expiration = exp;
3626 process_reply (&prq, key, pr);
3632 * Continuation called to notify client about result of the
3635 * @param cls closure
3636 * @param success GNUNET_SYSERR on failure
3637 * @param msg NULL on success, otherwise an error message
3640 put_migration_continuation (void *cls,
3644 struct GNUNET_TIME_Absolute *start = cls;
3645 struct GNUNET_TIME_Relative delay;
3647 delay = GNUNET_TIME_absolute_get_duration (*start);
3648 GNUNET_free (start);
3649 GNUNET_LOAD_update (datastore_put_load,
3651 if (GNUNET_OK == success)
3653 GNUNET_STATISTICS_update (stats,
3654 gettext_noop ("# datastore 'put' failures"),
3661 * Handle P2P "PUT" message.
3663 * @param cls closure, always NULL
3664 * @param other the other peer involved (sender or receiver, NULL
3665 * for loopback messages where we are both sender and receiver)
3666 * @param message the actual message
3667 * @param atsi performance information
3668 * @return GNUNET_OK to keep the connection open,
3669 * GNUNET_SYSERR to close it (signal serious error)
3672 handle_p2p_put (void *cls,
3673 const struct GNUNET_PeerIdentity *other,
3674 const struct GNUNET_MessageHeader *message,
3675 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
3677 const struct PutMessage *put;
3680 enum GNUNET_BLOCK_Type type;
3681 struct GNUNET_TIME_Absolute expiration;
3682 GNUNET_HashCode query;
3683 struct ProcessReplyClosure prq;
3684 struct GNUNET_TIME_Absolute *start;
3685 struct GNUNET_TIME_Relative block_time;
3687 struct ConnectedPeer *cp;
3688 struct PendingMessage *pm;
3689 struct MigrationStopMessage *msm;
3691 msize = ntohs (message->size);
3692 if (msize < sizeof (struct PutMessage))
3695 return GNUNET_SYSERR;
3697 put = (const struct PutMessage*) message;
3698 dsize = msize - sizeof (struct PutMessage);
3699 type = ntohl (put->type);
3700 expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
3702 if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
3703 return GNUNET_SYSERR;
3705 GNUNET_BLOCK_get_key (block_ctx,
3711 GNUNET_break_op (0);
3712 return GNUNET_SYSERR;
3714 cover_content_count++;
3716 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3717 "Received result for query `%s' from peer `%4s'\n",
3718 GNUNET_h2s (&query),
3719 GNUNET_i2s (other));
3721 GNUNET_STATISTICS_update (stats,
3722 gettext_noop ("# replies received (overall)"),
3725 /* now, lookup 'query' */
3726 prq.data = (const void*) &put[1];
3728 prq.sender = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3729 &other->hashPubKey);
3734 prq.expiration = expiration;
3736 prq.anonymity_level = 1;
3737 prq.finished = GNUNET_NO;
3738 prq.request_found = GNUNET_NO;
3739 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
3743 if (prq.sender != NULL)
3745 prq.sender->inc_preference += CONTENT_BANDWIDTH_VALUE + 1000 * prq.priority;
3746 change_host_trust (prq.sender, prq.priority);
3748 if ( (GNUNET_YES == active_to_migration) &&
3749 (GNUNET_NO == test_put_load_too_high (prq.priority)) )
3752 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3753 "Replicating result for query `%s' with priority %u\n",
3754 GNUNET_h2s (&query),
3757 start = GNUNET_malloc (sizeof (struct GNUNET_TIME_Absolute));
3758 *start = GNUNET_TIME_absolute_get ();
3759 GNUNET_DATASTORE_put (dsh,
3760 0, &query, dsize, &put[1],
3761 type, prq.priority, 1 /* anonymity */,
3763 1 + prq.priority, MAX_DATASTORE_QUEUE,
3764 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
3765 &put_migration_continuation,
3768 putl = GNUNET_LOAD_get_load (datastore_put_load);
3769 if ( (NULL != (cp = prq.sender)) &&
3770 (GNUNET_NO == prq.request_found) &&
3771 ( (GNUNET_YES != active_to_migration) ||
3772 (putl > 2.5 * (1 + prq.priority)) ) )
3774 if (GNUNET_TIME_absolute_get_duration (cp->last_migration_block).rel_value < 5000)
3775 return GNUNET_OK; /* already blocked */
3776 /* We're too busy; send MigrationStop message! */
3777 if (GNUNET_YES != active_to_migration)
3778 putl = 1.0 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 5);
3779 block_time = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
3780 5000 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3781 (unsigned int) (60000 * putl * putl)));
3783 cp->last_migration_block = GNUNET_TIME_relative_to_absolute (block_time);
3784 pm = GNUNET_malloc (sizeof (struct PendingMessage) +
3785 sizeof (struct MigrationStopMessage));
3786 pm->msize = sizeof (struct MigrationStopMessage);
3787 pm->priority = UINT32_MAX;
3788 msm = (struct MigrationStopMessage*) &pm[1];
3789 msm->header.size = htons (sizeof (struct MigrationStopMessage));
3790 msm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP);
3791 msm->duration = GNUNET_TIME_relative_hton (block_time);
3792 add_to_pending_messages_for_peer (cp,
3801 * Handle P2P "MIGRATION_STOP" message.
3803 * @param cls closure, always NULL
3804 * @param other the other peer involved (sender or receiver, NULL
3805 * for loopback messages where we are both sender and receiver)
3806 * @param message the actual message
3807 * @param atsi performance information
3808 * @return GNUNET_OK to keep the connection open,
3809 * GNUNET_SYSERR to close it (signal serious error)
3812 handle_p2p_migration_stop (void *cls,
3813 const struct GNUNET_PeerIdentity *other,
3814 const struct GNUNET_MessageHeader *message,
3815 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
3817 struct ConnectedPeer *cp;
3818 const struct MigrationStopMessage *msm;
3820 msm = (const struct MigrationStopMessage*) message;
3821 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3822 &other->hashPubKey);
3828 cp->migration_blocked = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (msm->duration));
3834 /* **************************** P2P GET Handling ************************ */
3838 * Closure for 'check_duplicate_request_{peer,client}'.
3840 struct CheckDuplicateRequestClosure
3843 * The new request we should check if it already exists.
3845 const struct PendingRequest *pr;
3848 * Existing request found by the checker, NULL if none.
3850 struct PendingRequest *have;
3855 * Iterator over entries in the 'query_request_map' that
3856 * tries to see if we have the same request pending from
3857 * the same client already.
3859 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
3860 * @param key current key code (query, ignored, must match)
3861 * @param value value in the hash map (a 'struct PendingRequest'
3862 * that already exists)
3863 * @return GNUNET_YES if we should continue to
3864 * iterate (no match yet)
3865 * GNUNET_NO if not (match found).
3868 check_duplicate_request_client (void *cls,
3869 const GNUNET_HashCode * key,
3872 struct CheckDuplicateRequestClosure *cdc = cls;
3873 struct PendingRequest *have = value;
3875 if (have->client_request_list == NULL)
3877 if ( (cdc->pr->client_request_list->client_list->client == have->client_request_list->client_list->client) &&
3888 * We're processing (local) results for a search request
3889 * from another peer. Pass applicable results to the
3890 * peer and if we are done either clean up (operation
3891 * complete) or forward to other peers (more results possible).
3893 * @param cls our closure (struct LocalGetContext)
3894 * @param key key for the content
3895 * @param size number of bytes in data
3896 * @param data content stored
3897 * @param type type of the content
3898 * @param priority priority of the content
3899 * @param anonymity anonymity-level for the content
3900 * @param expiration expiration time for the content
3901 * @param uid unique identifier for the datum;
3902 * maybe 0 if no unique identifier is available
3905 process_local_reply (void *cls,
3906 const GNUNET_HashCode * key,
3909 enum GNUNET_BLOCK_Type type,
3912 struct GNUNET_TIME_Absolute
3916 struct PendingRequest *pr = cls;
3917 struct ProcessReplyClosure prq;
3918 struct CheckDuplicateRequestClosure cdrc;
3919 GNUNET_HashCode query;
3920 unsigned int old_rf;
3925 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3926 "Done processing local replies, forwarding request to other peers.\n");
3929 if (pr->client_request_list != NULL)
3931 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
3933 /* Figure out if this is a duplicate request and possibly
3934 merge 'struct PendingRequest' entries */
3937 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
3939 &check_duplicate_request_client,
3941 if (cdrc.have != NULL)
3944 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3945 "Received request for block `%s' twice from client, will only request once.\n",
3946 GNUNET_h2s (&pr->query));
3949 destroy_pending_request (pr);
3953 if (pr->local_only == GNUNET_YES)
3955 destroy_pending_request (pr);
3958 /* no more results */
3959 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
3960 pr->task = GNUNET_SCHEDULER_add_now (&forward_request_task,
3965 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3966 "New local response to `%s' of type %u.\n",
3970 if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
3973 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3974 "Found ONDEMAND block, performing on-demand encoding\n");
3976 GNUNET_STATISTICS_update (stats,
3977 gettext_noop ("# on-demand blocks matched requests"),
3981 GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
3982 anonymity, expiration, uid,
3983 &process_local_reply,
3987 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3991 old_rf = pr->results_found;
3992 memset (&prq, 0, sizeof (prq));
3994 prq.expiration = expiration;
3997 GNUNET_BLOCK_get_key (block_ctx,
4004 GNUNET_DATASTORE_remove (dsh,
4008 GNUNET_TIME_UNIT_FOREVER_REL,
4010 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
4014 prq.priority = priority;
4015 prq.finished = GNUNET_NO;
4016 prq.request_found = GNUNET_NO;
4017 prq.anonymity_level = anonymity;
4018 if ( (old_rf == 0) &&
4019 (pr->results_found == 0) )
4020 update_datastore_delays (pr->start_time);
4021 process_reply (&prq, key, pr);
4022 if (prq.finished == GNUNET_YES)
4025 return; /* done here */
4026 if (prq.eval == GNUNET_BLOCK_EVALUATION_OK_LAST)
4028 pr->local_only = GNUNET_YES; /* do not forward */
4029 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
4032 if ( (pr->client_request_list == NULL) &&
4033 ( (GNUNET_YES == test_get_load_too_high (0)) ||
4034 (pr->results_found > 5 + 2 * pr->priority) ) )
4037 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4038 "Load too high, done with request\n");
4040 GNUNET_STATISTICS_update (stats,
4041 gettext_noop ("# processing result set cut short due to load"),
4044 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
4047 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
4052 * We've received a request with the specified priority. Bound it
4053 * according to how much we trust the given peer.
4055 * @param prio_in requested priority
4056 * @param cp the peer making the request
4057 * @return effective priority
4060 bound_priority (uint32_t prio_in,
4061 struct ConnectedPeer *cp)
4063 #define N ((double)128.0)
4068 ld = test_get_load_too_high (0);
4069 if (ld == GNUNET_SYSERR)
4071 GNUNET_STATISTICS_update (stats,
4072 gettext_noop ("# requests done for free (low load)"),
4075 return 0; /* excess resources */
4077 if (prio_in > INT32_MAX)
4078 prio_in = INT32_MAX;
4079 ret = - change_host_trust (cp, - (int) prio_in);
4082 if (ret > current_priorities + N)
4083 rret = current_priorities + N;
4087 = (current_priorities * (N-1) + rret)/N;
4089 if ( (ld == GNUNET_YES) && (ret > 0) )
4091 /* try with charging */
4092 ld = test_get_load_too_high (ret);
4094 if (ld == GNUNET_YES)
4096 GNUNET_STATISTICS_update (stats,
4097 gettext_noop ("# request dropped, priority insufficient"),
4101 change_host_trust (cp, (int) ret);
4102 return -1; /* not enough resources */
4106 GNUNET_STATISTICS_update (stats,
4107 gettext_noop ("# requests done for a price (normal load)"),
4117 * Iterator over entries in the 'query_request_map' that
4118 * tries to see if we have the same request pending from
4119 * the same peer already.
4121 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
4122 * @param key current key code (query, ignored, must match)
4123 * @param value value in the hash map (a 'struct PendingRequest'
4124 * that already exists)
4125 * @return GNUNET_YES if we should continue to
4126 * iterate (no match yet)
4127 * GNUNET_NO if not (match found).
4130 check_duplicate_request_peer (void *cls,
4131 const GNUNET_HashCode * key,
4134 struct CheckDuplicateRequestClosure *cdc = cls;
4135 struct PendingRequest *have = value;
4137 if (cdc->pr->target_pid == have->target_pid)
4147 * Handle P2P "GET" request.
4149 * @param cls closure, always NULL
4150 * @param other the other peer involved (sender or receiver, NULL
4151 * for loopback messages where we are both sender and receiver)
4152 * @param message the actual message
4153 * @param atsi performance information
4154 * @return GNUNET_OK to keep the connection open,
4155 * GNUNET_SYSERR to close it (signal serious error)
4158 handle_p2p_get (void *cls,
4159 const struct GNUNET_PeerIdentity *other,
4160 const struct GNUNET_MessageHeader *message,
4161 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
4163 struct PendingRequest *pr;
4164 struct ConnectedPeer *cp;
4165 struct ConnectedPeer *cps;
4166 struct CheckDuplicateRequestClosure cdc;
4167 struct GNUNET_TIME_Relative timeout;
4169 const struct GetMessage *gm;
4171 const GNUNET_HashCode *opt;
4174 uint32_t ttl_decrement;
4176 enum GNUNET_BLOCK_Type type;
4179 msize = ntohs(message->size);
4180 if (msize < sizeof (struct GetMessage))
4182 GNUNET_break_op (0);
4183 return GNUNET_SYSERR;
4185 gm = (const struct GetMessage*) message;
4187 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4188 "Received request for `%s'\n",
4189 GNUNET_h2s (&gm->query));
4191 type = ntohl (gm->type);
4192 bm = ntohl (gm->hash_bitmap);
4200 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
4202 GNUNET_break_op (0);
4203 return GNUNET_SYSERR;
4205 opt = (const GNUNET_HashCode*) &gm[1];
4206 bfsize = msize - sizeof (struct GetMessage) - bits * sizeof (GNUNET_HashCode);
4207 /* bfsize must be power of 2, check! */
4208 if (0 != ( (bfsize - 1) & bfsize))
4210 GNUNET_break_op (0);
4211 return GNUNET_SYSERR;
4213 cover_query_count++;
4214 bm = ntohl (gm->hash_bitmap);
4216 cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
4217 &other->hashPubKey);
4220 /* peer must have just disconnected */
4221 GNUNET_STATISTICS_update (stats,
4222 gettext_noop ("# requests dropped due to initiator not being connected"),
4225 return GNUNET_SYSERR;
4227 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
4228 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
4235 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
4236 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4237 "Failed to find RETURN-TO peer `%4s' in connection set. Dropping query.\n",
4238 GNUNET_i2s ((const struct GNUNET_PeerIdentity*) &opt[bits-1]));
4241 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4242 "Failed to find peer `%4s' in connection set. Dropping query.\n",
4243 GNUNET_i2s (other));
4245 GNUNET_STATISTICS_update (stats,
4246 gettext_noop ("# requests dropped due to missing reverse route"),
4249 /* FIXME: try connect? */
4252 /* note that we can really only check load here since otherwise
4253 peers could find out that we are overloaded by not being
4254 disconnected after sending us a malformed query... */
4255 priority = bound_priority (ntohl (gm->priority), cps);
4259 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4260 "Dropping query from `%s', this peer is too busy.\n",
4261 GNUNET_i2s (other));
4266 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4267 "Received request for `%s' of type %u from peer `%4s' with flags %u\n",
4268 GNUNET_h2s (&gm->query),
4269 (unsigned int) type,
4273 have_ns = (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE));
4274 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
4275 (have_ns ? sizeof(GNUNET_HashCode) : 0));
4278 pr->namespace = (GNUNET_HashCode*) &pr[1];
4279 memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
4281 if ( (GNUNET_LOAD_get_load (cp->transmission_delay) > 3 * (1 + priority)) ||
4282 (GNUNET_LOAD_get_average (cp->transmission_delay) >
4283 GNUNET_CONSTANTS_MAX_CORK_DELAY.rel_value * 2 + GNUNET_LOAD_get_average (rt_entry_lifetime)) )
4285 /* don't have BW to send to peer, or would likely take longer than we have for it,
4286 so at best indirect the query */
4288 pr->forward_only = GNUNET_YES;
4291 pr->mingle = ntohl (gm->filter_mutator);
4292 if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
4293 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
4294 pr->anonymity_level = 1;
4295 pr->priority = (uint32_t) priority;
4296 pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
4297 pr->query = gm->query;
4298 /* decrement ttl (always) */
4299 ttl_decrement = 2 * TTL_DECREMENT +
4300 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
4302 if ( (pr->ttl < 0) &&
4303 (((int32_t)(pr->ttl - ttl_decrement)) > 0) )
4306 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4307 "Dropping query from `%s' due to TTL underflow (%d - %u).\n",
4312 GNUNET_STATISTICS_update (stats,
4313 gettext_noop ("# requests dropped due TTL underflow"),
4316 /* integer underflow => drop (should be very rare)! */
4320 pr->ttl -= ttl_decrement;
4321 pr->start_time = GNUNET_TIME_absolute_get ();
4323 /* get bloom filter */
4326 pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
4329 pr->bf_size = bfsize;
4333 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
4335 &check_duplicate_request_peer,
4337 if (cdc.have != NULL)
4339 if (cdc.have->start_time.abs_value + cdc.have->ttl >=
4340 pr->start_time.abs_value + pr->ttl)
4342 /* existing request has higher TTL, drop new one! */
4343 cdc.have->priority += pr->priority;
4344 destroy_pending_request (pr);
4346 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4347 "Have existing request with higher TTL, dropping new request.\n",
4348 GNUNET_i2s (other));
4350 GNUNET_STATISTICS_update (stats,
4351 gettext_noop ("# requests dropped due to higher-TTL request"),
4358 /* existing request has lower TTL, drop old one! */
4359 pr->priority += cdc.have->priority;
4360 /* Possible optimization: if we have applicable pending
4361 replies in 'cdc.have', we might want to move those over
4362 (this is a really rare special-case, so it is not clear
4363 that this would be worth it) */
4364 destroy_pending_request (cdc.have);
4365 /* keep processing 'pr'! */
4370 GNUNET_break (GNUNET_OK ==
4371 GNUNET_CONTAINER_multihashmap_put (query_request_map,
4374 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
4375 GNUNET_break (GNUNET_OK ==
4376 GNUNET_CONTAINER_multihashmap_put (peer_request_map,
4379 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
4381 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
4383 pr->start_time.abs_value + pr->ttl);
4385 GNUNET_STATISTICS_update (stats,
4386 gettext_noop ("# P2P searches received"),
4389 GNUNET_STATISTICS_update (stats,
4390 gettext_noop ("# P2P searches active"),
4394 /* calculate change in traffic preference */
4395 cps->inc_preference += pr->priority * 1000 + QUERY_BANDWIDTH_VALUE;
4396 /* process locally */
4397 if (type == GNUNET_BLOCK_TYPE_FS_DBLOCK)
4398 type = GNUNET_BLOCK_TYPE_ANY; /* to get on-demand as well */
4399 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
4400 (pr->priority + 1));
4401 if (GNUNET_YES != pr->forward_only)
4404 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4405 "Handing request for `%s' to datastore\n",
4406 GNUNET_h2s (&gm->query));
4408 pr->qe = GNUNET_DATASTORE_get (dsh,
4412 MAX_DATASTORE_QUEUE,
4414 &process_local_reply,
4418 GNUNET_STATISTICS_update (stats,
4419 gettext_noop ("# requests dropped by datastore (queue length limit)"),
4426 GNUNET_STATISTICS_update (stats,
4427 gettext_noop ("# requests forwarded due to high load"),
4432 /* Are multiple results possible (and did we look locally)? If so, start processing remotely now! */
4435 case GNUNET_BLOCK_TYPE_FS_DBLOCK:
4436 case GNUNET_BLOCK_TYPE_FS_IBLOCK:
4437 /* only one result, wait for datastore */
4438 if (GNUNET_YES != pr->forward_only)
4440 GNUNET_STATISTICS_update (stats,
4441 gettext_noop ("# requests not instantly forwarded (waiting for datastore)"),
4447 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
4448 pr->task = GNUNET_SCHEDULER_add_now (&forward_request_task,
4452 /* make sure we don't track too many requests */
4453 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
4455 pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
4456 GNUNET_assert (pr != NULL);
4457 destroy_pending_request (pr);
4463 /* **************************** CS GET Handling ************************ */
4467 * Handle START_SEARCH-message (search request from client).
4469 * @param cls closure
4470 * @param client identification of the client
4471 * @param message the actual message
4474 handle_start_search (void *cls,
4475 struct GNUNET_SERVER_Client *client,
4476 const struct GNUNET_MessageHeader *message)
4478 static GNUNET_HashCode all_zeros;
4479 const struct SearchMessage *sm;
4480 struct ClientList *cl;
4481 struct ClientRequestList *crl;
4482 struct PendingRequest *pr;
4485 enum GNUNET_BLOCK_Type type;
4487 msize = ntohs (message->size);
4488 if ( (msize < sizeof (struct SearchMessage)) ||
4489 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
4492 GNUNET_SERVER_receive_done (client,
4496 GNUNET_STATISTICS_update (stats,
4497 gettext_noop ("# client searches received"),
4500 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
4501 sm = (const struct SearchMessage*) message;
4502 type = ntohl (sm->type);
4504 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4505 "Received request for `%s' of type %u from local client\n",
4506 GNUNET_h2s (&sm->query),
4507 (unsigned int) type);
4510 while ( (cl != NULL) &&
4511 (cl->client != client) )
4515 cl = GNUNET_malloc (sizeof (struct ClientList));
4516 cl->client = client;
4517 GNUNET_SERVER_client_keep (client);
4518 cl->next = client_list;
4521 /* detect duplicate KBLOCK requests */
4522 if ( (type == GNUNET_BLOCK_TYPE_FS_KBLOCK) ||
4523 (type == GNUNET_BLOCK_TYPE_FS_NBLOCK) ||
4524 (type == GNUNET_BLOCK_TYPE_ANY) )
4527 while ( (crl != NULL) &&
4528 ( (0 != memcmp (&crl->req->query,
4530 sizeof (GNUNET_HashCode))) ||
4531 (crl->req->type != type) ) )
4536 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4537 "Have existing request, merging content-seen lists.\n");
4540 /* Duplicate request (used to send long list of
4541 known/blocked results); merge 'pr->replies_seen'
4542 and update bloom filter */
4543 GNUNET_array_grow (pr->replies_seen,
4544 pr->replies_seen_size,
4545 pr->replies_seen_off + sc);
4546 memcpy (&pr->replies_seen[pr->replies_seen_off],
4548 sc * sizeof (GNUNET_HashCode));
4549 pr->replies_seen_off += sc;
4550 refresh_bloomfilter (pr);
4551 GNUNET_STATISTICS_update (stats,
4552 gettext_noop ("# client searches updated (merged content seen list)"),
4555 GNUNET_SERVER_receive_done (client,
4560 GNUNET_STATISTICS_update (stats,
4561 gettext_noop ("# client searches active"),
4564 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
4565 ((type == GNUNET_BLOCK_TYPE_FS_SBLOCK) ? sizeof(GNUNET_HashCode) : 0));
4566 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
4567 memset (crl, 0, sizeof (struct ClientRequestList));
4568 crl->client_list = cl;
4569 GNUNET_CONTAINER_DLL_insert (cl->rl_head,
4574 pr->client_request_list = crl;
4575 GNUNET_array_grow (pr->replies_seen,
4576 pr->replies_seen_size,
4578 memcpy (pr->replies_seen,
4580 sc * sizeof (GNUNET_HashCode));
4581 pr->replies_seen_off = sc;
4582 pr->anonymity_level = ntohl (sm->anonymity_level);
4583 pr->start_time = GNUNET_TIME_absolute_get ();
4584 refresh_bloomfilter (pr);
4585 pr->query = sm->query;
4586 if (0 == (1 & ntohl (sm->options)))
4587 pr->local_only = GNUNET_NO;
4589 pr->local_only = GNUNET_YES;
4592 case GNUNET_BLOCK_TYPE_FS_DBLOCK:
4593 case GNUNET_BLOCK_TYPE_FS_IBLOCK:
4594 if (0 != memcmp (&sm->target,
4596 sizeof (GNUNET_HashCode)))
4597 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
4599 case GNUNET_BLOCK_TYPE_FS_SBLOCK:
4600 pr->namespace = (GNUNET_HashCode*) &pr[1];
4601 memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
4606 GNUNET_break (GNUNET_OK ==
4607 GNUNET_CONTAINER_multihashmap_put (query_request_map,
4610 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
4611 if (type == GNUNET_BLOCK_TYPE_FS_DBLOCK)
4612 type = GNUNET_BLOCK_TYPE_ANY; /* get on-demand blocks too! */
4613 pr->qe = GNUNET_DATASTORE_get (dsh,
4617 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
4618 &process_local_reply,
4623 /* **************************** Startup ************************ */
4628 * Function called after GNUNET_CORE_connect has succeeded
4629 * (or failed for good). Note that the private key of the
4630 * peer is intentionally not exposed here; if you need it,
4631 * your process should try to read the private key file
4632 * directly (which should work if you are authorized...).
4634 * @param cls closure
4635 * @param server handle to the server, NULL if we failed
4636 * @param my_identity ID of this peer, NULL if we failed
4637 * @param publicKey public key of this peer, NULL if we failed
4640 peer_init_handler (void *cls,
4641 struct GNUNET_CORE_Handle * server,
4642 const struct GNUNET_PeerIdentity *
4645 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *
4648 my_id = *my_identity;
4655 * Process fs requests.
4657 * @param server the initialized server
4658 * @param c configuration to use
4661 main_init (struct GNUNET_SERVER_Handle *server,
4662 const struct GNUNET_CONFIGURATION_Handle *c)
4664 static const struct GNUNET_CORE_MessageHandler p2p_handlers[] =
4667 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
4669 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
4670 { &handle_p2p_migration_stop,
4671 GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP,
4672 sizeof (struct MigrationStopMessage) },
4675 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
4676 {&GNUNET_FS_handle_index_start, NULL,
4677 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
4678 {&GNUNET_FS_handle_index_list_get, NULL,
4679 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
4680 {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
4681 sizeof (struct UnindexMessage) },
4682 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
4686 unsigned long long enc = 128;
4689 stats = GNUNET_STATISTICS_create ("fs", cfg);
4690 min_migration_delay = GNUNET_TIME_UNIT_SECONDS;
4692 GNUNET_CONFIGURATION_get_value_number (cfg,
4694 "MAX_PENDING_REQUESTS",
4695 &max_pending_requests)) ||
4697 GNUNET_CONFIGURATION_get_value_number (cfg,
4699 "EXPECTED_NEIGHBOUR_COUNT",
4702 GNUNET_CONFIGURATION_get_value_time (cfg,
4704 "MIN_MIGRATION_DELAY",
4705 &min_migration_delay)) )
4707 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4708 _("Configuration fails to specify certain parameters, assuming default values."));
4710 connected_peers = GNUNET_CONTAINER_multihashmap_create (enc);
4711 query_request_map = GNUNET_CONTAINER_multihashmap_create (max_pending_requests);
4712 rt_entry_lifetime = GNUNET_LOAD_value_init (GNUNET_TIME_UNIT_FOREVER_REL);
4713 peer_request_map = GNUNET_CONTAINER_multihashmap_create (enc);
4714 requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
4715 core = GNUNET_CORE_connect (cfg,
4719 &peer_connect_handler,
4720 &peer_disconnect_handler,
4721 &peer_status_handler,
4727 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4728 _("Failed to connect to `%s' service.\n"),
4730 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
4731 connected_peers = NULL;
4732 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
4733 query_request_map = NULL;
4734 GNUNET_LOAD_value_free (rt_entry_lifetime);
4735 rt_entry_lifetime = NULL;
4736 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
4737 requests_by_expiration_heap = NULL;
4738 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
4739 peer_request_map = NULL;
4742 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
4745 return GNUNET_SYSERR;
4747 if (active_from_migration)
4749 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4750 _("Content migration is enabled, will start to gather data\n"));
4751 consider_migration_gathering ();
4753 consider_dht_put_gathering (NULL);
4754 GNUNET_SERVER_disconnect_notify (server,
4755 &handle_client_disconnect,
4757 GNUNET_assert (GNUNET_OK ==
4758 GNUNET_CONFIGURATION_get_value_filename (cfg,
4762 GNUNET_DISK_directory_create (trustDirectory);
4763 GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_HIGH,
4764 &cron_flush_trust, NULL);
4767 GNUNET_SERVER_add_handlers (server, handlers);
4768 cover_age_task = GNUNET_SCHEDULER_add_delayed (COVER_AGE_FREQUENCY,
4769 &age_cover_counters,
4771 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4779 * Process fs requests.
4781 * @param cls closure
4782 * @param server the initialized server
4783 * @param cfg configuration to use
4787 struct GNUNET_SERVER_Handle *server,
4788 const struct GNUNET_CONFIGURATION_Handle *cfg)
4790 active_to_migration = GNUNET_CONFIGURATION_get_value_yesno (cfg,
4793 active_from_migration = GNUNET_CONFIGURATION_get_value_yesno (cfg,
4796 dsh = GNUNET_DATASTORE_connect (cfg);
4799 GNUNET_SCHEDULER_shutdown ();
4802 datastore_get_load = GNUNET_LOAD_value_init (DATASTORE_LOAD_AUTODECLINE);
4803 datastore_put_load = GNUNET_LOAD_value_init (DATASTORE_LOAD_AUTODECLINE);
4804 block_cfg = GNUNET_CONFIGURATION_create ();
4805 GNUNET_CONFIGURATION_set_value_string (block_cfg,
4809 block_ctx = GNUNET_BLOCK_context_create (block_cfg);
4810 GNUNET_assert (NULL != block_ctx);
4811 dht_handle = GNUNET_DHT_connect (cfg,
4813 if ( (GNUNET_OK != GNUNET_FS_indexing_init (cfg, dsh)) ||
4814 (GNUNET_OK != main_init (server, cfg)) )
4816 GNUNET_SCHEDULER_shutdown ();
4817 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
4819 GNUNET_DHT_disconnect (dht_handle);
4821 GNUNET_BLOCK_context_destroy (block_ctx);
4823 GNUNET_CONFIGURATION_destroy (block_cfg);
4825 GNUNET_LOAD_value_free (datastore_get_load);
4826 datastore_get_load = NULL;
4827 GNUNET_LOAD_value_free (datastore_put_load);
4828 datastore_put_load = NULL;
4835 * The main function for the fs service.
4837 * @param argc number of arguments from the command line
4838 * @param argv command line arguments
4839 * @return 0 ok, 1 on error
4842 main (int argc, char *const *argv)
4844 return (GNUNET_OK ==
4845 GNUNET_SERVICE_run (argc,
4848 GNUNET_SERVICE_OPTION_NONE,
4849 &run, NULL)) ? 0 : 1;
4852 /* end of gnunet-service-fs.c */