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
27 * - track per-peer request latency (using new load API)
28 * - consider more precise latency estimation (per-peer & request) -- again load API?
29 * - implement test_load_too_high, make decision priority-based, implement forwarding, etc.
30 * - introduce random latency in processing
35 #include "gnunet_constants.h"
36 #include "gnunet_core_service.h"
37 #include "gnunet_dht_service.h"
38 #include "gnunet_datastore_service.h"
39 #include "gnunet_load_lib.h"
40 #include "gnunet_peer_lib.h"
41 #include "gnunet_protocols.h"
42 #include "gnunet_signatures.h"
43 #include "gnunet_statistics_service.h"
44 #include "gnunet_util_lib.h"
45 #include "gnunet-service-fs_indexing.h"
48 #define DEBUG_FS GNUNET_NO
51 * Maximum number of outgoing messages we queue per peer.
53 #define MAX_QUEUE_PER_PEER 16
56 * Size for the hash map for DHT requests from the FS
57 * service. Should be about the number of concurrent
58 * DHT requests we plan to make.
60 #define FS_DHT_HT_SIZE 1024
63 * How often do we flush trust values to disk?
65 #define TRUST_FLUSH_FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
68 * Inverse of the probability that we will submit the same query
69 * to the same peer again. If the same peer already got the query
70 * repeatedly recently, the probability is multiplied by the inverse
71 * of this number each time. Note that we only try about every TTL_DECREMENT/2
72 * plus MAX_CORK_DELAY (so roughly every 3.5s).
74 #define RETRY_PROBABILITY_INV 3
77 * What is the maximum delay for a P2P FS message (in our interaction
78 * with core)? FS-internal delays are another story. The value is
79 * chosen based on the 32k block size. Given that peers typcially
80 * have at least 1 kb/s bandwidth, 45s waits give us a chance to
81 * transmit one message even to the lowest-bandwidth peers.
83 #define MAX_TRANSMIT_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 45)
86 * Maximum number of requests (from other peers) that we're
87 * willing to have pending at any given point in time.
89 static unsigned long long max_pending_requests = (32 * 1024);
93 * Information we keep for each pending reply. The
94 * actual message follows at the end of this struct.
96 struct PendingMessage;
99 * Function called upon completion of a transmission.
102 * @param pid ID of receiving peer, 0 on transmission error
104 typedef void (*TransmissionContinuation)(void * cls,
105 GNUNET_PEER_Id tpid);
109 * Information we keep for each pending message (GET/PUT). The
110 * actual message follows at the end of this struct.
112 struct PendingMessage
115 * This is a doubly-linked list of messages to the same peer.
117 struct PendingMessage *next;
120 * This is a doubly-linked list of messages to the same peer.
122 struct PendingMessage *prev;
125 * Entry in pending message list for this pending message.
127 struct PendingMessageList *pml;
130 * Function to call immediately once we have transmitted this
133 TransmissionContinuation cont;
141 * Size of the reply; actual reply message follows
142 * at the end of this struct.
147 * How important is this message for us?
155 * Information about a peer that we are connected to.
156 * We track data that is useful for determining which
157 * peers should receive our requests. We also keep
158 * a list of messages to transmit to this peer.
164 * List of the last clients for which this peer successfully
167 struct GNUNET_SERVER_Client *last_client_replies[CS2P_SUCCESS_LIST_SIZE];
170 * List of the last PIDs for which
171 * this peer successfully answered a query;
172 * We use 0 to indicate no successful reply.
174 GNUNET_PEER_Id last_p2p_replies[P2P_SUCCESS_LIST_SIZE];
177 * Average delay between sending the peer a request and
178 * getting a reply (only calculated over the requests for
179 * which we actually got a reply). Calculated
180 * as a moving average: new_delay = ((n-1)*last_delay+curr_delay) / n
182 struct GNUNET_TIME_Relative avg_delay;
185 * Point in time until which this peer does not want us to migrate content
188 struct GNUNET_TIME_Absolute migration_blocked;
191 * Time until when we blocked this peer from migrating
194 struct GNUNET_TIME_Absolute last_migration_block;
197 * Handle for an active request for transmission to this
200 struct GNUNET_CORE_TransmitHandle *cth;
203 * Messages (replies, queries, content migration) we would like to
204 * send to this peer in the near future. Sorted by priority, head.
206 struct PendingMessage *pending_messages_head;
209 * Messages (replies, queries, content migration) we would like to
210 * send to this peer in the near future. Sorted by priority, tail.
212 struct PendingMessage *pending_messages_tail;
215 * Average priority of successful replies. Calculated
216 * as a moving average: new_avg = ((n-1)*last_avg+curr_prio) / n
221 * Increase in traffic preference still to be submitted
222 * to the core service for this peer.
224 uint64_t inc_preference;
227 * Trust rating for this peer
232 * Trust rating for this peer on disk.
237 * The peer's identity.
242 * Size of the linked list of 'pending_messages'.
244 unsigned int pending_requests;
247 * Which offset in "last_p2p_replies" will be updated next?
248 * (we go round-robin).
250 unsigned int last_p2p_replies_woff;
253 * Which offset in "last_client_replies" will be updated next?
254 * (we go round-robin).
256 unsigned int last_client_replies_woff;
262 * Information we keep for each pending request. We should try to
263 * keep this struct as small as possible since its memory consumption
264 * is key to how many requests we can have pending at once.
266 struct PendingRequest;
270 * Doubly-linked list of requests we are performing
271 * on behalf of the same client.
273 struct ClientRequestList
277 * This is a doubly-linked list.
279 struct ClientRequestList *next;
282 * This is a doubly-linked list.
284 struct ClientRequestList *prev;
287 * Request this entry represents.
289 struct PendingRequest *req;
292 * Client list this request belongs to.
294 struct ClientList *client_list;
300 * Replies to be transmitted to the client. The actual
301 * response message is allocated after this struct.
303 struct ClientResponseMessage
306 * This is a doubly-linked list.
308 struct ClientResponseMessage *next;
311 * This is a doubly-linked list.
313 struct ClientResponseMessage *prev;
316 * Client list entry this response belongs to.
318 struct ClientList *client_list;
321 * Number of bytes in the response.
328 * Linked list of clients we are performing requests
334 * This is a linked list.
336 struct ClientList *next;
339 * ID of a client making a request, NULL if this entry is for a
342 struct GNUNET_SERVER_Client *client;
345 * Head of list of requests performed on behalf
346 * of this client right now.
348 struct ClientRequestList *rl_head;
351 * Tail of list of requests performed on behalf
352 * of this client right now.
354 struct ClientRequestList *rl_tail;
357 * Head of linked list of responses.
359 struct ClientResponseMessage *res_head;
362 * Tail of linked list of responses.
364 struct ClientResponseMessage *res_tail;
367 * Context for sending replies.
369 struct GNUNET_CONNECTION_TransmitHandle *th;
375 * Doubly-linked list of messages we are performing
376 * due to a pending request.
378 struct PendingMessageList
382 * This is a doubly-linked list of messages on behalf of the same request.
384 struct PendingMessageList *next;
387 * This is a doubly-linked list of messages on behalf of the same request.
389 struct PendingMessageList *prev;
392 * Message this entry represents.
394 struct PendingMessage *pm;
397 * Request this entry belongs to.
399 struct PendingRequest *req;
402 * Peer this message is targeted for.
404 struct ConnectedPeer *target;
410 * Information we keep for each pending request. We should try to
411 * keep this struct as small as possible since its memory consumption
412 * is key to how many requests we can have pending at once.
414 struct PendingRequest
418 * If this request was made by a client, this is our entry in the
419 * client request list; otherwise NULL.
421 struct ClientRequestList *client_request_list;
424 * Entry of peer responsible for this entry (if this request
425 * was made by a peer).
427 struct ConnectedPeer *cp;
430 * If this is a namespace query, pointer to the hash of the public
431 * key of the namespace; otherwise NULL. Pointer will be to the
432 * end of this struct (so no need to free it).
434 const GNUNET_HashCode *namespace;
437 * Bloomfilter we use to filter out replies that we don't care about
438 * (anymore). NULL as long as we are interested in all replies.
440 struct GNUNET_CONTAINER_BloomFilter *bf;
443 * Context of our GNUNET_CORE_peer_change_preference call.
445 struct GNUNET_CORE_InformationRequestContext *irc;
448 * Reference to DHT get operation for this request (or NULL).
450 struct GNUNET_DHT_GetHandle *dht_get;
453 * Hash code of all replies that we have seen so far (only valid
454 * if client is not NULL since we only track replies like this for
457 GNUNET_HashCode *replies_seen;
460 * Node in the heap representing this entry; NULL
461 * if we have no heap node.
463 struct GNUNET_CONTAINER_HeapNode *hnode;
466 * Head of list of messages being performed on behalf of this
469 struct PendingMessageList *pending_head;
472 * Tail of list of messages being performed on behalf of this
475 struct PendingMessageList *pending_tail;
478 * When did we first see this request (form this peer), or, if our
479 * client is initiating, when did we last initiate a search?
481 struct GNUNET_TIME_Absolute start_time;
484 * The query that this request is for.
486 GNUNET_HashCode query;
489 * The task responsible for transmitting queries
492 GNUNET_SCHEDULER_TaskIdentifier task;
495 * (Interned) Peer identifier that identifies a preferred target
498 GNUNET_PEER_Id target_pid;
501 * (Interned) Peer identifiers of peers that have already
502 * received our query for this content.
504 GNUNET_PEER_Id *used_pids;
507 * Our entry in the queue (non-NULL while we wait for our
508 * turn to interact with the local database).
510 struct GNUNET_DATASTORE_QueueEntry *qe;
513 * Size of the 'bf' (in bytes).
518 * Desired anonymity level; only valid for requests from a local client.
520 uint32_t anonymity_level;
523 * How many entries in "used_pids" are actually valid?
525 unsigned int used_pids_off;
528 * How long is the "used_pids" array?
530 unsigned int used_pids_size;
533 * Number of results found for this request.
535 unsigned int results_found;
538 * How many entries in "replies_seen" are actually valid?
540 unsigned int replies_seen_off;
543 * How long is the "replies_seen" array?
545 unsigned int replies_seen_size;
548 * Priority with which this request was made. If one of our clients
549 * made the request, then this is the current priority that we are
550 * using when initiating the request. This value is used when
551 * we decide to reward other peers with trust for providing a reply.
556 * Priority points left for us to spend when forwarding this request
559 uint32_t remaining_priority;
562 * Number to mingle hashes for bloom-filter tests with.
567 * TTL with which we saw this request (or, if we initiated, TTL that
568 * we used for the request).
573 * Type of the content that this request is for.
575 enum GNUNET_BLOCK_Type type;
578 * Remove this request after transmission of the current response.
583 * GNUNET_YES if we should not forward this request to other peers.
591 * Block that is ready for migration to other peers. Actual data is at the end of the block.
593 struct MigrationReadyBlock
597 * This is a doubly-linked list.
599 struct MigrationReadyBlock *next;
602 * This is a doubly-linked list.
604 struct MigrationReadyBlock *prev;
607 * Query for the block.
609 GNUNET_HashCode query;
612 * When does this block expire?
614 struct GNUNET_TIME_Absolute expiration;
617 * Peers we would consider forwarding this
618 * block to. Zero for empty entries.
620 GNUNET_PEER_Id target_list[MIGRATION_LIST_SIZE];
628 * Number of targets already used.
630 unsigned int used_targets;
635 enum GNUNET_BLOCK_Type type;
640 * Our connection to the datastore.
642 static struct GNUNET_DATASTORE_Handle *dsh;
647 static struct GNUNET_BLOCK_Context *block_ctx;
650 * Our block configuration.
652 static struct GNUNET_CONFIGURATION_Handle *block_cfg;
657 static struct GNUNET_SCHEDULER_Handle *sched;
662 static const struct GNUNET_CONFIGURATION_Handle *cfg;
665 * Map of peer identifiers to "struct ConnectedPeer" (for that peer).
667 static struct GNUNET_CONTAINER_MultiHashMap *connected_peers;
670 * Map of peer identifiers to "struct PendingRequest" (for that peer).
672 static struct GNUNET_CONTAINER_MultiHashMap *peer_request_map;
675 * Map of query identifiers to "struct PendingRequest" (for that query).
677 static struct GNUNET_CONTAINER_MultiHashMap *query_request_map;
680 * Heap with the request that will expire next at the top. Contains
681 * pointers of type "struct PendingRequest*"; these will *also* be
682 * aliased from the "requests_by_peer" data structures and the
683 * "requests_by_query" table. Note that requests from our clients
684 * don't expire and are thus NOT in the "requests_by_expiration"
685 * (or the "requests_by_peer" tables).
687 static struct GNUNET_CONTAINER_Heap *requests_by_expiration_heap;
690 * Handle for reporting statistics.
692 static struct GNUNET_STATISTICS_Handle *stats;
695 * Linked list of clients we are currently processing requests for.
697 static struct ClientList *client_list;
700 * Pointer to handle to the core service (points to NULL until we've
703 static struct GNUNET_CORE_Handle *core;
706 * Head of linked list of blocks that can be migrated.
708 static struct MigrationReadyBlock *mig_head;
711 * Tail of linked list of blocks that can be migrated.
713 static struct MigrationReadyBlock *mig_tail;
716 * Request to datastore for migration (or NULL).
718 static struct GNUNET_DATASTORE_QueueEntry *mig_qe;
721 * Where do we store trust information?
723 static char *trustDirectory;
726 * ID of task that collects blocks for migration.
728 static GNUNET_SCHEDULER_TaskIdentifier mig_task;
731 * What is the maximum frequency at which we are allowed to
732 * poll the datastore for migration content?
734 static struct GNUNET_TIME_Relative min_migration_delay;
737 * Handle for DHT operations.
739 static struct GNUNET_DHT_Handle *dht_handle;
742 * Size of the doubly-linked list of migration blocks.
744 static unsigned int mig_size;
747 * Are we allowed to migrate content to this peer.
749 static int active_migration;
752 * Typical priorities we're seeing from other peers right now. Since
753 * most priorities will be zero, this value is the weighted average of
754 * non-zero priorities seen "recently". In order to ensure that new
755 * values do not dramatically change the ratio, values are first
756 * "capped" to a reasonable range (+N of the current value) and then
757 * averaged into the existing value by a ratio of 1:N. Hence
758 * receiving the largest possible priority can still only raise our
759 * "current_priorities" by at most 1.
761 static double current_priorities;
764 * Datastore 'GET' load tracking.
766 static struct GNUNET_LOAD_Value *datastore_get_load;
769 * Datastore 'PUT' load tracking.
771 static struct GNUNET_LOAD_Value *datastore_put_load;
775 * We've just now completed a datastore request. Update our
776 * datastore load calculations.
778 * @param start time when the datastore request was issued
781 update_datastore_delays (struct GNUNET_TIME_Absolute start)
783 struct GNUNET_TIME_Relative delay;
785 delay = GNUNET_TIME_absolute_get_duration (start);
786 GNUNET_LOAD_update (datastore_get_load,
792 * Get the filename under which we would store the GNUNET_HELLO_Message
793 * for the given host and protocol.
794 * @return filename of the form DIRECTORY/HOSTID
797 get_trust_filename (const struct GNUNET_PeerIdentity *id)
799 struct GNUNET_CRYPTO_HashAsciiEncoded fil;
802 GNUNET_CRYPTO_hash_to_enc (&id->hashPubKey, &fil);
803 GNUNET_asprintf (&fn, "%s%s%s", trustDirectory, DIR_SEPARATOR_STR, &fil);
810 * Transmit messages by copying it to the target buffer
811 * "buf". "buf" will be NULL and "size" zero if the socket was closed
812 * for writing in the meantime. In that case, do nothing
813 * (the disconnect or shutdown handler will take care of the rest).
814 * If we were able to transmit messages and there are still more
815 * pending, ask core again for further calls to this function.
817 * @param cls closure, pointer to the 'struct ConnectedPeer*'
818 * @param size number of bytes available in buf
819 * @param buf where the callee should write the message
820 * @return number of bytes written to buf
823 transmit_to_peer (void *cls,
824 size_t size, void *buf);
827 /* ******************* clean up functions ************************ */
830 * Delete the given migration block.
832 * @param mb block to delete
835 delete_migration_block (struct MigrationReadyBlock *mb)
837 GNUNET_CONTAINER_DLL_remove (mig_head,
840 GNUNET_PEER_decrement_rcs (mb->target_list,
841 MIGRATION_LIST_SIZE);
848 * Compare the distance of two peers to a key.
851 * @param p1 first peer
852 * @param p2 second peer
853 * @return GNUNET_YES if P1 is closer to key than P2
856 is_closer (const GNUNET_HashCode *key,
857 const struct GNUNET_PeerIdentity *p1,
858 const struct GNUNET_PeerIdentity *p2)
860 return GNUNET_CRYPTO_hash_xorcmp (&p1->hashPubKey,
867 * Consider migrating content to a given peer.
869 * @param cls 'struct MigrationReadyBlock*' to select
870 * targets for (or NULL for none)
871 * @param key ID of the peer
872 * @param value 'struct ConnectedPeer' of the peer
873 * @return GNUNET_YES (always continue iteration)
876 consider_migration (void *cls,
877 const GNUNET_HashCode *key,
880 struct MigrationReadyBlock *mb = cls;
881 struct ConnectedPeer *cp = value;
882 struct MigrationReadyBlock *pos;
883 struct GNUNET_PeerIdentity cppid;
884 struct GNUNET_PeerIdentity otherpid;
885 struct GNUNET_PeerIdentity worstpid;
890 /* consider 'cp' as a migration target for mb */
891 if (GNUNET_TIME_absolute_get_remaining (cp->migration_blocked).value > 0)
892 return GNUNET_YES; /* peer has requested no migration! */
895 GNUNET_PEER_resolve (cp->pid,
897 repl = MIGRATION_LIST_SIZE;
898 for (i=0;i<MIGRATION_LIST_SIZE;i++)
900 if (mb->target_list[i] == 0)
902 mb->target_list[i] = cp->pid;
903 GNUNET_PEER_change_rc (mb->target_list[i], 1);
904 repl = MIGRATION_LIST_SIZE;
907 GNUNET_PEER_resolve (mb->target_list[i],
909 if ( (repl == MIGRATION_LIST_SIZE) &&
910 is_closer (&mb->query,
917 else if ( (repl != MIGRATION_LIST_SIZE) &&
918 (is_closer (&mb->query,
926 if (repl != MIGRATION_LIST_SIZE)
928 GNUNET_PEER_change_rc (mb->target_list[repl], -1);
929 mb->target_list[repl] = cp->pid;
930 GNUNET_PEER_change_rc (mb->target_list[repl], 1);
934 /* consider scheduling transmission to cp for content migration */
941 for (i=0;i<MIGRATION_LIST_SIZE;i++)
943 if (cp->pid == pos->target_list[i])
948 msize = GNUNET_MIN (msize,
956 return GNUNET_YES; /* no content available */
958 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
959 "Trying to migrate at least %u bytes to peer `%s'\n",
964 = GNUNET_CORE_notify_transmit_ready (core,
965 0, GNUNET_TIME_UNIT_FOREVER_REL,
966 (const struct GNUNET_PeerIdentity*) key,
967 msize + sizeof (struct PutMessage),
975 * Task that is run periodically to obtain blocks for content
979 * @param tc scheduler context (also unused)
982 gather_migration_blocks (void *cls,
983 const struct GNUNET_SCHEDULER_TaskContext *tc);
987 * If the migration task is not currently running, consider
988 * (re)scheduling it with the appropriate delay.
991 consider_migration_gathering ()
993 struct GNUNET_TIME_Relative delay;
999 if (mig_task != GNUNET_SCHEDULER_NO_TASK)
1001 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
1003 delay = GNUNET_TIME_relative_divide (delay,
1004 MAX_MIGRATION_QUEUE);
1005 delay = GNUNET_TIME_relative_max (delay,
1006 min_migration_delay);
1007 mig_task = GNUNET_SCHEDULER_add_delayed (sched,
1009 &gather_migration_blocks,
1015 * Process content offered for migration.
1017 * @param cls closure
1018 * @param key key for the content
1019 * @param size number of bytes in data
1020 * @param data content stored
1021 * @param type type of the content
1022 * @param priority priority of the content
1023 * @param anonymity anonymity-level for the content
1024 * @param expiration expiration time for the content
1025 * @param uid unique identifier for the datum;
1026 * maybe 0 if no unique identifier is available
1029 process_migration_content (void *cls,
1030 const GNUNET_HashCode * key,
1033 enum GNUNET_BLOCK_Type type,
1036 struct GNUNET_TIME_Absolute
1037 expiration, uint64_t uid)
1039 struct MigrationReadyBlock *mb;
1044 if (mig_size < MAX_MIGRATION_QUEUE)
1045 consider_migration_gathering ();
1048 if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
1051 GNUNET_FS_handle_on_demand_block (key, size, data,
1052 type, priority, anonymity,
1054 &process_migration_content,
1057 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1062 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1063 "Retrieved block `%s' of type %u for migration\n",
1067 mb = GNUNET_malloc (sizeof (struct MigrationReadyBlock) + size);
1069 mb->expiration = expiration;
1072 memcpy (&mb[1], data, size);
1073 GNUNET_CONTAINER_DLL_insert_after (mig_head,
1078 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1079 &consider_migration,
1081 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1086 * Task that is run periodically to obtain blocks for content
1090 * @param tc scheduler context (also unused)
1093 gather_migration_blocks (void *cls,
1094 const struct GNUNET_SCHEDULER_TaskContext *tc)
1096 mig_task = GNUNET_SCHEDULER_NO_TASK;
1099 mig_qe = GNUNET_DATASTORE_get_random (dsh, 0, -1,
1100 GNUNET_TIME_UNIT_FOREVER_REL,
1101 &process_migration_content, NULL);
1102 GNUNET_assert (mig_qe != NULL);
1108 * We're done with a particular message list entry.
1109 * Free all associated resources.
1111 * @param pml entry to destroy
1114 destroy_pending_message_list_entry (struct PendingMessageList *pml)
1116 GNUNET_CONTAINER_DLL_remove (pml->req->pending_head,
1117 pml->req->pending_tail,
1119 GNUNET_CONTAINER_DLL_remove (pml->target->pending_messages_head,
1120 pml->target->pending_messages_tail,
1122 pml->target->pending_requests--;
1123 GNUNET_free (pml->pm);
1129 * Destroy the given pending message (and call the respective
1132 * @param pm message to destroy
1133 * @param tpid id of peer that the message was delivered to, or 0 for none
1136 destroy_pending_message (struct PendingMessage *pm,
1137 GNUNET_PEER_Id tpid)
1139 struct PendingMessageList *pml = pm->pml;
1140 TransmissionContinuation cont;
1145 GNUNET_assert (pml->pm == pm);
1146 GNUNET_assert ( (tpid == 0) || (tpid == pml->target->pid) );
1148 cont_cls = pm->cont_cls;
1149 destroy_pending_message_list_entry (pml);
1156 cont (cont_cls, tpid);
1161 * We're done processing a particular request.
1162 * Free all associated resources.
1164 * @param pr request to destroy
1167 destroy_pending_request (struct PendingRequest *pr)
1169 struct GNUNET_PeerIdentity pid;
1171 if (pr->hnode != NULL)
1173 GNUNET_CONTAINER_heap_remove_node (requests_by_expiration_heap,
1177 if (NULL == pr->client_request_list)
1179 GNUNET_STATISTICS_update (stats,
1180 gettext_noop ("# P2P searches active"),
1186 GNUNET_STATISTICS_update (stats,
1187 gettext_noop ("# client searches active"),
1191 /* might have already been removed from map in 'process_reply' (if
1192 there was a unique reply) or never inserted if it was a
1193 duplicate; hence ignore the return value here */
1194 (void) GNUNET_CONTAINER_multihashmap_remove (query_request_map,
1199 GNUNET_DATASTORE_cancel (pr->qe);
1202 if (pr->dht_get != NULL)
1204 GNUNET_DHT_get_stop (pr->dht_get);
1207 if (pr->client_request_list != NULL)
1209 GNUNET_CONTAINER_DLL_remove (pr->client_request_list->client_list->rl_head,
1210 pr->client_request_list->client_list->rl_tail,
1211 pr->client_request_list);
1212 GNUNET_free (pr->client_request_list);
1213 pr->client_request_list = NULL;
1217 GNUNET_PEER_resolve (pr->cp->pid,
1219 (void) GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
1226 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
1229 if (pr->irc != NULL)
1231 GNUNET_CORE_peer_change_preference_cancel (pr->irc);
1234 if (pr->replies_seen != NULL)
1236 GNUNET_free (pr->replies_seen);
1237 pr->replies_seen = NULL;
1239 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
1241 GNUNET_SCHEDULER_cancel (sched,
1243 pr->task = GNUNET_SCHEDULER_NO_TASK;
1245 while (NULL != pr->pending_head)
1246 destroy_pending_message_list_entry (pr->pending_head);
1247 GNUNET_PEER_change_rc (pr->target_pid, -1);
1248 if (pr->used_pids != NULL)
1250 GNUNET_PEER_decrement_rcs (pr->used_pids, pr->used_pids_off);
1251 GNUNET_free (pr->used_pids);
1252 pr->used_pids_off = 0;
1253 pr->used_pids_size = 0;
1254 pr->used_pids = NULL;
1261 * Method called whenever a given peer connects.
1263 * @param cls closure, not used
1264 * @param peer peer identity this notification is about
1265 * @param latency reported latency of the connection with 'other'
1266 * @param distance reported distance (DV) to 'other'
1269 peer_connect_handler (void *cls,
1271 GNUNET_PeerIdentity * peer,
1272 struct GNUNET_TIME_Relative latency,
1275 struct ConnectedPeer *cp;
1276 struct MigrationReadyBlock *pos;
1280 cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
1281 cp->pid = GNUNET_PEER_intern (peer);
1283 fn = get_trust_filename (peer);
1284 if ((GNUNET_DISK_file_test (fn) == GNUNET_YES) &&
1285 (sizeof (trust) == GNUNET_DISK_fn_read (fn, &trust, sizeof (trust))))
1286 cp->disk_trust = cp->trust = ntohl (trust);
1289 GNUNET_break (GNUNET_OK ==
1290 GNUNET_CONTAINER_multihashmap_put (connected_peers,
1293 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1298 (void) consider_migration (pos, &peer->hashPubKey, cp);
1305 * Increase the host credit by a value.
1307 * @param host which peer to change the trust value on
1308 * @param value is the int value by which the
1309 * host credit is to be increased or decreased
1310 * @returns the actual change in trust (positive or negative)
1313 change_host_trust (struct ConnectedPeer *host, int value)
1315 unsigned int old_trust;
1319 GNUNET_assert (host != NULL);
1320 old_trust = host->trust;
1323 if (host->trust + value < host->trust)
1325 value = UINT32_MAX - host->trust;
1326 host->trust = UINT32_MAX;
1329 host->trust += value;
1333 if (host->trust < -value)
1335 value = -host->trust;
1339 host->trust += value;
1346 * Write host-trust information to a file - flush the buffer entry!
1349 flush_trust (void *cls,
1350 const GNUNET_HashCode *key,
1353 struct ConnectedPeer *host = value;
1356 struct GNUNET_PeerIdentity pid;
1358 if (host->trust == host->disk_trust)
1359 return GNUNET_OK; /* unchanged */
1360 GNUNET_PEER_resolve (host->pid,
1362 fn = get_trust_filename (&pid);
1363 if (host->trust == 0)
1365 if ((0 != UNLINK (fn)) && (errno != ENOENT))
1366 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
1367 GNUNET_ERROR_TYPE_BULK, "unlink", fn);
1371 trust = htonl (host->trust);
1372 if (sizeof(uint32_t) == GNUNET_DISK_fn_write (fn, &trust,
1374 GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE
1375 | GNUNET_DISK_PERM_GROUP_READ | GNUNET_DISK_PERM_OTHER_READ))
1376 host->disk_trust = host->trust;
1383 * Call this method periodically to scan data/hosts for new hosts.
1386 cron_flush_trust (void *cls,
1387 const struct GNUNET_SCHEDULER_TaskContext *tc)
1390 if (NULL == connected_peers)
1392 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1397 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1399 GNUNET_SCHEDULER_add_delayed (tc->sched,
1400 TRUST_FLUSH_FREQ, &cron_flush_trust, NULL);
1405 * Free (each) request made by the peer.
1407 * @param cls closure, points to peer that the request belongs to
1408 * @param key current key code
1409 * @param value value in the hash map
1410 * @return GNUNET_YES (we should continue to iterate)
1413 destroy_request (void *cls,
1414 const GNUNET_HashCode * key,
1417 const struct GNUNET_PeerIdentity * peer = cls;
1418 struct PendingRequest *pr = value;
1420 GNUNET_break (GNUNET_YES ==
1421 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
1424 destroy_pending_request (pr);
1430 * Method called whenever a peer disconnects.
1432 * @param cls closure, not used
1433 * @param peer peer identity this notification is about
1436 peer_disconnect_handler (void *cls,
1438 GNUNET_PeerIdentity * peer)
1440 struct ConnectedPeer *cp;
1441 struct PendingMessage *pm;
1443 struct MigrationReadyBlock *pos;
1444 struct MigrationReadyBlock *next;
1446 GNUNET_CONTAINER_multihashmap_get_multiple (peer_request_map,
1450 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1454 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1456 if (NULL != cp->last_client_replies[i])
1458 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1459 cp->last_client_replies[i] = NULL;
1462 GNUNET_break (GNUNET_YES ==
1463 GNUNET_CONTAINER_multihashmap_remove (connected_peers,
1466 /* remove this peer from migration considerations; schedule
1469 while (NULL != (pos = next))
1472 for (i=0;i<MIGRATION_LIST_SIZE;i++)
1474 if (pos->target_list[i] == cp->pid)
1476 GNUNET_PEER_change_rc (pos->target_list[i], -1);
1477 pos->target_list[i] = 0;
1480 if (pos->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers))
1482 delete_migration_block (pos);
1483 consider_migration_gathering ();
1486 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1487 &consider_migration,
1490 GNUNET_PEER_change_rc (cp->pid, -1);
1491 GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
1492 if (NULL != cp->cth)
1493 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
1494 while (NULL != (pm = cp->pending_messages_head))
1495 destroy_pending_message (pm, 0 /* delivery failed */);
1496 GNUNET_break (0 == cp->pending_requests);
1502 * Iterator over hash map entries that removes all occurences
1503 * of the given 'client' from the 'last_client_replies' of the
1504 * given connected peer.
1506 * @param cls closure, the 'struct GNUNET_SERVER_Client*' to remove
1507 * @param key current key code (unused)
1508 * @param value value in the hash map (the 'struct ConnectedPeer*' to change)
1509 * @return GNUNET_YES (we should continue to iterate)
1512 remove_client_from_last_client_replies (void *cls,
1513 const GNUNET_HashCode * key,
1516 struct GNUNET_SERVER_Client *client = cls;
1517 struct ConnectedPeer *cp = value;
1520 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1522 if (cp->last_client_replies[i] == client)
1524 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1525 cp->last_client_replies[i] = NULL;
1533 * A client disconnected. Remove all of its pending queries.
1535 * @param cls closure, NULL
1536 * @param client identification of the client
1539 handle_client_disconnect (void *cls,
1540 struct GNUNET_SERVER_Client
1543 struct ClientList *pos;
1544 struct ClientList *prev;
1545 struct ClientRequestList *rcl;
1546 struct ClientResponseMessage *creply;
1552 while ( (NULL != pos) &&
1553 (pos->client != client) )
1559 return; /* no requests pending for this client */
1560 while (NULL != (rcl = pos->rl_head))
1562 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1563 "Destroying pending request `%s' on disconnect\n",
1564 GNUNET_h2s (&rcl->req->query));
1565 destroy_pending_request (rcl->req);
1568 client_list = pos->next;
1570 prev->next = pos->next;
1571 if (pos->th != NULL)
1573 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
1576 while (NULL != (creply = pos->res_head))
1578 GNUNET_CONTAINER_DLL_remove (pos->res_head,
1581 GNUNET_free (creply);
1583 GNUNET_SERVER_client_drop (pos->client);
1585 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1586 &remove_client_from_last_client_replies,
1592 * Iterator to free peer entries.
1594 * @param cls closure, unused
1595 * @param key current key code
1596 * @param value value in the hash map (peer entry)
1597 * @return GNUNET_YES (we should continue to iterate)
1600 clean_peer (void *cls,
1601 const GNUNET_HashCode * key,
1604 peer_disconnect_handler (NULL, (const struct GNUNET_PeerIdentity*) key);
1610 * Task run during shutdown.
1616 shutdown_task (void *cls,
1617 const struct GNUNET_SCHEDULER_TaskContext *tc)
1621 GNUNET_DATASTORE_cancel (mig_qe);
1624 if (GNUNET_SCHEDULER_NO_TASK != mig_task)
1626 GNUNET_SCHEDULER_cancel (sched, mig_task);
1627 mig_task = GNUNET_SCHEDULER_NO_TASK;
1629 while (client_list != NULL)
1630 handle_client_disconnect (NULL,
1631 client_list->client);
1632 cron_flush_trust (NULL, NULL);
1633 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1636 GNUNET_break (0 == GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap));
1637 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
1638 requests_by_expiration_heap = 0;
1639 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
1640 connected_peers = NULL;
1641 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (query_request_map));
1642 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
1643 query_request_map = NULL;
1644 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (peer_request_map));
1645 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
1646 peer_request_map = NULL;
1647 GNUNET_assert (NULL != core);
1648 GNUNET_CORE_disconnect (core);
1652 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1657 GNUNET_DATASTORE_disconnect (dsh,
1661 while (mig_head != NULL)
1662 delete_migration_block (mig_head);
1663 GNUNET_assert (0 == mig_size);
1664 GNUNET_DHT_disconnect (dht_handle);
1666 GNUNET_LOAD_value_free (datastore_get_load);
1667 datastore_get_load = NULL;
1668 GNUNET_LOAD_value_free (datastore_put_load);
1669 datastore_put_load = NULL;
1670 GNUNET_BLOCK_context_destroy (block_ctx);
1672 GNUNET_CONFIGURATION_destroy (block_cfg);
1676 GNUNET_free_non_null (trustDirectory);
1677 trustDirectory = NULL;
1681 /* ******************* Utility functions ******************** */
1685 * Transmit messages by copying it to the target buffer
1686 * "buf". "buf" will be NULL and "size" zero if the socket was closed
1687 * for writing in the meantime. In that case, do nothing
1688 * (the disconnect or shutdown handler will take care of the rest).
1689 * If we were able to transmit messages and there are still more
1690 * pending, ask core again for further calls to this function.
1692 * @param cls closure, pointer to the 'struct ConnectedPeer*'
1693 * @param size number of bytes available in buf
1694 * @param buf where the callee should write the message
1695 * @return number of bytes written to buf
1698 transmit_to_peer (void *cls,
1699 size_t size, void *buf)
1701 struct ConnectedPeer *cp = cls;
1703 struct GNUNET_PeerIdentity pid;
1704 struct PendingMessage *pm;
1705 struct MigrationReadyBlock *mb;
1706 struct MigrationReadyBlock *next;
1707 struct PutMessage migm;
1715 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1716 "Dropping message, core too busy.\n");
1721 while ( (NULL != (pm = cp->pending_messages_head) ) &&
1722 (pm->msize <= size) )
1724 memcpy (&cbuf[msize], &pm[1], pm->msize);
1727 destroy_pending_message (pm, cp->pid);
1731 GNUNET_PEER_resolve (cp->pid,
1733 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1735 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1744 while (NULL != (mb = next))
1747 for (i=0;i<MIGRATION_LIST_SIZE;i++)
1749 if ( (cp->pid == mb->target_list[i]) &&
1750 (mb->size + sizeof (migm) <= size) )
1752 GNUNET_PEER_change_rc (mb->target_list[i], -1);
1753 mb->target_list[i] = 0;
1755 memset (&migm, 0, sizeof (migm));
1756 migm.header.size = htons (sizeof (migm) + mb->size);
1757 migm.header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
1758 migm.type = htonl (mb->type);
1759 migm.expiration = GNUNET_TIME_absolute_hton (mb->expiration);
1760 memcpy (&cbuf[msize], &migm, sizeof (migm));
1761 msize += sizeof (migm);
1762 size -= sizeof (migm);
1763 memcpy (&cbuf[msize], &mb[1], mb->size);
1767 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1768 "Pushing migration block `%s' (%u bytes) to `%s'\n",
1769 GNUNET_h2s (&mb->query),
1778 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1779 "Migration block `%s' (%u bytes) is not on migration list for peer `%s'\n",
1780 GNUNET_h2s (&mb->query),
1786 if ( (mb->used_targets >= MIGRATION_TARGET_COUNT) ||
1787 (mb->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers)) )
1789 delete_migration_block (mb);
1790 consider_migration_gathering ();
1793 consider_migration (NULL,
1798 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1799 "Transmitting %u bytes to peer %u\n",
1808 * Add a message to the set of pending messages for the given peer.
1810 * @param cp peer to send message to
1811 * @param pm message to queue
1812 * @param pr request on which behalf this message is being queued
1815 add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
1816 struct PendingMessage *pm,
1817 struct PendingRequest *pr)
1819 struct PendingMessage *pos;
1820 struct PendingMessageList *pml;
1821 struct GNUNET_PeerIdentity pid;
1823 GNUNET_assert (pm->next == NULL);
1824 GNUNET_assert (pm->pml == NULL);
1827 pml = GNUNET_malloc (sizeof (struct PendingMessageList));
1832 GNUNET_CONTAINER_DLL_insert (pr->pending_head,
1836 pos = cp->pending_messages_head;
1837 while ( (pos != NULL) &&
1838 (pm->priority < pos->priority) )
1840 GNUNET_CONTAINER_DLL_insert_after (cp->pending_messages_head,
1841 cp->pending_messages_tail,
1844 cp->pending_requests++;
1845 if (cp->pending_requests > MAX_QUEUE_PER_PEER)
1846 destroy_pending_message (cp->pending_messages_tail, 0);
1847 GNUNET_PEER_resolve (cp->pid, &pid);
1848 if (NULL != cp->cth)
1849 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
1850 /* need to schedule transmission */
1851 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1852 cp->pending_messages_head->priority,
1855 cp->pending_messages_head->msize,
1858 if (cp->cth == NULL)
1861 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1862 "Failed to schedule transmission with core!\n");
1864 GNUNET_STATISTICS_update (stats,
1865 gettext_noop ("# CORE transmission failures"),
1873 * Test if the load on this peer is too high
1874 * to even consider processing the query at
1877 * @return GNUNET_YES if the load is too high to do anything, GNUNET_NO to forward (load high, but not too high), GNUNET_SYSERR to indirect (load low)
1880 test_load_too_high ()
1882 return GNUNET_SYSERR; // FIXME
1886 /* ******************* Pending Request Refresh Task ******************** */
1891 * We use a random delay to make the timing of requests less
1892 * predictable. This function returns such a random delay. We add a base
1893 * delay of MAX_CORK_DELAY (1s).
1895 * FIXME: make schedule dependent on the specifics of the request?
1896 * Or bandwidth and number of connected peers and load?
1898 * @return random delay to use for some request, between 1s and 1000+TTL_DECREMENT ms
1900 static struct GNUNET_TIME_Relative
1901 get_processing_delay ()
1904 GNUNET_TIME_relative_add (GNUNET_CONSTANTS_MAX_CORK_DELAY,
1905 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1906 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1912 * We're processing a GET request from another peer and have decided
1913 * to forward it to other peers. This function is called periodically
1914 * and should forward the request to other peers until we have all
1915 * possible replies. If we have transmitted the *only* reply to
1916 * the initiator we should destroy the pending request. If we have
1917 * many replies in the queue to the initiator, we should delay sending
1918 * out more queries until the reply queue has shrunk some.
1920 * @param cls our "struct ProcessGetContext *"
1924 forward_request_task (void *cls,
1925 const struct GNUNET_SCHEDULER_TaskContext *tc);
1929 * Function called after we either failed or succeeded
1930 * at transmitting a query to a peer.
1932 * @param cls the requests "struct PendingRequest*"
1933 * @param tpid ID of receiving peer, 0 on transmission error
1936 transmit_query_continuation (void *cls,
1937 GNUNET_PEER_Id tpid)
1939 struct PendingRequest *pr = cls;
1941 GNUNET_STATISTICS_update (stats,
1942 gettext_noop ("# queries scheduled for forwarding"),
1948 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1949 "Transmission of request failed, will try again later.\n");
1951 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1952 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1953 get_processing_delay (),
1954 &forward_request_task,
1958 GNUNET_STATISTICS_update (stats,
1959 gettext_noop ("# queries forwarded"),
1962 GNUNET_PEER_change_rc (tpid, 1);
1963 if (pr->used_pids_off == pr->used_pids_size)
1964 GNUNET_array_grow (pr->used_pids,
1966 pr->used_pids_size * 2 + 2);
1967 pr->used_pids[pr->used_pids_off++] = tpid;
1968 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1969 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1970 get_processing_delay (),
1971 &forward_request_task,
1977 * How many bytes should a bloomfilter be if we have already seen
1978 * entry_count responses? Note that BLOOMFILTER_K gives us the number
1979 * of bits set per entry. Furthermore, we should not re-size the
1980 * filter too often (to keep it cheap).
1982 * Since other peers will also add entries but not resize the filter,
1983 * we should generally pick a slightly larger size than what the
1984 * strict math would suggest.
1986 * @return must be a power of two and smaller or equal to 2^15.
1989 compute_bloomfilter_size (unsigned int entry_count)
1992 unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
1993 uint16_t max = 1 << 15;
1995 if (entry_count > max)
1998 while ((size < max) && (size < ideal))
2007 * Recalculate our bloom filter for filtering replies. This function
2008 * will create a new bloom filter from scratch, so it should only be
2009 * called if we have no bloomfilter at all (and hence can create a
2010 * fresh one of minimal size without problems) OR if our peer is the
2011 * initiator (in which case we may resize to larger than mimimum size).
2013 * @param pr request for which the BF is to be recomputed
2016 refresh_bloomfilter (struct PendingRequest *pr)
2020 GNUNET_HashCode mhash;
2022 nsize = compute_bloomfilter_size (pr->replies_seen_off);
2023 if (nsize == pr->bf_size)
2024 return; /* size not changed */
2026 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
2027 pr->bf_size = nsize;
2028 pr->mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
2029 pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
2032 for (i=0;i<pr->replies_seen_off;i++)
2034 GNUNET_BLOCK_mingle_hash (&pr->replies_seen[i],
2037 GNUNET_CONTAINER_bloomfilter_add (pr->bf, &mhash);
2043 * Function called after we've tried to reserve a certain amount of
2044 * bandwidth for a reply. Check if we succeeded and if so send our
2047 * @param cls the requests "struct PendingRequest*"
2048 * @param peer identifies the peer
2049 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
2050 * @param bpm_out set to the current bandwidth limit (sending) for this peer
2051 * @param amount set to the amount that was actually reserved or unreserved
2052 * @param preference current traffic preference for the given peer
2055 target_reservation_cb (void *cls,
2057 GNUNET_PeerIdentity * peer,
2058 struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
2059 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
2061 uint64_t preference)
2063 struct PendingRequest *pr = cls;
2064 struct ConnectedPeer *cp;
2065 struct PendingMessage *pm;
2066 struct GetMessage *gm;
2067 GNUNET_HashCode *ext;
2077 /* error in communication with core, try again later */
2078 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2079 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
2080 get_processing_delay (),
2081 &forward_request_task,
2085 // (3) transmit, update ttl/priority
2086 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2090 /* Peer must have just left */
2092 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2093 "Selected peer disconnected!\n");
2095 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2096 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
2097 get_processing_delay (),
2098 &forward_request_task,
2102 no_route = GNUNET_NO;
2108 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2109 "Failed to reserve bandwidth for reply (got %d/%u bytes only)!\n",
2113 GNUNET_STATISTICS_update (stats,
2114 gettext_noop ("# reply bandwidth reservation requests failed"),
2117 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2118 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
2119 get_processing_delay (),
2120 &forward_request_task,
2122 return; /* this target round failed */
2124 /* FIXME: if we are "quite" busy, we may still want to skip
2125 this round; need more load detection code! */
2126 no_route = GNUNET_YES;
2129 GNUNET_STATISTICS_update (stats,
2130 gettext_noop ("# queries scheduled for forwarding"),
2133 /* build message and insert message into priority queue */
2135 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2136 "Forwarding request `%s' to `%4s'!\n",
2137 GNUNET_h2s (&pr->query),
2142 if (GNUNET_YES == no_route)
2144 bm |= GET_MESSAGE_BIT_RETURN_TO;
2147 if (pr->namespace != NULL)
2149 bm |= GET_MESSAGE_BIT_SKS_NAMESPACE;
2152 if (pr->target_pid != 0)
2154 bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
2157 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
2158 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
2159 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
2161 gm = (struct GetMessage*) &pm[1];
2162 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
2163 gm->header.size = htons (msize);
2164 gm->type = htonl (pr->type);
2165 pr->remaining_priority /= 2;
2166 gm->priority = htonl (pr->remaining_priority);
2167 gm->ttl = htonl (pr->ttl);
2168 gm->filter_mutator = htonl(pr->mingle);
2169 gm->hash_bitmap = htonl (bm);
2170 gm->query = pr->query;
2171 ext = (GNUNET_HashCode*) &gm[1];
2173 if (GNUNET_YES == no_route)
2174 GNUNET_PEER_resolve (pr->cp->pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
2175 if (pr->namespace != NULL)
2176 memcpy (&ext[k++], pr->namespace, sizeof (GNUNET_HashCode));
2177 if (pr->target_pid != 0)
2178 GNUNET_PEER_resolve (pr->target_pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
2179 bfdata = (char *) &ext[k];
2181 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
2184 pm->cont = &transmit_query_continuation;
2186 add_to_pending_messages_for_peer (cp, pm, pr);
2191 * Closure used for "target_peer_select_cb".
2193 struct PeerSelectionContext
2196 * The request for which we are selecting
2199 struct PendingRequest *pr;
2202 * Current "prime" target.
2204 struct GNUNET_PeerIdentity target;
2207 * How much do we like this target?
2209 double target_score;
2215 * Function called for each connected peer to determine
2216 * which one(s) would make good targets for forwarding.
2218 * @param cls closure (struct PeerSelectionContext)
2219 * @param key current key code (peer identity)
2220 * @param value value in the hash map (struct ConnectedPeer)
2221 * @return GNUNET_YES if we should continue to
2226 target_peer_select_cb (void *cls,
2227 const GNUNET_HashCode * key,
2230 struct PeerSelectionContext *psc = cls;
2231 struct ConnectedPeer *cp = value;
2232 struct PendingRequest *pr = psc->pr;
2237 /* 1) check that this peer is not the initiator */
2241 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2242 "Skipping initiator in forwarding selection\n");
2244 return GNUNET_YES; /* skip */
2247 /* 2) check if we have already (recently) forwarded to this peer */
2249 for (i=0;i<pr->used_pids_off;i++)
2250 if (pr->used_pids[i] == cp->pid)
2253 if (0 != GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2254 RETRY_PROBABILITY_INV))
2257 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2258 "NOT re-trying query that was previously transmitted %u times\n",
2259 (unsigned int) pr->used_pids_off);
2261 return GNUNET_YES; /* skip */
2266 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2267 "Re-trying query that was previously transmitted %u times to this peer\n",
2270 /* 3) calculate how much we'd like to forward to this peer,
2271 starting with a random value that is strong enough
2272 to at least give any peer a chance sometimes
2273 (compared to the other factors that come later) */
2274 /* 3a) count successful (recent) routes from cp for same source */
2277 score = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2278 P2P_SUCCESS_LIST_SIZE);
2279 for (i=0;i<P2P_SUCCESS_LIST_SIZE;i++)
2280 if (cp->last_p2p_replies[i] == pr->cp->pid)
2281 score += 1; /* likely successful based on hot path */
2285 score = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2286 CS2P_SUCCESS_LIST_SIZE);
2287 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
2288 if (cp->last_client_replies[i] == pr->client_request_list->client_list->client)
2289 score += 1; /* likely successful based on hot path */
2291 /* 3b) include latency */
2292 if (cp->avg_delay.value < 4 * TTL_DECREMENT)
2293 score += 1; /* likely fast based on latency */
2294 /* 3c) include priorities */
2295 if (cp->avg_priority <= pr->remaining_priority / 2.0)
2296 score += 1; /* likely successful based on priorities */
2297 /* 3d) penalize for queue size */
2298 score -= (2.0 * cp->pending_requests / (double) MAX_QUEUE_PER_PEER);
2299 /* 3e) include peer proximity */
2300 score -= (2.0 * (GNUNET_CRYPTO_hash_distance_u32 (key,
2301 &pr->query)) / (double) UINT32_MAX);
2302 /* 4) super-bonus for being the known target */
2303 if (pr->target_pid == cp->pid)
2305 /* store best-fit in closure */
2307 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2308 "Peer `%s' gets score %f for forwarding query, max is %f\n",
2313 score++; /* avoid zero */
2314 if (score > psc->target_score)
2316 psc->target_score = score;
2317 psc->target.hashPubKey = *key;
2324 * The priority level imposes a bound on the maximum
2325 * value for the ttl that can be requested.
2327 * @param ttl_in requested ttl
2328 * @param prio given priority
2329 * @return ttl_in if ttl_in is below the limit,
2330 * otherwise the ttl-limit for the given priority
2333 bound_ttl (int32_t ttl_in, uint32_t prio)
2335 unsigned long long allowed;
2339 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
2340 if (ttl_in > allowed)
2342 if (allowed >= (1 << 30))
2351 * Iterator called on each result obtained for a DHT
2352 * operation that expects a reply
2354 * @param cls closure
2355 * @param exp when will this value expire
2356 * @param key key of the result
2357 * @param get_path NULL-terminated array of pointers
2358 * to the peers on reverse GET path (or NULL if not recorded)
2359 * @param put_path NULL-terminated array of pointers
2360 * to the peers on the PUT path (or NULL if not recorded)
2361 * @param type type of the result
2362 * @param size number of bytes in data
2363 * @param data pointer to the result data
2366 process_dht_reply (void *cls,
2367 struct GNUNET_TIME_Absolute exp,
2368 const GNUNET_HashCode * key,
2369 const struct GNUNET_PeerIdentity * const *get_path,
2370 const struct GNUNET_PeerIdentity * const *put_path,
2371 enum GNUNET_BLOCK_Type type,
2377 * We're processing a GET request and have decided
2378 * to forward it to other peers. This function is called periodically
2379 * and should forward the request to other peers until we have all
2380 * possible replies. If we have transmitted the *only* reply to
2381 * the initiator we should destroy the pending request. If we have
2382 * many replies in the queue to the initiator, we should delay sending
2383 * out more queries until the reply queue has shrunk some.
2385 * @param cls our "struct ProcessGetContext *"
2389 forward_request_task (void *cls,
2390 const struct GNUNET_SCHEDULER_TaskContext *tc)
2392 struct PendingRequest *pr = cls;
2393 struct PeerSelectionContext psc;
2394 struct ConnectedPeer *cp;
2395 struct GNUNET_TIME_Relative delay;
2397 pr->task = GNUNET_SCHEDULER_NO_TASK;
2398 if (pr->irc != NULL)
2401 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2402 "Forwarding of query `%s' not attempted due to pending local lookup!\n",
2403 GNUNET_h2s (&pr->query));
2405 return; /* already pending */
2407 if (GNUNET_YES == pr->local_only)
2408 return; /* configured to not do P2P search */
2410 if ( (0 == pr->anonymity_level) &&
2411 (pr->type != GNUNET_BLOCK_TYPE_FS_DBLOCK) &&
2412 (pr->type != GNUNET_BLOCK_TYPE_FS_IBLOCK) )
2414 pr->dht_get = GNUNET_DHT_get_start (dht_handle,
2415 GNUNET_TIME_UNIT_FOREVER_REL,
2422 (pr->namespace != NULL) ? sizeof (GNUNET_HashCode) : 0,
2426 /* (1) select target */
2428 psc.target_score = -DBL_MAX;
2429 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
2430 &target_peer_select_cb,
2432 if (psc.target_score == -DBL_MAX)
2434 delay = get_processing_delay ();
2436 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2437 "No peer selected for forwarding of query `%s', will try again in %llu ms!\n",
2438 GNUNET_h2s (&pr->query),
2441 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
2443 &forward_request_task,
2445 return; /* nobody selected */
2447 /* (3) update TTL/priority */
2448 if (pr->client_request_list != NULL)
2450 /* FIXME: use better algorithm!? */
2451 if (0 == GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2454 /* bound priority we use by priorities we see from other peers
2455 rounded up (must round up so that we can see non-zero
2456 priorities, but round up as little as possible to make it
2457 plausible that we forwarded another peers request) */
2458 if (pr->priority > current_priorities + 1.0)
2459 pr->priority = (uint32_t) current_priorities + 1.0;
2460 pr->ttl = bound_ttl (pr->ttl + TTL_DECREMENT * 2,
2463 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2464 "Trying query `%s' with priority %u and TTL %d.\n",
2465 GNUNET_h2s (&pr->query),
2471 /* (3) reserve reply bandwidth */
2472 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2473 &psc.target.hashPubKey);
2474 GNUNET_assert (NULL != cp);
2475 pr->irc = GNUNET_CORE_peer_change_preference (sched, cfg,
2477 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
2478 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
2481 &target_reservation_cb,
2483 cp->inc_preference = 0;
2487 /* **************************** P2P PUT Handling ************************ */
2491 * Function called after we either failed or succeeded
2492 * at transmitting a reply to a peer.
2494 * @param cls the requests "struct PendingRequest*"
2495 * @param tpid ID of receiving peer, 0 on transmission error
2498 transmit_reply_continuation (void *cls,
2499 GNUNET_PEER_Id tpid)
2501 struct PendingRequest *pr = cls;
2505 case GNUNET_BLOCK_TYPE_FS_DBLOCK:
2506 case GNUNET_BLOCK_TYPE_FS_IBLOCK:
2507 /* only one reply expected, done with the request! */
2508 destroy_pending_request (pr);
2510 case GNUNET_BLOCK_TYPE_ANY:
2511 case GNUNET_BLOCK_TYPE_FS_KBLOCK:
2512 case GNUNET_BLOCK_TYPE_FS_SBLOCK:
2522 * Transmit the given message by copying it to the target buffer
2523 * "buf". "buf" will be NULL and "size" zero if the socket was closed
2524 * for writing in the meantime. In that case, do nothing
2525 * (the disconnect or shutdown handler will take care of the rest).
2526 * If we were able to transmit messages and there are still more
2527 * pending, ask core again for further calls to this function.
2529 * @param cls closure, pointer to the 'struct ClientList*'
2530 * @param size number of bytes available in buf
2531 * @param buf where the callee should write the message
2532 * @return number of bytes written to buf
2535 transmit_to_client (void *cls,
2536 size_t size, void *buf)
2538 struct ClientList *cl = cls;
2540 struct ClientResponseMessage *creply;
2547 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2548 "Not sending reply, client communication problem.\n");
2553 while ( (NULL != (creply = cl->res_head) ) &&
2554 (creply->msize <= size) )
2556 memcpy (&cbuf[msize], &creply[1], creply->msize);
2557 msize += creply->msize;
2558 size -= creply->msize;
2559 GNUNET_CONTAINER_DLL_remove (cl->res_head,
2562 GNUNET_free (creply);
2565 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
2567 GNUNET_TIME_UNIT_FOREVER_REL,
2568 &transmit_to_client,
2571 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2572 "Transmitted %u bytes to client\n",
2573 (unsigned int) msize);
2580 * Closure for "process_reply" function.
2582 struct ProcessReplyClosure
2585 * The data for the reply.
2590 * Who gave us this reply? NULL for local host (or DHT)
2592 struct ConnectedPeer *sender;
2595 * When the reply expires.
2597 struct GNUNET_TIME_Absolute expiration;
2605 * Type of the block.
2607 enum GNUNET_BLOCK_Type type;
2610 * How much was this reply worth to us?
2615 * Evaluation result (returned).
2617 enum GNUNET_BLOCK_EvaluationResult eval;
2620 * Did we finish processing the associated request?
2625 * Did we find a matching request?
2632 * We have received a reply; handle it!
2634 * @param cls response (struct ProcessReplyClosure)
2635 * @param key our query
2636 * @param value value in the hash map (info about the query)
2637 * @return GNUNET_YES (we should continue to iterate)
2640 process_reply (void *cls,
2641 const GNUNET_HashCode * key,
2644 struct ProcessReplyClosure *prq = cls;
2645 struct PendingRequest *pr = value;
2646 struct PendingMessage *reply;
2647 struct ClientResponseMessage *creply;
2648 struct ClientList *cl;
2649 struct PutMessage *pm;
2650 struct ConnectedPeer *cp;
2651 struct GNUNET_TIME_Relative cur_delay;
2655 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2656 "Matched result (type %u) for query `%s' with pending request\n",
2657 (unsigned int) prq->type,
2660 GNUNET_STATISTICS_update (stats,
2661 gettext_noop ("# replies received and matched"),
2664 if (prq->sender != NULL)
2666 /* FIXME: should we be more precise here and not use
2667 "start_time" but a peer-specific time stamp? */
2668 cur_delay = GNUNET_TIME_absolute_get_duration (pr->start_time);
2669 prq->sender->avg_delay.value
2670 = (prq->sender->avg_delay.value *
2671 (RUNAVG_DELAY_N - 1) + cur_delay.value) / RUNAVG_DELAY_N;
2672 prq->sender->avg_priority
2673 = (prq->sender->avg_priority *
2674 (RUNAVG_DELAY_N - 1) + pr->priority) / (double) RUNAVG_DELAY_N;
2677 GNUNET_PEER_change_rc (prq->sender->last_p2p_replies
2678 [prq->sender->last_p2p_replies_woff % P2P_SUCCESS_LIST_SIZE],
2680 GNUNET_PEER_change_rc (pr->cp->pid, 1);
2681 prq->sender->last_p2p_replies
2682 [(prq->sender->last_p2p_replies_woff++) % P2P_SUCCESS_LIST_SIZE]
2687 if (NULL != prq->sender->last_client_replies
2688 [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE])
2689 GNUNET_SERVER_client_drop (prq->sender->last_client_replies
2690 [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE]);
2691 prq->sender->last_client_replies
2692 [(prq->sender->last_client_replies_woff++) % CS2P_SUCCESS_LIST_SIZE]
2693 = pr->client_request_list->client_list->client;
2694 GNUNET_SERVER_client_keep (pr->client_request_list->client_list->client);
2697 prq->eval = GNUNET_BLOCK_evaluate (block_ctx,
2702 pr->namespace, (pr->namespace != NULL) ? sizeof (GNUNET_HashCode) : 0,
2707 case GNUNET_BLOCK_EVALUATION_OK_MORE:
2709 case GNUNET_BLOCK_EVALUATION_OK_LAST:
2710 while (NULL != pr->pending_head)
2711 destroy_pending_message_list_entry (pr->pending_head);
2714 if (pr->client_request_list != NULL)
2715 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
2717 GNUNET_DATASTORE_cancel (pr->qe);
2720 pr->do_remove = GNUNET_YES;
2721 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
2723 GNUNET_SCHEDULER_cancel (sched,
2725 pr->task = GNUNET_SCHEDULER_NO_TASK;
2727 GNUNET_break (GNUNET_YES ==
2728 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
2732 case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
2733 GNUNET_STATISTICS_update (stats,
2734 gettext_noop ("# duplicate replies discarded (bloomfilter)"),
2738 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2739 "Duplicate response `%s', discarding.\n",
2740 GNUNET_h2s (&mhash));
2742 return GNUNET_YES; /* duplicate */
2743 case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
2744 return GNUNET_YES; /* wrong namespace */
2745 case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
2748 case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
2751 case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
2752 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2753 _("Unsupported block type %u\n"),
2757 if (pr->client_request_list != NULL)
2759 if (pr->replies_seen_size == pr->replies_seen_off)
2760 GNUNET_array_grow (pr->replies_seen,
2761 pr->replies_seen_size,
2762 pr->replies_seen_size * 2 + 4);
2763 GNUNET_CRYPTO_hash (prq->data,
2765 &pr->replies_seen[pr->replies_seen_off++]);
2766 refresh_bloomfilter (pr);
2768 if (NULL == prq->sender)
2771 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2772 "Found result for query `%s' in local datastore\n",
2775 GNUNET_STATISTICS_update (stats,
2776 gettext_noop ("# results found locally"),
2780 prq->priority += pr->remaining_priority;
2781 pr->remaining_priority = 0;
2782 pr->results_found++;
2783 prq->request_found = GNUNET_YES;
2784 if (NULL != pr->client_request_list)
2786 GNUNET_STATISTICS_update (stats,
2787 gettext_noop ("# replies received for local clients"),
2790 cl = pr->client_request_list->client_list;
2791 msize = sizeof (struct PutMessage) + prq->size;
2792 creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
2793 creply->msize = msize;
2794 creply->client_list = cl;
2795 GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
2799 pm = (struct PutMessage*) &creply[1];
2800 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2801 pm->header.size = htons (msize);
2802 pm->type = htonl (prq->type);
2803 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
2804 memcpy (&pm[1], prq->data, prq->size);
2808 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2809 "Transmitting result for query `%s' to client\n",
2812 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
2814 GNUNET_TIME_UNIT_FOREVER_REL,
2815 &transmit_to_client,
2818 GNUNET_break (cl->th != NULL);
2821 prq->finished = GNUNET_YES;
2822 destroy_pending_request (pr);
2829 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2830 "Transmitting result for query `%s' to other peer (PID=%u)\n",
2832 (unsigned int) cp->pid);
2834 GNUNET_STATISTICS_update (stats,
2835 gettext_noop ("# replies received for other peers"),
2838 msize = sizeof (struct PutMessage) + prq->size;
2839 reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
2840 reply->cont = &transmit_reply_continuation;
2841 reply->cont_cls = pr;
2842 reply->msize = msize;
2843 reply->priority = UINT32_MAX; /* send replies first! */
2844 pm = (struct PutMessage*) &reply[1];
2845 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2846 pm->header.size = htons (msize);
2847 pm->type = htonl (prq->type);
2848 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
2849 memcpy (&pm[1], prq->data, prq->size);
2850 add_to_pending_messages_for_peer (cp, reply, pr);
2857 * Iterator called on each result obtained for a DHT
2858 * operation that expects a reply
2860 * @param cls closure
2861 * @param exp when will this value expire
2862 * @param key key of the result
2863 * @param get_path NULL-terminated array of pointers
2864 * to the peers on reverse GET path (or NULL if not recorded)
2865 * @param put_path NULL-terminated array of pointers
2866 * to the peers on the PUT path (or NULL if not recorded)
2867 * @param type type of the result
2868 * @param size number of bytes in data
2869 * @param data pointer to the result data
2872 process_dht_reply (void *cls,
2873 struct GNUNET_TIME_Absolute exp,
2874 const GNUNET_HashCode * key,
2875 const struct GNUNET_PeerIdentity * const *get_path,
2876 const struct GNUNET_PeerIdentity * const *put_path,
2877 enum GNUNET_BLOCK_Type type,
2881 struct PendingRequest *pr = cls;
2882 struct ProcessReplyClosure prq;
2884 memset (&prq, 0, sizeof (prq));
2886 prq.expiration = exp;
2889 process_reply (&prq, key, pr);
2895 * Continuation called to notify client about result of the
2898 * @param cls closure
2899 * @param success GNUNET_SYSERR on failure
2900 * @param msg NULL on success, otherwise an error message
2903 put_migration_continuation (void *cls,
2907 struct GNUNET_TIME_Absolute *start = cls;
2908 struct GNUNET_TIME_Relative delay;
2910 delay = GNUNET_TIME_absolute_get_duration (*start);
2911 GNUNET_free (start);
2912 GNUNET_LOAD_update (datastore_put_load,
2914 if (GNUNET_OK == success)
2916 GNUNET_STATISTICS_update (stats,
2917 gettext_noop ("# datastore 'put' failures"),
2924 * Handle P2P "PUT" message.
2926 * @param cls closure, always NULL
2927 * @param other the other peer involved (sender or receiver, NULL
2928 * for loopback messages where we are both sender and receiver)
2929 * @param message the actual message
2930 * @param latency reported latency of the connection with 'other'
2931 * @param distance reported distance (DV) to 'other'
2932 * @return GNUNET_OK to keep the connection open,
2933 * GNUNET_SYSERR to close it (signal serious error)
2936 handle_p2p_put (void *cls,
2937 const struct GNUNET_PeerIdentity *other,
2938 const struct GNUNET_MessageHeader *message,
2939 struct GNUNET_TIME_Relative latency,
2942 const struct PutMessage *put;
2945 enum GNUNET_BLOCK_Type type;
2946 struct GNUNET_TIME_Absolute expiration;
2947 GNUNET_HashCode query;
2948 struct ProcessReplyClosure prq;
2949 struct GNUNET_TIME_Absolute *start;
2950 struct GNUNET_TIME_Relative block_time;
2952 struct ConnectedPeer *cp;
2953 struct PendingMessage *pm;
2954 struct MigrationStopMessage *msm;
2956 msize = ntohs (message->size);
2957 if (msize < sizeof (struct PutMessage))
2960 return GNUNET_SYSERR;
2962 put = (const struct PutMessage*) message;
2963 dsize = msize - sizeof (struct PutMessage);
2964 type = ntohl (put->type);
2965 expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
2967 if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
2968 return GNUNET_SYSERR;
2970 GNUNET_BLOCK_get_key (block_ctx,
2976 GNUNET_break_op (0);
2977 return GNUNET_SYSERR;
2980 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2981 "Received result for query `%s' from peer `%4s'\n",
2982 GNUNET_h2s (&query),
2983 GNUNET_i2s (other));
2985 GNUNET_STATISTICS_update (stats,
2986 gettext_noop ("# replies received (overall)"),
2989 /* now, lookup 'query' */
2990 prq.data = (const void*) &put[1];
2992 prq.sender = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2993 &other->hashPubKey);
2998 prq.expiration = expiration;
3000 prq.finished = GNUNET_NO;
3001 prq.request_found = GNUNET_NO;
3002 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
3006 if (prq.sender != NULL)
3008 prq.sender->inc_preference += CONTENT_BANDWIDTH_VALUE + 1000 * prq.priority;
3009 prq.sender->trust += prq.priority;
3011 if (GNUNET_YES == active_migration)
3014 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3015 "Replicating result for query `%s' with priority %u\n",
3016 GNUNET_h2s (&query),
3019 start = GNUNET_malloc (sizeof (struct GNUNET_TIME_Absolute));
3020 *start = GNUNET_TIME_absolute_get ();
3021 GNUNET_DATASTORE_put (dsh,
3022 0, &query, dsize, &put[1],
3023 type, prq.priority, 1 /* anonymity */,
3025 1 + prq.priority, MAX_DATASTORE_QUEUE,
3026 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
3027 &put_migration_continuation,
3030 putl = GNUNET_LOAD_get_load (datastore_put_load);
3031 if ( (GNUNET_NO == prq.request_found) &&
3032 ( (GNUNET_YES != active_migration) ||
3035 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3036 &other->hashPubKey);
3037 if (GNUNET_TIME_absolute_get_duration (cp->last_migration_block).value < 5000)
3038 return GNUNET_OK; /* already blocked */
3039 /* We're too busy; send MigrationStop message! */
3040 if (GNUNET_YES != active_migration)
3041 putl = 1.0 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 5);
3042 block_time = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
3043 5000 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3044 (unsigned int) (60000 * putl * putl)));
3046 cp->last_migration_block = GNUNET_TIME_relative_to_absolute (block_time);
3047 pm = GNUNET_malloc (sizeof (struct PendingMessage) +
3048 sizeof (struct MigrationStopMessage));
3049 pm->msize = sizeof (struct MigrationStopMessage);
3050 pm->priority = UINT32_MAX;
3051 msm = (struct MigrationStopMessage*) &pm[1];
3052 msm->header.size = htons (sizeof (struct MigrationStopMessage));
3053 msm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP);
3054 msm->duration = GNUNET_TIME_relative_hton (block_time);
3055 add_to_pending_messages_for_peer (cp,
3064 * Handle P2P "MIGRATION_STOP" message.
3066 * @param cls closure, always NULL
3067 * @param other the other peer involved (sender or receiver, NULL
3068 * for loopback messages where we are both sender and receiver)
3069 * @param message the actual message
3070 * @param latency reported latency of the connection with 'other'
3071 * @param distance reported distance (DV) to 'other'
3072 * @return GNUNET_OK to keep the connection open,
3073 * GNUNET_SYSERR to close it (signal serious error)
3076 handle_p2p_migration_stop (void *cls,
3077 const struct GNUNET_PeerIdentity *other,
3078 const struct GNUNET_MessageHeader *message,
3079 struct GNUNET_TIME_Relative latency,
3082 struct ConnectedPeer *cp;
3083 const struct MigrationStopMessage *msm;
3085 msm = (const struct MigrationStopMessage*) message;
3086 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3087 &other->hashPubKey);
3093 cp->migration_blocked = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (msm->duration));
3099 /* **************************** P2P GET Handling ************************ */
3103 * Closure for 'check_duplicate_request_{peer,client}'.
3105 struct CheckDuplicateRequestClosure
3108 * The new request we should check if it already exists.
3110 const struct PendingRequest *pr;
3113 * Existing request found by the checker, NULL if none.
3115 struct PendingRequest *have;
3120 * Iterator over entries in the 'query_request_map' that
3121 * tries to see if we have the same request pending from
3122 * the same client already.
3124 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
3125 * @param key current key code (query, ignored, must match)
3126 * @param value value in the hash map (a 'struct PendingRequest'
3127 * that already exists)
3128 * @return GNUNET_YES if we should continue to
3129 * iterate (no match yet)
3130 * GNUNET_NO if not (match found).
3133 check_duplicate_request_client (void *cls,
3134 const GNUNET_HashCode * key,
3137 struct CheckDuplicateRequestClosure *cdc = cls;
3138 struct PendingRequest *have = value;
3140 if (have->client_request_list == NULL)
3142 if ( (cdc->pr->client_request_list->client_list->client == have->client_request_list->client_list->client) &&
3153 * We're processing (local) results for a search request
3154 * from another peer. Pass applicable results to the
3155 * peer and if we are done either clean up (operation
3156 * complete) or forward to other peers (more results possible).
3158 * @param cls our closure (struct LocalGetContext)
3159 * @param key key for the content
3160 * @param size number of bytes in data
3161 * @param data content stored
3162 * @param type type of the content
3163 * @param priority priority of the content
3164 * @param anonymity anonymity-level for the content
3165 * @param expiration expiration time for the content
3166 * @param uid unique identifier for the datum;
3167 * maybe 0 if no unique identifier is available
3170 process_local_reply (void *cls,
3171 const GNUNET_HashCode * key,
3174 enum GNUNET_BLOCK_Type type,
3177 struct GNUNET_TIME_Absolute
3181 struct PendingRequest *pr = cls;
3182 struct ProcessReplyClosure prq;
3183 struct CheckDuplicateRequestClosure cdrc;
3184 GNUNET_HashCode query;
3185 unsigned int old_rf;
3190 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3191 "Done processing local replies, forwarding request to other peers.\n");
3194 if (pr->client_request_list != NULL)
3196 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
3198 /* Figure out if this is a duplicate request and possibly
3199 merge 'struct PendingRequest' entries */
3202 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
3204 &check_duplicate_request_client,
3206 if (cdrc.have != NULL)
3209 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3210 "Received request for block `%s' twice from client, will only request once.\n",
3211 GNUNET_h2s (&pr->query));
3214 destroy_pending_request (pr);
3219 /* no more results */
3220 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
3221 pr->task = GNUNET_SCHEDULER_add_now (sched,
3222 &forward_request_task,
3227 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3228 "New local response to `%s' of type %u.\n",
3232 if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
3235 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3236 "Found ONDEMAND block, performing on-demand encoding\n");
3238 GNUNET_STATISTICS_update (stats,
3239 gettext_noop ("# on-demand blocks matched requests"),
3243 GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
3244 anonymity, expiration, uid,
3245 &process_local_reply,
3249 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3253 old_rf = pr->results_found;
3254 memset (&prq, 0, sizeof (prq));
3256 prq.expiration = expiration;
3259 GNUNET_BLOCK_get_key (block_ctx,
3266 GNUNET_DATASTORE_remove (dsh,
3270 GNUNET_TIME_UNIT_FOREVER_REL,
3272 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3276 prq.priority = priority;
3277 prq.finished = GNUNET_NO;
3278 prq.request_found = GNUNET_NO;
3279 process_reply (&prq, key, pr);
3280 if ( (old_rf == 0) &&
3281 (pr->results_found == 1) )
3282 update_datastore_delays (pr->start_time);
3283 if (prq.finished == GNUNET_YES)
3286 return; /* done here */
3287 if (prq.eval == GNUNET_BLOCK_EVALUATION_OK_LAST)
3289 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
3292 if ( (pr->client_request_list == NULL) &&
3293 ( (GNUNET_YES == test_load_too_high()) ||
3294 (pr->results_found > 5 + 2 * pr->priority) ) )
3297 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3298 "Load too high, done with request\n");
3300 GNUNET_STATISTICS_update (stats,
3301 gettext_noop ("# processing result set cut short due to load"),
3304 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
3307 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3312 * We've received a request with the specified priority. Bound it
3313 * according to how much we trust the given peer.
3315 * @param prio_in requested priority
3316 * @param cp the peer making the request
3317 * @return effective priority
3320 bound_priority (uint32_t prio_in,
3321 struct ConnectedPeer *cp)
3323 #define N ((double)128.0)
3328 ld = test_load_too_high ();
3329 if (ld == GNUNET_SYSERR)
3330 return 0; /* excess resources */
3331 ret = change_host_trust (cp, prio_in);
3334 if (ret > current_priorities + N)
3335 rret = current_priorities + N;
3339 = (current_priorities * (N-1) + rret)/N;
3347 * Iterator over entries in the 'query_request_map' that
3348 * tries to see if we have the same request pending from
3349 * the same peer already.
3351 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
3352 * @param key current key code (query, ignored, must match)
3353 * @param value value in the hash map (a 'struct PendingRequest'
3354 * that already exists)
3355 * @return GNUNET_YES if we should continue to
3356 * iterate (no match yet)
3357 * GNUNET_NO if not (match found).
3360 check_duplicate_request_peer (void *cls,
3361 const GNUNET_HashCode * key,
3364 struct CheckDuplicateRequestClosure *cdc = cls;
3365 struct PendingRequest *have = value;
3367 if (cdc->pr->target_pid == have->target_pid)
3377 * Handle P2P "GET" request.
3379 * @param cls closure, always NULL
3380 * @param other the other peer involved (sender or receiver, NULL
3381 * for loopback messages where we are both sender and receiver)
3382 * @param message the actual message
3383 * @param latency reported latency of the connection with 'other'
3384 * @param distance reported distance (DV) to 'other'
3385 * @return GNUNET_OK to keep the connection open,
3386 * GNUNET_SYSERR to close it (signal serious error)
3389 handle_p2p_get (void *cls,
3390 const struct GNUNET_PeerIdentity *other,
3391 const struct GNUNET_MessageHeader *message,
3392 struct GNUNET_TIME_Relative latency,
3395 struct PendingRequest *pr;
3396 struct ConnectedPeer *cp;
3397 struct ConnectedPeer *cps;
3398 struct CheckDuplicateRequestClosure cdc;
3399 struct GNUNET_TIME_Relative timeout;
3401 const struct GetMessage *gm;
3403 const GNUNET_HashCode *opt;
3406 uint32_t ttl_decrement;
3407 enum GNUNET_BLOCK_Type type;
3411 msize = ntohs(message->size);
3412 if (msize < sizeof (struct GetMessage))
3414 GNUNET_break_op (0);
3415 return GNUNET_SYSERR;
3417 gm = (const struct GetMessage*) message;
3418 type = ntohl (gm->type);
3419 bm = ntohl (gm->hash_bitmap);
3427 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
3429 GNUNET_break_op (0);
3430 return GNUNET_SYSERR;
3432 opt = (const GNUNET_HashCode*) &gm[1];
3433 bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
3434 bm = ntohl (gm->hash_bitmap);
3436 cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3437 &other->hashPubKey);
3440 /* peer must have just disconnected */
3441 GNUNET_STATISTICS_update (stats,
3442 gettext_noop ("# requests dropped due to initiator not being connected"),
3445 return GNUNET_SYSERR;
3447 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
3448 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3455 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
3456 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3457 "Failed to find RETURN-TO peer `%4s' in connection set. Dropping query.\n",
3458 GNUNET_i2s ((const struct GNUNET_PeerIdentity*) &opt[bits-1]));
3461 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3462 "Failed to find peer `%4s' in connection set. Dropping query.\n",
3463 GNUNET_i2s (other));
3465 GNUNET_STATISTICS_update (stats,
3466 gettext_noop ("# requests dropped due to missing reverse route"),
3469 /* FIXME: try connect? */
3472 /* note that we can really only check load here since otherwise
3473 peers could find out that we are overloaded by not being
3474 disconnected after sending us a malformed query... */
3476 /* FIXME: query priority should play
3477 a major role here! */
3478 ld = test_load_too_high ();
3479 if (GNUNET_YES == ld)
3482 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3483 "Dropping query from `%s', this peer is too busy.\n",
3484 GNUNET_i2s (other));
3486 GNUNET_STATISTICS_update (stats,
3487 gettext_noop ("# requests dropped due to high load"),
3492 /* FIXME: if ld == GNUNET_NO, forward
3493 instead of indirecting! */
3496 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3497 "Received request for `%s' of type %u from peer `%4s' with flags %u\n",
3498 GNUNET_h2s (&gm->query),
3499 (unsigned int) type,
3503 have_ns = (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE));
3504 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
3505 (have_ns ? sizeof(GNUNET_HashCode) : 0));
3508 pr->namespace = (GNUNET_HashCode*) &pr[1];
3509 memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
3512 pr->mingle = ntohl (gm->filter_mutator);
3513 if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
3514 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
3515 pr->anonymity_level = 1;
3516 pr->priority = bound_priority (ntohl (gm->priority), cps);
3517 pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
3518 pr->query = gm->query;
3519 /* decrement ttl (always) */
3520 ttl_decrement = 2 * TTL_DECREMENT +
3521 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3523 if ( (pr->ttl < 0) &&
3524 (((int32_t)(pr->ttl - ttl_decrement)) > 0) )
3527 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3528 "Dropping query from `%s' due to TTL underflow (%d - %u).\n",
3533 GNUNET_STATISTICS_update (stats,
3534 gettext_noop ("# requests dropped due TTL underflow"),
3537 /* integer underflow => drop (should be very rare)! */
3541 pr->ttl -= ttl_decrement;
3542 pr->start_time = GNUNET_TIME_absolute_get ();
3544 /* get bloom filter */
3547 pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
3550 pr->bf_size = bfsize;
3555 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
3557 &check_duplicate_request_peer,
3559 if (cdc.have != NULL)
3561 if (cdc.have->start_time.value + cdc.have->ttl >=
3562 pr->start_time.value + pr->ttl)
3564 /* existing request has higher TTL, drop new one! */
3565 cdc.have->priority += pr->priority;
3566 destroy_pending_request (pr);
3568 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3569 "Have existing request with higher TTL, dropping new request.\n",
3570 GNUNET_i2s (other));
3572 GNUNET_STATISTICS_update (stats,
3573 gettext_noop ("# requests dropped due to higher-TTL request"),
3580 /* existing request has lower TTL, drop old one! */
3581 pr->priority += cdc.have->priority;
3582 /* Possible optimization: if we have applicable pending
3583 replies in 'cdc.have', we might want to move those over
3584 (this is a really rare special-case, so it is not clear
3585 that this would be worth it) */
3586 destroy_pending_request (cdc.have);
3587 /* keep processing 'pr'! */
3592 GNUNET_break (GNUNET_OK ==
3593 GNUNET_CONTAINER_multihashmap_put (query_request_map,
3596 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
3597 GNUNET_break (GNUNET_OK ==
3598 GNUNET_CONTAINER_multihashmap_put (peer_request_map,
3601 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
3603 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
3605 pr->start_time.value + pr->ttl);
3607 GNUNET_STATISTICS_update (stats,
3608 gettext_noop ("# P2P searches received"),
3611 GNUNET_STATISTICS_update (stats,
3612 gettext_noop ("# P2P searches active"),
3616 /* calculate change in traffic preference */
3617 cps->inc_preference += pr->priority * 1000 + QUERY_BANDWIDTH_VALUE;
3618 /* process locally */
3619 if (type == GNUNET_BLOCK_TYPE_FS_DBLOCK)
3620 type = GNUNET_BLOCK_TYPE_ANY; /* to get on-demand as well */
3621 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
3622 (pr->priority + 1));
3623 pr->qe = GNUNET_DATASTORE_get (dsh,
3627 MAX_DATASTORE_QUEUE,
3629 &process_local_reply,
3632 /* Are multiple results possible? If so, start processing remotely now! */
3635 case GNUNET_BLOCK_TYPE_FS_DBLOCK:
3636 case GNUNET_BLOCK_TYPE_FS_IBLOCK:
3637 /* only one result, wait for datastore */
3640 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
3641 pr->task = GNUNET_SCHEDULER_add_now (sched,
3642 &forward_request_task,
3646 /* make sure we don't track too many requests */
3647 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
3649 pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
3650 GNUNET_assert (pr != NULL);
3651 destroy_pending_request (pr);
3657 /* **************************** CS GET Handling ************************ */
3661 * Handle START_SEARCH-message (search request from client).
3663 * @param cls closure
3664 * @param client identification of the client
3665 * @param message the actual message
3668 handle_start_search (void *cls,
3669 struct GNUNET_SERVER_Client *client,
3670 const struct GNUNET_MessageHeader *message)
3672 static GNUNET_HashCode all_zeros;
3673 const struct SearchMessage *sm;
3674 struct ClientList *cl;
3675 struct ClientRequestList *crl;
3676 struct PendingRequest *pr;
3679 enum GNUNET_BLOCK_Type type;
3681 msize = ntohs (message->size);
3682 if ( (msize < sizeof (struct SearchMessage)) ||
3683 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
3686 GNUNET_SERVER_receive_done (client,
3690 GNUNET_STATISTICS_update (stats,
3691 gettext_noop ("# client searches received"),
3694 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
3695 sm = (const struct SearchMessage*) message;
3696 type = ntohl (sm->type);
3698 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3699 "Received request for `%s' of type %u from local client\n",
3700 GNUNET_h2s (&sm->query),
3701 (unsigned int) type);
3704 while ( (cl != NULL) &&
3705 (cl->client != client) )
3709 cl = GNUNET_malloc (sizeof (struct ClientList));
3710 cl->client = client;
3711 GNUNET_SERVER_client_keep (client);
3712 cl->next = client_list;
3715 /* detect duplicate KBLOCK requests */
3716 if ( (type == GNUNET_BLOCK_TYPE_FS_KBLOCK) ||
3717 (type == GNUNET_BLOCK_TYPE_FS_NBLOCK) ||
3718 (type == GNUNET_BLOCK_TYPE_ANY) )
3721 while ( (crl != NULL) &&
3722 ( (0 != memcmp (&crl->req->query,
3724 sizeof (GNUNET_HashCode))) ||
3725 (crl->req->type != type) ) )
3730 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3731 "Have existing request, merging content-seen lists.\n");
3734 /* Duplicate request (used to send long list of
3735 known/blocked results); merge 'pr->replies_seen'
3736 and update bloom filter */
3737 GNUNET_array_grow (pr->replies_seen,
3738 pr->replies_seen_size,
3739 pr->replies_seen_off + sc);
3740 memcpy (&pr->replies_seen[pr->replies_seen_off],
3742 sc * sizeof (GNUNET_HashCode));
3743 pr->replies_seen_off += sc;
3744 refresh_bloomfilter (pr);
3745 GNUNET_STATISTICS_update (stats,
3746 gettext_noop ("# client searches updated (merged content seen list)"),
3749 GNUNET_SERVER_receive_done (client,
3754 GNUNET_STATISTICS_update (stats,
3755 gettext_noop ("# client searches active"),
3758 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
3759 ((type == GNUNET_BLOCK_TYPE_FS_SBLOCK) ? sizeof(GNUNET_HashCode) : 0));
3760 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
3761 memset (crl, 0, sizeof (struct ClientRequestList));
3762 crl->client_list = cl;
3763 GNUNET_CONTAINER_DLL_insert (cl->rl_head,
3768 pr->client_request_list = crl;
3769 GNUNET_array_grow (pr->replies_seen,
3770 pr->replies_seen_size,
3772 memcpy (pr->replies_seen,
3774 sc * sizeof (GNUNET_HashCode));
3775 pr->replies_seen_off = sc;
3776 pr->anonymity_level = ntohl (sm->anonymity_level);
3777 pr->start_time = GNUNET_TIME_absolute_get ();
3778 refresh_bloomfilter (pr);
3779 pr->query = sm->query;
3780 if (0 == (1 & ntohl (sm->options)))
3781 pr->local_only = GNUNET_NO;
3783 pr->local_only = GNUNET_YES;
3786 case GNUNET_BLOCK_TYPE_FS_DBLOCK:
3787 case GNUNET_BLOCK_TYPE_FS_IBLOCK:
3788 if (0 != memcmp (&sm->target,
3790 sizeof (GNUNET_HashCode)))
3791 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
3793 case GNUNET_BLOCK_TYPE_FS_SBLOCK:
3794 pr->namespace = (GNUNET_HashCode*) &pr[1];
3795 memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
3800 GNUNET_break (GNUNET_OK ==
3801 GNUNET_CONTAINER_multihashmap_put (query_request_map,
3804 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
3805 if (type == GNUNET_BLOCK_TYPE_FS_DBLOCK)
3806 type = GNUNET_BLOCK_TYPE_ANY; /* get on-demand blocks too! */
3807 pr->qe = GNUNET_DATASTORE_get (dsh,
3811 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
3812 &process_local_reply,
3817 /* **************************** Startup ************************ */
3820 * Process fs requests.
3822 * @param s scheduler to use
3823 * @param server the initialized server
3824 * @param c configuration to use
3827 main_init (struct GNUNET_SCHEDULER_Handle *s,
3828 struct GNUNET_SERVER_Handle *server,
3829 const struct GNUNET_CONFIGURATION_Handle *c)
3831 static const struct GNUNET_CORE_MessageHandler p2p_handlers[] =
3834 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
3836 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
3837 { &handle_p2p_migration_stop,
3838 GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP,
3839 sizeof (struct MigrationStopMessage) },
3842 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
3843 {&GNUNET_FS_handle_index_start, NULL,
3844 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
3845 {&GNUNET_FS_handle_index_list_get, NULL,
3846 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
3847 {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
3848 sizeof (struct UnindexMessage) },
3849 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
3853 unsigned long long enc = 128;
3857 stats = GNUNET_STATISTICS_create (sched, "fs", cfg);
3858 min_migration_delay = GNUNET_TIME_UNIT_SECONDS;
3860 GNUNET_CONFIGURATION_get_value_number (cfg,
3862 "MAX_PENDING_REQUESTS",
3863 &max_pending_requests)) ||
3865 GNUNET_CONFIGURATION_get_value_number (cfg,
3867 "EXPECTED_NEIGHBOUR_COUNT",
3870 GNUNET_CONFIGURATION_get_value_time (cfg,
3872 "MIN_MIGRATION_DELAY",
3873 &min_migration_delay)) )
3875 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3876 _("Configuration fails to specify certain parameters, assuming default values."));
3878 connected_peers = GNUNET_CONTAINER_multihashmap_create (enc);
3879 query_request_map = GNUNET_CONTAINER_multihashmap_create (max_pending_requests);
3880 peer_request_map = GNUNET_CONTAINER_multihashmap_create (enc);
3881 requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
3882 core = GNUNET_CORE_connect (sched,
3884 GNUNET_TIME_UNIT_FOREVER_REL,
3887 &peer_connect_handler,
3888 &peer_disconnect_handler,
3895 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3896 _("Failed to connect to `%s' service.\n"),
3898 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
3899 connected_peers = NULL;
3900 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
3901 query_request_map = NULL;
3902 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
3903 requests_by_expiration_heap = NULL;
3904 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
3905 peer_request_map = NULL;
3908 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
3911 return GNUNET_SYSERR;
3913 /* FIXME: distinguish between sending and storing in options? */
3914 if (active_migration)
3916 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3917 _("Content migration is enabled, will start to gather data\n"));
3918 consider_migration_gathering ();
3920 GNUNET_SERVER_disconnect_notify (server,
3921 &handle_client_disconnect,
3923 GNUNET_assert (GNUNET_OK ==
3924 GNUNET_CONFIGURATION_get_value_filename (cfg,
3928 GNUNET_DISK_directory_create (trustDirectory);
3929 GNUNET_SCHEDULER_add_with_priority (sched,
3930 GNUNET_SCHEDULER_PRIORITY_HIGH,
3931 &cron_flush_trust, NULL);
3934 GNUNET_SERVER_add_handlers (server, handlers);
3935 GNUNET_SCHEDULER_add_delayed (sched,
3936 GNUNET_TIME_UNIT_FOREVER_REL,
3944 * Process fs requests.
3946 * @param cls closure
3947 * @param sched scheduler to use
3948 * @param server the initialized server
3949 * @param cfg configuration to use
3953 struct GNUNET_SCHEDULER_Handle *sched,
3954 struct GNUNET_SERVER_Handle *server,
3955 const struct GNUNET_CONFIGURATION_Handle *cfg)
3957 active_migration = GNUNET_CONFIGURATION_get_value_yesno (cfg,
3960 dsh = GNUNET_DATASTORE_connect (cfg,
3964 GNUNET_SCHEDULER_shutdown (sched);
3967 datastore_get_load = GNUNET_LOAD_value_init ();
3968 datastore_put_load = GNUNET_LOAD_value_init ();
3969 block_cfg = GNUNET_CONFIGURATION_create ();
3970 GNUNET_CONFIGURATION_set_value_string (block_cfg,
3974 block_ctx = GNUNET_BLOCK_context_create (block_cfg);
3975 GNUNET_assert (NULL != block_ctx);
3976 dht_handle = GNUNET_DHT_connect (sched,
3979 if ( (GNUNET_OK != GNUNET_FS_indexing_init (sched, cfg, dsh)) ||
3980 (GNUNET_OK != main_init (sched, server, cfg)) )
3982 GNUNET_SCHEDULER_shutdown (sched);
3983 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
3985 GNUNET_DHT_disconnect (dht_handle);
3987 GNUNET_BLOCK_context_destroy (block_ctx);
3989 GNUNET_CONFIGURATION_destroy (block_cfg);
3991 GNUNET_LOAD_value_free (datastore_get_load);
3992 datastore_get_load = NULL;
3993 GNUNET_LOAD_value_free (datastore_put_load);
3994 datastore_put_load = NULL;
4001 * The main function for the fs service.
4003 * @param argc number of arguments from the command line
4004 * @param argv command line arguments
4005 * @return 0 ok, 1 on error
4008 main (int argc, char *const *argv)
4010 return (GNUNET_OK ==
4011 GNUNET_SERVICE_run (argc,
4014 GNUNET_SERVICE_OPTION_NONE,
4015 &run, NULL)) ? 0 : 1;
4018 /* end of gnunet-service-fs.c */