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 * - implement test_load_too_high, make decision priority-based, implement forwarding, etc.
28 * - consider more precise latency estimation (per-peer & request)
29 * - introduce random latency in processing
30 * - tell other peers to stop migration if our PUTs fail (or if
31 * we don't support migration per configuration?)
36 #include "gnunet_constants.h"
37 #include "gnunet_core_service.h"
38 #include "gnunet_datastore_service.h"
39 #include "gnunet_peer_lib.h"
40 #include "gnunet_protocols.h"
41 #include "gnunet_signatures.h"
42 #include "gnunet_statistics_service.h"
43 #include "gnunet_util_lib.h"
44 #include "gnunet-service-fs_indexing.h"
47 #define DEBUG_FS GNUNET_NO
50 * Maximum number of outgoing messages we queue per peer.
52 #define MAX_QUEUE_PER_PEER 16
55 * How often do we flush trust values to disk?
57 #define TRUST_FLUSH_FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
60 * Inverse of the probability that we will submit the same query
61 * to the same peer again. If the same peer already got the query
62 * repeatedly recently, the probability is multiplied by the inverse
63 * of this number each time. Note that we only try about every TTL_DECREMENT/2
64 * plus MAX_CORK_DELAY (so roughly every 3.5s).
66 #define RETRY_PROBABILITY_INV 3
69 * What is the maximum delay for a P2P FS message (in our interaction
70 * with core)? FS-internal delays are another story. The value is
71 * chosen based on the 32k block size. Given that peers typcially
72 * have at least 1 kb/s bandwidth, 45s waits give us a chance to
73 * transmit one message even to the lowest-bandwidth peers.
75 #define MAX_TRANSMIT_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 45)
78 * Maximum number of requests (from other peers) that we're
79 * willing to have pending at any given point in time.
81 static unsigned long long max_pending_requests = (32 * 1024);
85 * Information we keep for each pending reply. The
86 * actual message follows at the end of this struct.
88 struct PendingMessage;
91 * Function called upon completion of a transmission.
94 * @param pid ID of receiving peer, 0 on transmission error
96 typedef void (*TransmissionContinuation)(void * cls,
101 * Information we keep for each pending message (GET/PUT). The
102 * actual message follows at the end of this struct.
104 struct PendingMessage
107 * This is a doubly-linked list of messages to the same peer.
109 struct PendingMessage *next;
112 * This is a doubly-linked list of messages to the same peer.
114 struct PendingMessage *prev;
117 * Entry in pending message list for this pending message.
119 struct PendingMessageList *pml;
122 * Function to call immediately once we have transmitted this
125 TransmissionContinuation cont;
133 * Size of the reply; actual reply message follows
134 * at the end of this struct.
139 * How important is this message for us?
147 * Information about a peer that we are connected to.
148 * We track data that is useful for determining which
149 * peers should receive our requests. We also keep
150 * a list of messages to transmit to this peer.
156 * List of the last clients for which this peer successfully
159 struct GNUNET_SERVER_Client *last_client_replies[CS2P_SUCCESS_LIST_SIZE];
162 * List of the last PIDs for which
163 * this peer successfully answered a query;
164 * We use 0 to indicate no successful reply.
166 GNUNET_PEER_Id last_p2p_replies[P2P_SUCCESS_LIST_SIZE];
169 * Average delay between sending the peer a request and
170 * getting a reply (only calculated over the requests for
171 * which we actually got a reply). Calculated
172 * as a moving average: new_delay = ((n-1)*last_delay+curr_delay) / n
174 struct GNUNET_TIME_Relative avg_delay;
177 * Handle for an active request for transmission to this
180 struct GNUNET_CORE_TransmitHandle *cth;
183 * Messages (replies, queries, content migration) we would like to
184 * send to this peer in the near future. Sorted by priority, head.
186 struct PendingMessage *pending_messages_head;
189 * Messages (replies, queries, content migration) we would like to
190 * send to this peer in the near future. Sorted by priority, tail.
192 struct PendingMessage *pending_messages_tail;
195 * Average priority of successful replies. Calculated
196 * as a moving average: new_avg = ((n-1)*last_avg+curr_prio) / n
201 * Increase in traffic preference still to be submitted
202 * to the core service for this peer.
204 uint64_t inc_preference;
207 * Trust rating for this peer
212 * Trust rating for this peer on disk.
217 * The peer's identity.
222 * Size of the linked list of 'pending_messages'.
224 unsigned int pending_requests;
227 * Which offset in "last_p2p_replies" will be updated next?
228 * (we go round-robin).
230 unsigned int last_p2p_replies_woff;
233 * Which offset in "last_client_replies" will be updated next?
234 * (we go round-robin).
236 unsigned int last_client_replies_woff;
242 * Information we keep for each pending request. We should try to
243 * keep this struct as small as possible since its memory consumption
244 * is key to how many requests we can have pending at once.
246 struct PendingRequest;
250 * Doubly-linked list of requests we are performing
251 * on behalf of the same client.
253 struct ClientRequestList
257 * This is a doubly-linked list.
259 struct ClientRequestList *next;
262 * This is a doubly-linked list.
264 struct ClientRequestList *prev;
267 * Request this entry represents.
269 struct PendingRequest *req;
272 * Client list this request belongs to.
274 struct ClientList *client_list;
280 * Replies to be transmitted to the client. The actual
281 * response message is allocated after this struct.
283 struct ClientResponseMessage
286 * This is a doubly-linked list.
288 struct ClientResponseMessage *next;
291 * This is a doubly-linked list.
293 struct ClientResponseMessage *prev;
296 * Client list entry this response belongs to.
298 struct ClientList *client_list;
301 * Number of bytes in the response.
308 * Linked list of clients we are performing requests
314 * This is a linked list.
316 struct ClientList *next;
319 * ID of a client making a request, NULL if this entry is for a
322 struct GNUNET_SERVER_Client *client;
325 * Head of list of requests performed on behalf
326 * of this client right now.
328 struct ClientRequestList *rl_head;
331 * Tail of list of requests performed on behalf
332 * of this client right now.
334 struct ClientRequestList *rl_tail;
337 * Head of linked list of responses.
339 struct ClientResponseMessage *res_head;
342 * Tail of linked list of responses.
344 struct ClientResponseMessage *res_tail;
347 * Context for sending replies.
349 struct GNUNET_CONNECTION_TransmitHandle *th;
355 * Doubly-linked list of messages we are performing
356 * due to a pending request.
358 struct PendingMessageList
362 * This is a doubly-linked list of messages on behalf of the same request.
364 struct PendingMessageList *next;
367 * This is a doubly-linked list of messages on behalf of the same request.
369 struct PendingMessageList *prev;
372 * Message this entry represents.
374 struct PendingMessage *pm;
377 * Request this entry belongs to.
379 struct PendingRequest *req;
382 * Peer this message is targeted for.
384 struct ConnectedPeer *target;
390 * Information we keep for each pending request. We should try to
391 * keep this struct as small as possible since its memory consumption
392 * is key to how many requests we can have pending at once.
394 struct PendingRequest
398 * If this request was made by a client, this is our entry in the
399 * client request list; otherwise NULL.
401 struct ClientRequestList *client_request_list;
404 * Entry of peer responsible for this entry (if this request
405 * was made by a peer).
407 struct ConnectedPeer *cp;
410 * If this is a namespace query, pointer to the hash of the public
411 * key of the namespace; otherwise NULL. Pointer will be to the
412 * end of this struct (so no need to free it).
414 const GNUNET_HashCode *namespace;
417 * Bloomfilter we use to filter out replies that we don't care about
418 * (anymore). NULL as long as we are interested in all replies.
420 struct GNUNET_CONTAINER_BloomFilter *bf;
423 * Context of our GNUNET_CORE_peer_change_preference call.
425 struct GNUNET_CORE_InformationRequestContext *irc;
428 * Hash code of all replies that we have seen so far (only valid
429 * if client is not NULL since we only track replies like this for
432 GNUNET_HashCode *replies_seen;
435 * Node in the heap representing this entry; NULL
436 * if we have no heap node.
438 struct GNUNET_CONTAINER_HeapNode *hnode;
441 * Head of list of messages being performed on behalf of this
444 struct PendingMessageList *pending_head;
447 * Tail of list of messages being performed on behalf of this
450 struct PendingMessageList *pending_tail;
453 * When did we first see this request (form this peer), or, if our
454 * client is initiating, when did we last initiate a search?
456 struct GNUNET_TIME_Absolute start_time;
459 * The query that this request is for.
461 GNUNET_HashCode query;
464 * The task responsible for transmitting queries
467 GNUNET_SCHEDULER_TaskIdentifier task;
470 * (Interned) Peer identifier that identifies a preferred target
473 GNUNET_PEER_Id target_pid;
476 * (Interned) Peer identifiers of peers that have already
477 * received our query for this content.
479 GNUNET_PEER_Id *used_pids;
482 * Our entry in the queue (non-NULL while we wait for our
483 * turn to interact with the local database).
485 struct GNUNET_DATASTORE_QueueEntry *qe;
488 * Size of the 'bf' (in bytes).
493 * Desired anonymity level; only valid for requests from a local client.
495 uint32_t anonymity_level;
498 * How many entries in "used_pids" are actually valid?
500 unsigned int used_pids_off;
503 * How long is the "used_pids" array?
505 unsigned int used_pids_size;
508 * Number of results found for this request.
510 unsigned int results_found;
513 * How many entries in "replies_seen" are actually valid?
515 unsigned int replies_seen_off;
518 * How long is the "replies_seen" array?
520 unsigned int replies_seen_size;
523 * Priority with which this request was made. If one of our clients
524 * made the request, then this is the current priority that we are
525 * using when initiating the request. This value is used when
526 * we decide to reward other peers with trust for providing a reply.
531 * Priority points left for us to spend when forwarding this request
534 uint32_t remaining_priority;
537 * Number to mingle hashes for bloom-filter tests with.
542 * TTL with which we saw this request (or, if we initiated, TTL that
543 * we used for the request).
548 * Type of the content that this request is for.
550 enum GNUNET_BLOCK_Type type;
553 * Remove this request after transmission of the current response.
558 * GNUNET_YES if we should not forward this request to other peers.
566 * Block that is ready for migration to other peers. Actual data is at the end of the block.
568 struct MigrationReadyBlock
572 * This is a doubly-linked list.
574 struct MigrationReadyBlock *next;
577 * This is a doubly-linked list.
579 struct MigrationReadyBlock *prev;
582 * Query for the block.
584 GNUNET_HashCode query;
587 * When does this block expire?
589 struct GNUNET_TIME_Absolute expiration;
592 * Peers we would consider forwarding this
593 * block to. Zero for empty entries.
595 GNUNET_PEER_Id target_list[MIGRATION_LIST_SIZE];
603 * Number of targets already used.
605 unsigned int used_targets;
610 enum GNUNET_BLOCK_Type type;
615 * Our connection to the datastore.
617 static struct GNUNET_DATASTORE_Handle *dsh;
623 static struct GNUNET_SCHEDULER_Handle *sched;
628 static const struct GNUNET_CONFIGURATION_Handle *cfg;
631 * Map of peer identifiers to "struct ConnectedPeer" (for that peer).
633 static struct GNUNET_CONTAINER_MultiHashMap *connected_peers;
636 * Map of peer identifiers to "struct PendingRequest" (for that peer).
638 static struct GNUNET_CONTAINER_MultiHashMap *peer_request_map;
641 * Map of query identifiers to "struct PendingRequest" (for that query).
643 static struct GNUNET_CONTAINER_MultiHashMap *query_request_map;
646 * Heap with the request that will expire next at the top. Contains
647 * pointers of type "struct PendingRequest*"; these will *also* be
648 * aliased from the "requests_by_peer" data structures and the
649 * "requests_by_query" table. Note that requests from our clients
650 * don't expire and are thus NOT in the "requests_by_expiration"
651 * (or the "requests_by_peer" tables).
653 static struct GNUNET_CONTAINER_Heap *requests_by_expiration_heap;
656 * Handle for reporting statistics.
658 static struct GNUNET_STATISTICS_Handle *stats;
661 * Linked list of clients we are currently processing requests for.
663 static struct ClientList *client_list;
666 * Pointer to handle to the core service (points to NULL until we've
669 static struct GNUNET_CORE_Handle *core;
672 * Head of linked list of blocks that can be migrated.
674 static struct MigrationReadyBlock *mig_head;
677 * Tail of linked list of blocks that can be migrated.
679 static struct MigrationReadyBlock *mig_tail;
682 * Request to datastore for migration (or NULL).
684 static struct GNUNET_DATASTORE_QueueEntry *mig_qe;
687 * Where do we store trust information?
689 static char *trustDirectory;
692 * ID of task that collects blocks for migration.
694 static GNUNET_SCHEDULER_TaskIdentifier mig_task;
697 * What is the maximum frequency at which we are allowed to
698 * poll the datastore for migration content?
700 static struct GNUNET_TIME_Relative min_migration_delay;
703 * Size of the doubly-linked list of migration blocks.
705 static unsigned int mig_size;
708 * Are we allowed to migrate content to this peer.
710 static int active_migration;
713 * Typical priorities we're seeing from other peers right now. Since
714 * most priorities will be zero, this value is the weighted average of
715 * non-zero priorities seen "recently". In order to ensure that new
716 * values do not dramatically change the ratio, values are first
717 * "capped" to a reasonable range (+N of the current value) and then
718 * averaged into the existing value by a ratio of 1:N. Hence
719 * receiving the largest possible priority can still only raise our
720 * "current_priorities" by at most 1.
722 static double current_priorities;
725 * Get the filename under which we would store the GNUNET_HELLO_Message
726 * for the given host and protocol.
727 * @return filename of the form DIRECTORY/HOSTID
730 get_trust_filename (const struct GNUNET_PeerIdentity *id)
732 struct GNUNET_CRYPTO_HashAsciiEncoded fil;
735 GNUNET_CRYPTO_hash_to_enc (&id->hashPubKey, &fil);
736 GNUNET_asprintf (&fn, "%s%s%s", trustDirectory, DIR_SEPARATOR_STR, &fil);
743 * Transmit messages by copying it to the target buffer
744 * "buf". "buf" will be NULL and "size" zero if the socket was closed
745 * for writing in the meantime. In that case, do nothing
746 * (the disconnect or shutdown handler will take care of the rest).
747 * If we were able to transmit messages and there are still more
748 * pending, ask core again for further calls to this function.
750 * @param cls closure, pointer to the 'struct ConnectedPeer*'
751 * @param size number of bytes available in buf
752 * @param buf where the callee should write the message
753 * @return number of bytes written to buf
756 transmit_to_peer (void *cls,
757 size_t size, void *buf);
760 /* ******************* clean up functions ************************ */
764 * Delete the given migration block.
766 * @param mb block to delete
769 delete_migration_block (struct MigrationReadyBlock *mb)
771 GNUNET_CONTAINER_DLL_remove (mig_head,
774 GNUNET_PEER_decrement_rcs (mb->target_list,
775 MIGRATION_LIST_SIZE);
782 * Compare the distance of two peers to a key.
785 * @param p1 first peer
786 * @param p2 second peer
787 * @return GNUNET_YES if P1 is closer to key than P2
790 is_closer (const GNUNET_HashCode *key,
791 const struct GNUNET_PeerIdentity *p1,
792 const struct GNUNET_PeerIdentity *p2)
794 return GNUNET_CRYPTO_hash_xorcmp (&p1->hashPubKey,
801 * Consider migrating content to a given peer.
803 * @param cls 'struct MigrationReadyBlock*' to select
804 * targets for (or NULL for none)
805 * @param key ID of the peer
806 * @param value 'struct ConnectedPeer' of the peer
807 * @return GNUNET_YES (always continue iteration)
810 consider_migration (void *cls,
811 const GNUNET_HashCode *key,
814 struct MigrationReadyBlock *mb = cls;
815 struct ConnectedPeer *cp = value;
816 struct MigrationReadyBlock *pos;
817 struct GNUNET_PeerIdentity cppid;
818 struct GNUNET_PeerIdentity otherpid;
819 struct GNUNET_PeerIdentity worstpid;
824 /* consider 'cp' as a migration target for mb */
827 GNUNET_PEER_resolve (cp->pid,
829 repl = MIGRATION_LIST_SIZE;
830 for (i=0;i<MIGRATION_LIST_SIZE;i++)
832 if (mb->target_list[i] == 0)
834 mb->target_list[i] = cp->pid;
835 GNUNET_PEER_change_rc (mb->target_list[i], 1);
836 repl = MIGRATION_LIST_SIZE;
839 GNUNET_PEER_resolve (mb->target_list[i],
841 if ( (repl == MIGRATION_LIST_SIZE) &&
842 is_closer (&mb->query,
849 else if ( (repl != MIGRATION_LIST_SIZE) &&
850 (is_closer (&mb->query,
858 if (repl != MIGRATION_LIST_SIZE)
860 GNUNET_PEER_change_rc (mb->target_list[repl], -1);
861 mb->target_list[repl] = cp->pid;
862 GNUNET_PEER_change_rc (mb->target_list[repl], 1);
866 /* consider scheduling transmission to cp for content migration */
873 for (i=0;i<MIGRATION_LIST_SIZE;i++)
875 if (cp->pid == pos->target_list[i])
880 msize = GNUNET_MIN (msize,
888 return GNUNET_YES; /* no content available */
890 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
891 "Trying to migrate at least %u bytes to peer `%s'\n",
896 = GNUNET_CORE_notify_transmit_ready (core,
897 0, GNUNET_TIME_UNIT_FOREVER_REL,
898 (const struct GNUNET_PeerIdentity*) key,
899 msize + sizeof (struct PutMessage),
907 * Task that is run periodically to obtain blocks for content
911 * @param tc scheduler context (also unused)
914 gather_migration_blocks (void *cls,
915 const struct GNUNET_SCHEDULER_TaskContext *tc);
919 * If the migration task is not currently running, consider
920 * (re)scheduling it with the appropriate delay.
923 consider_migration_gathering ()
925 struct GNUNET_TIME_Relative delay;
931 if (mig_task != GNUNET_SCHEDULER_NO_TASK)
933 delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
935 delay = GNUNET_TIME_relative_divide (delay,
936 MAX_MIGRATION_QUEUE);
937 delay = GNUNET_TIME_relative_max (delay,
938 min_migration_delay);
939 mig_task = GNUNET_SCHEDULER_add_delayed (sched,
941 &gather_migration_blocks,
947 * Process content offered for migration.
950 * @param key key for the content
951 * @param size number of bytes in data
952 * @param data content stored
953 * @param type type of the content
954 * @param priority priority of the content
955 * @param anonymity anonymity-level for the content
956 * @param expiration expiration time for the content
957 * @param uid unique identifier for the datum;
958 * maybe 0 if no unique identifier is available
961 process_migration_content (void *cls,
962 const GNUNET_HashCode * key,
965 enum GNUNET_BLOCK_Type type,
968 struct GNUNET_TIME_Absolute
969 expiration, uint64_t uid)
971 struct MigrationReadyBlock *mb;
976 if (mig_size < MAX_MIGRATION_QUEUE)
977 consider_migration_gathering ();
980 if (type == GNUNET_BLOCK_TYPE_ONDEMAND)
983 GNUNET_FS_handle_on_demand_block (key, size, data,
984 type, priority, anonymity,
986 &process_migration_content,
988 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
992 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
993 "Retrieved block `%s' of type %u for migration\n",
997 mb = GNUNET_malloc (sizeof (struct MigrationReadyBlock) + size);
999 mb->expiration = expiration;
1002 memcpy (&mb[1], data, size);
1003 GNUNET_CONTAINER_DLL_insert_after (mig_head,
1008 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1009 &consider_migration,
1011 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1016 * Task that is run periodically to obtain blocks for content
1020 * @param tc scheduler context (also unused)
1023 gather_migration_blocks (void *cls,
1024 const struct GNUNET_SCHEDULER_TaskContext *tc)
1026 mig_task = GNUNET_SCHEDULER_NO_TASK;
1029 mig_qe = GNUNET_DATASTORE_get_random (dsh, 0, -1,
1030 GNUNET_TIME_UNIT_FOREVER_REL,
1031 &process_migration_content, NULL);
1032 GNUNET_assert (mig_qe != NULL);
1038 * We're done with a particular message list entry.
1039 * Free all associated resources.
1041 * @param pml entry to destroy
1044 destroy_pending_message_list_entry (struct PendingMessageList *pml)
1046 GNUNET_CONTAINER_DLL_remove (pml->req->pending_head,
1047 pml->req->pending_tail,
1049 GNUNET_CONTAINER_DLL_remove (pml->target->pending_messages_head,
1050 pml->target->pending_messages_tail,
1052 pml->target->pending_requests--;
1053 GNUNET_free (pml->pm);
1059 * Destroy the given pending message (and call the respective
1062 * @param pm message to destroy
1063 * @param tpid id of peer that the message was delivered to, or 0 for none
1066 destroy_pending_message (struct PendingMessage *pm,
1067 GNUNET_PEER_Id tpid)
1069 struct PendingMessageList *pml = pm->pml;
1070 TransmissionContinuation cont;
1073 GNUNET_assert (pml->pm == pm);
1074 GNUNET_assert ( (tpid == 0) || (tpid == pml->target->pid) );
1076 cont_cls = pm->cont_cls;
1077 destroy_pending_message_list_entry (pml);
1078 cont (cont_cls, tpid);
1083 * We're done processing a particular request.
1084 * Free all associated resources.
1086 * @param pr request to destroy
1089 destroy_pending_request (struct PendingRequest *pr)
1091 struct GNUNET_PeerIdentity pid;
1093 if (pr->hnode != NULL)
1095 GNUNET_CONTAINER_heap_remove_node (requests_by_expiration_heap,
1099 if (NULL == pr->client_request_list)
1101 GNUNET_STATISTICS_update (stats,
1102 gettext_noop ("# P2P searches active"),
1108 GNUNET_STATISTICS_update (stats,
1109 gettext_noop ("# client searches active"),
1113 /* might have already been removed from map in 'process_reply' (if
1114 there was a unique reply) or never inserted if it was a
1115 duplicate; hence ignore the return value here */
1116 (void) GNUNET_CONTAINER_multihashmap_remove (query_request_map,
1121 GNUNET_DATASTORE_cancel (pr->qe);
1124 if (pr->client_request_list != NULL)
1126 GNUNET_CONTAINER_DLL_remove (pr->client_request_list->client_list->rl_head,
1127 pr->client_request_list->client_list->rl_tail,
1128 pr->client_request_list);
1129 GNUNET_free (pr->client_request_list);
1130 pr->client_request_list = NULL;
1134 GNUNET_PEER_resolve (pr->cp->pid,
1136 (void) GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
1143 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
1146 if (pr->irc != NULL)
1148 GNUNET_CORE_peer_change_preference_cancel (pr->irc);
1151 if (pr->replies_seen != NULL)
1153 GNUNET_free (pr->replies_seen);
1154 pr->replies_seen = NULL;
1156 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
1158 GNUNET_SCHEDULER_cancel (sched,
1160 pr->task = GNUNET_SCHEDULER_NO_TASK;
1162 while (NULL != pr->pending_head)
1163 destroy_pending_message_list_entry (pr->pending_head);
1164 GNUNET_PEER_change_rc (pr->target_pid, -1);
1165 if (pr->used_pids != NULL)
1167 GNUNET_PEER_decrement_rcs (pr->used_pids, pr->used_pids_off);
1168 GNUNET_free (pr->used_pids);
1169 pr->used_pids_off = 0;
1170 pr->used_pids_size = 0;
1171 pr->used_pids = NULL;
1178 * Method called whenever a given peer connects.
1180 * @param cls closure, not used
1181 * @param peer peer identity this notification is about
1182 * @param latency reported latency of the connection with 'other'
1183 * @param distance reported distance (DV) to 'other'
1186 peer_connect_handler (void *cls,
1188 GNUNET_PeerIdentity * peer,
1189 struct GNUNET_TIME_Relative latency,
1192 struct ConnectedPeer *cp;
1193 struct MigrationReadyBlock *pos;
1197 cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
1198 cp->pid = GNUNET_PEER_intern (peer);
1200 fn = get_trust_filename (peer);
1201 if ((GNUNET_DISK_file_test (fn) == GNUNET_YES) &&
1202 (sizeof (trust) == GNUNET_DISK_fn_read (fn, &trust, sizeof (trust))))
1203 cp->disk_trust = cp->trust = ntohl (trust);
1206 GNUNET_break (GNUNET_OK ==
1207 GNUNET_CONTAINER_multihashmap_put (connected_peers,
1210 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1215 (void) consider_migration (pos, &peer->hashPubKey, cp);
1222 * Increase the host credit by a value.
1224 * @param host which peer to change the trust value on
1225 * @param value is the int value by which the
1226 * host credit is to be increased or decreased
1227 * @returns the actual change in trust (positive or negative)
1230 change_host_trust (struct ConnectedPeer *host, int value)
1232 unsigned int old_trust;
1236 GNUNET_assert (host != NULL);
1237 old_trust = host->trust;
1240 if (host->trust + value < host->trust)
1242 value = UINT32_MAX - host->trust;
1243 host->trust = UINT32_MAX;
1246 host->trust += value;
1250 if (host->trust < -value)
1252 value = -host->trust;
1256 host->trust += value;
1263 * Write host-trust information to a file - flush the buffer entry!
1266 flush_trust (void *cls,
1267 const GNUNET_HashCode *key,
1270 struct ConnectedPeer *host = value;
1273 struct GNUNET_PeerIdentity pid;
1275 if (host->trust == host->disk_trust)
1276 return GNUNET_OK; /* unchanged */
1277 GNUNET_PEER_resolve (host->pid,
1279 fn = get_trust_filename (&pid);
1280 if (host->trust == 0)
1282 if ((0 != UNLINK (fn)) && (errno != ENOENT))
1283 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
1284 GNUNET_ERROR_TYPE_BULK, "unlink", fn);
1288 trust = htonl (host->trust);
1289 if (sizeof(uint32_t) == GNUNET_DISK_fn_write (fn, &trust,
1291 GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE
1292 | GNUNET_DISK_PERM_GROUP_READ | GNUNET_DISK_PERM_OTHER_READ))
1293 host->disk_trust = host->trust;
1300 * Call this method periodically to scan data/hosts for new hosts.
1303 cron_flush_trust (void *cls,
1304 const struct GNUNET_SCHEDULER_TaskContext *tc)
1307 if (NULL == connected_peers)
1309 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1314 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1316 GNUNET_SCHEDULER_add_delayed (tc->sched,
1317 TRUST_FLUSH_FREQ, &cron_flush_trust, NULL);
1322 * Free (each) request made by the peer.
1324 * @param cls closure, points to peer that the request belongs to
1325 * @param key current key code
1326 * @param value value in the hash map
1327 * @return GNUNET_YES (we should continue to iterate)
1330 destroy_request (void *cls,
1331 const GNUNET_HashCode * key,
1334 const struct GNUNET_PeerIdentity * peer = cls;
1335 struct PendingRequest *pr = value;
1337 GNUNET_break (GNUNET_YES ==
1338 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
1341 destroy_pending_request (pr);
1347 * Method called whenever a peer disconnects.
1349 * @param cls closure, not used
1350 * @param peer peer identity this notification is about
1353 peer_disconnect_handler (void *cls,
1355 GNUNET_PeerIdentity * peer)
1357 struct ConnectedPeer *cp;
1358 struct PendingMessage *pm;
1360 struct MigrationReadyBlock *pos;
1361 struct MigrationReadyBlock *next;
1363 GNUNET_CONTAINER_multihashmap_get_multiple (peer_request_map,
1367 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1371 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1373 if (NULL != cp->last_client_replies[i])
1375 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1376 cp->last_client_replies[i] = NULL;
1379 GNUNET_break (GNUNET_YES ==
1380 GNUNET_CONTAINER_multihashmap_remove (connected_peers,
1383 /* remove this peer from migration considerations; schedule
1386 while (NULL != (pos = next))
1389 for (i=0;i<MIGRATION_LIST_SIZE;i++)
1391 if (pos->target_list[i] == cp->pid)
1393 GNUNET_PEER_change_rc (pos->target_list[i], -1);
1394 pos->target_list[i] = 0;
1397 if (pos->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers))
1399 delete_migration_block (pos);
1400 consider_migration_gathering ();
1403 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1404 &consider_migration,
1407 GNUNET_PEER_change_rc (cp->pid, -1);
1408 GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
1409 if (NULL != cp->cth)
1410 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
1411 while (NULL != (pm = cp->pending_messages_head))
1412 destroy_pending_message (pm, 0 /* delivery failed */);
1413 GNUNET_break (0 == cp->pending_requests);
1419 * Iterator over hash map entries that removes all occurences
1420 * of the given 'client' from the 'last_client_replies' of the
1421 * given connected peer.
1423 * @param cls closure, the 'struct GNUNET_SERVER_Client*' to remove
1424 * @param key current key code (unused)
1425 * @param value value in the hash map (the 'struct ConnectedPeer*' to change)
1426 * @return GNUNET_YES (we should continue to iterate)
1429 remove_client_from_last_client_replies (void *cls,
1430 const GNUNET_HashCode * key,
1433 struct GNUNET_SERVER_Client *client = cls;
1434 struct ConnectedPeer *cp = value;
1437 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1439 if (cp->last_client_replies[i] == client)
1441 GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1442 cp->last_client_replies[i] = NULL;
1450 * A client disconnected. Remove all of its pending queries.
1452 * @param cls closure, NULL
1453 * @param client identification of the client
1456 handle_client_disconnect (void *cls,
1457 struct GNUNET_SERVER_Client
1460 struct ClientList *pos;
1461 struct ClientList *prev;
1462 struct ClientRequestList *rcl;
1463 struct ClientResponseMessage *creply;
1469 while ( (NULL != pos) &&
1470 (pos->client != client) )
1476 return; /* no requests pending for this client */
1477 while (NULL != (rcl = pos->rl_head))
1479 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1480 "Destroying pending request `%s' on disconnect\n",
1481 GNUNET_h2s (&rcl->req->query));
1482 destroy_pending_request (rcl->req);
1485 client_list = pos->next;
1487 prev->next = pos->next;
1488 if (pos->th != NULL)
1490 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
1493 while (NULL != (creply = pos->res_head))
1495 GNUNET_CONTAINER_DLL_remove (pos->res_head,
1498 GNUNET_free (creply);
1500 GNUNET_SERVER_client_drop (pos->client);
1502 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1503 &remove_client_from_last_client_replies,
1509 * Iterator to free peer entries.
1511 * @param cls closure, unused
1512 * @param key current key code
1513 * @param value value in the hash map (peer entry)
1514 * @return GNUNET_YES (we should continue to iterate)
1517 clean_peer (void *cls,
1518 const GNUNET_HashCode * key,
1521 peer_disconnect_handler (NULL, (const struct GNUNET_PeerIdentity*) key);
1527 * Task run during shutdown.
1533 shutdown_task (void *cls,
1534 const struct GNUNET_SCHEDULER_TaskContext *tc)
1538 GNUNET_DATASTORE_cancel (mig_qe);
1541 if (GNUNET_SCHEDULER_NO_TASK != mig_task)
1543 GNUNET_SCHEDULER_cancel (sched, mig_task);
1544 mig_task = GNUNET_SCHEDULER_NO_TASK;
1546 while (client_list != NULL)
1547 handle_client_disconnect (NULL,
1548 client_list->client);
1549 cron_flush_trust (NULL, NULL);
1550 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1553 GNUNET_break (0 == GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap));
1554 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
1555 requests_by_expiration_heap = 0;
1556 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
1557 connected_peers = NULL;
1558 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (query_request_map));
1559 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
1560 query_request_map = NULL;
1561 GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (peer_request_map));
1562 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
1563 peer_request_map = NULL;
1564 GNUNET_assert (NULL != core);
1565 GNUNET_CORE_disconnect (core);
1569 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1572 GNUNET_DATASTORE_disconnect (dsh,
1574 while (mig_head != NULL)
1575 delete_migration_block (mig_head);
1576 GNUNET_assert (0 == mig_size);
1580 GNUNET_free_non_null (trustDirectory);
1581 trustDirectory = NULL;
1585 /* ******************* Utility functions ******************** */
1589 * Transmit messages by copying it to the target buffer
1590 * "buf". "buf" will be NULL and "size" zero if the socket was closed
1591 * for writing in the meantime. In that case, do nothing
1592 * (the disconnect or shutdown handler will take care of the rest).
1593 * If we were able to transmit messages and there are still more
1594 * pending, ask core again for further calls to this function.
1596 * @param cls closure, pointer to the 'struct ConnectedPeer*'
1597 * @param size number of bytes available in buf
1598 * @param buf where the callee should write the message
1599 * @return number of bytes written to buf
1602 transmit_to_peer (void *cls,
1603 size_t size, void *buf)
1605 struct ConnectedPeer *cp = cls;
1607 struct GNUNET_PeerIdentity pid;
1608 struct PendingMessage *pm;
1609 struct MigrationReadyBlock *mb;
1610 struct MigrationReadyBlock *next;
1611 struct PutMessage migm;
1619 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1620 "Dropping message, core too busy.\n");
1625 while ( (NULL != (pm = cp->pending_messages_head) ) &&
1626 (pm->msize <= size) )
1628 memcpy (&cbuf[msize], &pm[1], pm->msize);
1631 destroy_pending_message (pm, cp->pid);
1635 GNUNET_PEER_resolve (cp->pid,
1637 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1639 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1648 while (NULL != (mb = next))
1651 for (i=0;i<MIGRATION_LIST_SIZE;i++)
1653 if ( (cp->pid == mb->target_list[i]) &&
1654 (mb->size + sizeof (migm) <= size) )
1656 GNUNET_PEER_change_rc (mb->target_list[i], -1);
1657 mb->target_list[i] = 0;
1659 migm.header.size = htons (sizeof (migm) + mb->size);
1660 migm.header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
1661 migm.type = htonl (mb->type);
1662 migm.expiration = GNUNET_TIME_absolute_hton (mb->expiration);
1663 memcpy (&cbuf[msize], &migm, sizeof (migm));
1664 msize += sizeof (migm);
1665 size -= sizeof (migm);
1666 memcpy (&cbuf[msize], &mb[1], mb->size);
1670 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1671 "Pushing migration block `%s' (%u bytes) to `%s'\n",
1672 GNUNET_h2s (&mb->query),
1681 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1682 "Migration block `%s' (%u bytes) is not on migration list for peer `%s'\n",
1683 GNUNET_h2s (&mb->query),
1689 if ( (mb->used_targets >= MIGRATION_TARGET_COUNT) ||
1690 (mb->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers)) )
1692 delete_migration_block (mb);
1693 consider_migration_gathering ();
1696 consider_migration (NULL,
1701 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1702 "Transmitting %u bytes to peer %u\n",
1711 * Add a message to the set of pending messages for the given peer.
1713 * @param cp peer to send message to
1714 * @param pm message to queue
1715 * @param pr request on which behalf this message is being queued
1718 add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
1719 struct PendingMessage *pm,
1720 struct PendingRequest *pr)
1722 struct PendingMessage *pos;
1723 struct PendingMessageList *pml;
1724 struct GNUNET_PeerIdentity pid;
1726 GNUNET_assert (pm->next == NULL);
1727 GNUNET_assert (pm->pml == NULL);
1728 pml = GNUNET_malloc (sizeof (struct PendingMessageList));
1733 GNUNET_CONTAINER_DLL_insert (pr->pending_head,
1736 pos = cp->pending_messages_head;
1737 while ( (pos != NULL) &&
1738 (pm->priority < pos->priority) )
1740 GNUNET_CONTAINER_DLL_insert_after (cp->pending_messages_head,
1741 cp->pending_messages_tail,
1744 cp->pending_requests++;
1745 if (cp->pending_requests > MAX_QUEUE_PER_PEER)
1746 destroy_pending_message (cp->pending_messages_tail, 0);
1747 GNUNET_PEER_resolve (cp->pid, &pid);
1748 if (NULL != cp->cth)
1749 GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
1750 /* need to schedule transmission */
1751 cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1752 cp->pending_messages_head->priority,
1755 cp->pending_messages_head->msize,
1758 if (cp->cth == NULL)
1761 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1762 "Failed to schedule transmission with core!\n");
1764 GNUNET_STATISTICS_update (stats,
1765 gettext_noop ("# CORE transmission failures"),
1773 * Mingle hash with the mingle_number to produce different bits.
1776 mingle_hash (const GNUNET_HashCode * in,
1777 int32_t mingle_number,
1778 GNUNET_HashCode * hc)
1782 GNUNET_CRYPTO_hash (&mingle_number,
1785 GNUNET_CRYPTO_hash_xor (&m, in, hc);
1790 * Test if the load on this peer is too high
1791 * to even consider processing the query at
1794 * @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)
1797 test_load_too_high ()
1799 return GNUNET_SYSERR; // FIXME
1803 /* ******************* Pending Request Refresh Task ******************** */
1808 * We use a random delay to make the timing of requests less
1809 * predictable. This function returns such a random delay. We add a base
1810 * delay of MAX_CORK_DELAY (1s).
1812 * FIXME: make schedule dependent on the specifics of the request?
1813 * Or bandwidth and number of connected peers and load?
1815 * @return random delay to use for some request, between 1s and 1000+TTL_DECREMENT ms
1817 static struct GNUNET_TIME_Relative
1818 get_processing_delay ()
1821 GNUNET_TIME_relative_add (GNUNET_CONSTANTS_MAX_CORK_DELAY,
1822 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1823 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1829 * We're processing a GET request from another peer and have decided
1830 * to forward it to other peers. This function is called periodically
1831 * and should forward the request to other peers until we have all
1832 * possible replies. If we have transmitted the *only* reply to
1833 * the initiator we should destroy the pending request. If we have
1834 * many replies in the queue to the initiator, we should delay sending
1835 * out more queries until the reply queue has shrunk some.
1837 * @param cls our "struct ProcessGetContext *"
1841 forward_request_task (void *cls,
1842 const struct GNUNET_SCHEDULER_TaskContext *tc);
1846 * Function called after we either failed or succeeded
1847 * at transmitting a query to a peer.
1849 * @param cls the requests "struct PendingRequest*"
1850 * @param tpid ID of receiving peer, 0 on transmission error
1853 transmit_query_continuation (void *cls,
1854 GNUNET_PEER_Id tpid)
1856 struct PendingRequest *pr = cls;
1858 GNUNET_STATISTICS_update (stats,
1859 gettext_noop ("# queries scheduled for forwarding"),
1865 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1866 "Transmission of request failed, will try again later.\n");
1868 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1869 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1870 get_processing_delay (),
1871 &forward_request_task,
1875 GNUNET_STATISTICS_update (stats,
1876 gettext_noop ("# queries forwarded"),
1879 GNUNET_PEER_change_rc (tpid, 1);
1880 if (pr->used_pids_off == pr->used_pids_size)
1881 GNUNET_array_grow (pr->used_pids,
1883 pr->used_pids_size * 2 + 2);
1884 pr->used_pids[pr->used_pids_off++] = tpid;
1885 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1886 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1887 get_processing_delay (),
1888 &forward_request_task,
1894 * How many bytes should a bloomfilter be if we have already seen
1895 * entry_count responses? Note that BLOOMFILTER_K gives us the number
1896 * of bits set per entry. Furthermore, we should not re-size the
1897 * filter too often (to keep it cheap).
1899 * Since other peers will also add entries but not resize the filter,
1900 * we should generally pick a slightly larger size than what the
1901 * strict math would suggest.
1903 * @return must be a power of two and smaller or equal to 2^15.
1906 compute_bloomfilter_size (unsigned int entry_count)
1909 unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
1910 uint16_t max = 1 << 15;
1912 if (entry_count > max)
1915 while ((size < max) && (size < ideal))
1924 * Recalculate our bloom filter for filtering replies. This function
1925 * will create a new bloom filter from scratch, so it should only be
1926 * called if we have no bloomfilter at all (and hence can create a
1927 * fresh one of minimal size without problems) OR if our peer is the
1928 * initiator (in which case we may resize to larger than mimimum size).
1930 * @param pr request for which the BF is to be recomputed
1933 refresh_bloomfilter (struct PendingRequest *pr)
1937 GNUNET_HashCode mhash;
1939 nsize = compute_bloomfilter_size (pr->replies_seen_off);
1940 if (nsize == pr->bf_size)
1941 return; /* size not changed */
1943 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
1944 pr->bf_size = nsize;
1945 pr->mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
1946 pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1949 for (i=0;i<pr->replies_seen_off;i++)
1951 mingle_hash (&pr->replies_seen[i], pr->mingle, &mhash);
1952 GNUNET_CONTAINER_bloomfilter_add (pr->bf, &mhash);
1958 * Function called after we've tried to reserve a certain amount of
1959 * bandwidth for a reply. Check if we succeeded and if so send our
1962 * @param cls the requests "struct PendingRequest*"
1963 * @param peer identifies the peer
1964 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1965 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1966 * @param amount set to the amount that was actually reserved or unreserved
1967 * @param preference current traffic preference for the given peer
1970 target_reservation_cb (void *cls,
1972 GNUNET_PeerIdentity * peer,
1973 struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
1974 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1976 uint64_t preference)
1978 struct PendingRequest *pr = cls;
1979 struct ConnectedPeer *cp;
1980 struct PendingMessage *pm;
1981 struct GetMessage *gm;
1982 GNUNET_HashCode *ext;
1992 /* error in communication with core, try again later */
1993 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1994 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1995 get_processing_delay (),
1996 &forward_request_task,
2000 // (3) transmit, update ttl/priority
2001 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2005 /* Peer must have just left */
2007 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2008 "Selected peer disconnected!\n");
2010 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2011 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
2012 get_processing_delay (),
2013 &forward_request_task,
2017 no_route = GNUNET_NO;
2023 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2024 "Failed to reserve bandwidth for reply (got %d/%u bytes only)!\n",
2028 GNUNET_STATISTICS_update (stats,
2029 gettext_noop ("# reply bandwidth reservation requests failed"),
2032 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2033 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
2034 get_processing_delay (),
2035 &forward_request_task,
2037 return; /* this target round failed */
2039 /* FIXME: if we are "quite" busy, we may still want to skip
2040 this round; need more load detection code! */
2041 no_route = GNUNET_YES;
2044 GNUNET_STATISTICS_update (stats,
2045 gettext_noop ("# queries scheduled for forwarding"),
2048 /* build message and insert message into priority queue */
2050 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2051 "Forwarding request `%s' to `%4s'!\n",
2052 GNUNET_h2s (&pr->query),
2057 if (GNUNET_YES == no_route)
2059 bm |= GET_MESSAGE_BIT_RETURN_TO;
2062 if (pr->namespace != NULL)
2064 bm |= GET_MESSAGE_BIT_SKS_NAMESPACE;
2067 if (pr->target_pid != 0)
2069 bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
2072 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
2073 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
2074 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
2076 gm = (struct GetMessage*) &pm[1];
2077 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
2078 gm->header.size = htons (msize);
2079 gm->type = htonl (pr->type);
2080 pr->remaining_priority /= 2;
2081 gm->priority = htonl (pr->remaining_priority);
2082 gm->ttl = htonl (pr->ttl);
2083 gm->filter_mutator = htonl(pr->mingle);
2084 gm->hash_bitmap = htonl (bm);
2085 gm->query = pr->query;
2086 ext = (GNUNET_HashCode*) &gm[1];
2088 if (GNUNET_YES == no_route)
2089 GNUNET_PEER_resolve (pr->cp->pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
2090 if (pr->namespace != NULL)
2091 memcpy (&ext[k++], pr->namespace, sizeof (GNUNET_HashCode));
2092 if (pr->target_pid != 0)
2093 GNUNET_PEER_resolve (pr->target_pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
2094 bfdata = (char *) &ext[k];
2096 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
2099 pm->cont = &transmit_query_continuation;
2101 add_to_pending_messages_for_peer (cp, pm, pr);
2106 * Closure used for "target_peer_select_cb".
2108 struct PeerSelectionContext
2111 * The request for which we are selecting
2114 struct PendingRequest *pr;
2117 * Current "prime" target.
2119 struct GNUNET_PeerIdentity target;
2122 * How much do we like this target?
2124 double target_score;
2130 * Function called for each connected peer to determine
2131 * which one(s) would make good targets for forwarding.
2133 * @param cls closure (struct PeerSelectionContext)
2134 * @param key current key code (peer identity)
2135 * @param value value in the hash map (struct ConnectedPeer)
2136 * @return GNUNET_YES if we should continue to
2141 target_peer_select_cb (void *cls,
2142 const GNUNET_HashCode * key,
2145 struct PeerSelectionContext *psc = cls;
2146 struct ConnectedPeer *cp = value;
2147 struct PendingRequest *pr = psc->pr;
2152 /* 1) check that this peer is not the initiator */
2156 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2157 "Skipping initiator in forwarding selection\n");
2159 return GNUNET_YES; /* skip */
2162 /* 2) check if we have already (recently) forwarded to this peer */
2164 for (i=0;i<pr->used_pids_off;i++)
2165 if (pr->used_pids[i] == cp->pid)
2168 if (0 != GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2169 RETRY_PROBABILITY_INV))
2172 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2173 "NOT re-trying query that was previously transmitted %u times\n",
2174 (unsigned int) pr->used_pids_off);
2176 return GNUNET_YES; /* skip */
2181 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2182 "Re-trying query that was previously transmitted %u times to this peer\n",
2185 /* 3) calculate how much we'd like to forward to this peer,
2186 starting with a random value that is strong enough
2187 to at least give any peer a chance sometimes
2188 (compared to the other factors that come later) */
2189 /* 3a) count successful (recent) routes from cp for same source */
2192 score = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2193 P2P_SUCCESS_LIST_SIZE);
2194 for (i=0;i<P2P_SUCCESS_LIST_SIZE;i++)
2195 if (cp->last_p2p_replies[i] == pr->cp->pid)
2196 score += 1; /* likely successful based on hot path */
2200 score = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2201 CS2P_SUCCESS_LIST_SIZE);
2202 for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
2203 if (cp->last_client_replies[i] == pr->client_request_list->client_list->client)
2204 score += 1; /* likely successful based on hot path */
2206 /* 3b) include latency */
2207 if (cp->avg_delay.value < 4 * TTL_DECREMENT)
2208 score += 1; /* likely fast based on latency */
2209 /* 3c) include priorities */
2210 if (cp->avg_priority <= pr->remaining_priority / 2.0)
2211 score += 1; /* likely successful based on priorities */
2212 /* 3d) penalize for queue size */
2213 score -= (2.0 * cp->pending_requests / (double) MAX_QUEUE_PER_PEER);
2214 /* 3e) include peer proximity */
2215 score -= (2.0 * (GNUNET_CRYPTO_hash_distance_u32 (key,
2216 &pr->query)) / (double) UINT32_MAX);
2217 /* 4) super-bonus for being the known target */
2218 if (pr->target_pid == cp->pid)
2220 /* store best-fit in closure */
2222 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2223 "Peer `%s' gets score %f for forwarding query, max is %f\n",
2228 score++; /* avoid zero */
2229 if (score > psc->target_score)
2231 psc->target_score = score;
2232 psc->target.hashPubKey = *key;
2239 * The priority level imposes a bound on the maximum
2240 * value for the ttl that can be requested.
2242 * @param ttl_in requested ttl
2243 * @param prio given priority
2244 * @return ttl_in if ttl_in is below the limit,
2245 * otherwise the ttl-limit for the given priority
2248 bound_ttl (int32_t ttl_in, uint32_t prio)
2250 unsigned long long allowed;
2254 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
2255 if (ttl_in > allowed)
2257 if (allowed >= (1 << 30))
2266 * We're processing a GET request and have decided
2267 * to forward it to other peers. This function is called periodically
2268 * and should forward the request to other peers until we have all
2269 * possible replies. If we have transmitted the *only* reply to
2270 * the initiator we should destroy the pending request. If we have
2271 * many replies in the queue to the initiator, we should delay sending
2272 * out more queries until the reply queue has shrunk some.
2274 * @param cls our "struct ProcessGetContext *"
2278 forward_request_task (void *cls,
2279 const struct GNUNET_SCHEDULER_TaskContext *tc)
2281 struct PendingRequest *pr = cls;
2282 struct PeerSelectionContext psc;
2283 struct ConnectedPeer *cp;
2284 struct GNUNET_TIME_Relative delay;
2286 pr->task = GNUNET_SCHEDULER_NO_TASK;
2287 if (pr->irc != NULL)
2290 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2291 "Forwarding of query `%s' not attempted due to pending local lookup!\n",
2292 GNUNET_h2s (&pr->query));
2294 return; /* already pending */
2296 if (GNUNET_YES == pr->local_only)
2297 return; /* configured to not do P2P search */
2298 /* (1) select target */
2300 psc.target_score = -DBL_MAX;
2301 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
2302 &target_peer_select_cb,
2304 if (psc.target_score == -DBL_MAX)
2306 delay = get_processing_delay ();
2308 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2309 "No peer selected for forwarding of query `%s', will try again in %llu ms!\n",
2310 GNUNET_h2s (&pr->query),
2313 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
2315 &forward_request_task,
2317 return; /* nobody selected */
2319 /* (3) update TTL/priority */
2320 if (pr->client_request_list != NULL)
2322 /* FIXME: use better algorithm!? */
2323 if (0 == GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2326 /* bound priority we use by priorities we see from other peers
2327 rounded up (must round up so that we can see non-zero
2328 priorities, but round up as little as possible to make it
2329 plausible that we forwarded another peers request) */
2330 if (pr->priority > current_priorities + 1.0)
2331 pr->priority = (uint32_t) current_priorities + 1.0;
2332 pr->ttl = bound_ttl (pr->ttl + TTL_DECREMENT * 2,
2335 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2336 "Trying query `%s' with priority %u and TTL %d.\n",
2337 GNUNET_h2s (&pr->query),
2343 /* (3) reserve reply bandwidth */
2344 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2345 &psc.target.hashPubKey);
2346 GNUNET_assert (NULL != cp);
2347 pr->irc = GNUNET_CORE_peer_change_preference (sched, cfg,
2349 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
2350 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
2353 &target_reservation_cb,
2355 cp->inc_preference = 0;
2359 /* **************************** P2P PUT Handling ************************ */
2363 * Function called after we either failed or succeeded
2364 * at transmitting a reply to a peer.
2366 * @param cls the requests "struct PendingRequest*"
2367 * @param tpid ID of receiving peer, 0 on transmission error
2370 transmit_reply_continuation (void *cls,
2371 GNUNET_PEER_Id tpid)
2373 struct PendingRequest *pr = cls;
2377 case GNUNET_BLOCK_TYPE_DBLOCK:
2378 case GNUNET_BLOCK_TYPE_IBLOCK:
2379 /* only one reply expected, done with the request! */
2380 destroy_pending_request (pr);
2382 case GNUNET_BLOCK_TYPE_ANY:
2383 case GNUNET_BLOCK_TYPE_KBLOCK:
2384 case GNUNET_BLOCK_TYPE_SBLOCK:
2394 * Transmit the given message by copying it to the target buffer
2395 * "buf". "buf" will be NULL and "size" zero if the socket was closed
2396 * for writing in the meantime. In that case, do nothing
2397 * (the disconnect or shutdown handler will take care of the rest).
2398 * If we were able to transmit messages and there are still more
2399 * pending, ask core again for further calls to this function.
2401 * @param cls closure, pointer to the 'struct ClientList*'
2402 * @param size number of bytes available in buf
2403 * @param buf where the callee should write the message
2404 * @return number of bytes written to buf
2407 transmit_to_client (void *cls,
2408 size_t size, void *buf)
2410 struct ClientList *cl = cls;
2412 struct ClientResponseMessage *creply;
2419 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2420 "Not sending reply, client communication problem.\n");
2425 while ( (NULL != (creply = cl->res_head) ) &&
2426 (creply->msize <= size) )
2428 memcpy (&cbuf[msize], &creply[1], creply->msize);
2429 msize += creply->msize;
2430 size -= creply->msize;
2431 GNUNET_CONTAINER_DLL_remove (cl->res_head,
2434 GNUNET_free (creply);
2437 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
2439 GNUNET_TIME_UNIT_FOREVER_REL,
2440 &transmit_to_client,
2443 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2444 "Transmitted %u bytes to client\n",
2445 (unsigned int) msize);
2452 * Closure for "process_reply" function.
2454 struct ProcessReplyClosure
2457 * The data for the reply.
2462 * Who gave us this reply? NULL for local host.
2464 struct ConnectedPeer *sender;
2467 * When the reply expires.
2469 struct GNUNET_TIME_Absolute expiration;
2477 * Namespace that this reply belongs to
2478 * (if it is of type SBLOCK).
2480 GNUNET_HashCode namespace;
2483 * Type of the block.
2485 enum GNUNET_BLOCK_Type type;
2488 * How much was this reply worth to us?
2493 * Did we finish processing the associated request?
2500 * We have received a reply; handle it!
2502 * @param cls response (struct ProcessReplyClosure)
2503 * @param key our query
2504 * @param value value in the hash map (info about the query)
2505 * @return GNUNET_YES (we should continue to iterate)
2508 process_reply (void *cls,
2509 const GNUNET_HashCode * key,
2512 struct ProcessReplyClosure *prq = cls;
2513 struct PendingRequest *pr = value;
2514 struct PendingMessage *reply;
2515 struct ClientResponseMessage *creply;
2516 struct ClientList *cl;
2517 struct PutMessage *pm;
2518 struct ConnectedPeer *cp;
2519 struct GNUNET_TIME_Relative cur_delay;
2520 GNUNET_HashCode chash;
2521 GNUNET_HashCode mhash;
2525 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2526 "Matched result (type %u) for query `%s' with pending request\n",
2527 (unsigned int) prq->type,
2530 GNUNET_STATISTICS_update (stats,
2531 gettext_noop ("# replies received and matched"),
2534 if (prq->sender != NULL)
2536 /* FIXME: should we be more precise here and not use
2537 "start_time" but a peer-specific time stamp? */
2538 cur_delay = GNUNET_TIME_absolute_get_duration (pr->start_time);
2539 prq->sender->avg_delay.value
2540 = (prq->sender->avg_delay.value *
2541 (RUNAVG_DELAY_N - 1) + cur_delay.value) / RUNAVG_DELAY_N;
2542 prq->sender->avg_priority
2543 = (prq->sender->avg_priority *
2544 (RUNAVG_DELAY_N - 1) + pr->priority) / (double) RUNAVG_DELAY_N;
2547 GNUNET_PEER_change_rc (prq->sender->last_p2p_replies
2548 [prq->sender->last_p2p_replies_woff % P2P_SUCCESS_LIST_SIZE],
2550 GNUNET_PEER_change_rc (pr->cp->pid, 1);
2551 prq->sender->last_p2p_replies
2552 [(prq->sender->last_p2p_replies_woff++) % P2P_SUCCESS_LIST_SIZE]
2557 if (NULL != prq->sender->last_client_replies
2558 [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE])
2559 GNUNET_SERVER_client_drop (prq->sender->last_client_replies
2560 [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE]);
2561 prq->sender->last_client_replies
2562 [(prq->sender->last_client_replies_woff++) % CS2P_SUCCESS_LIST_SIZE]
2563 = pr->client_request_list->client_list->client;
2564 GNUNET_SERVER_client_keep (pr->client_request_list->client_list->client);
2567 GNUNET_CRYPTO_hash (prq->data,
2572 case GNUNET_BLOCK_TYPE_DBLOCK:
2573 case GNUNET_BLOCK_TYPE_IBLOCK:
2574 /* only possible reply, stop requesting! */
2575 while (NULL != pr->pending_head)
2576 destroy_pending_message_list_entry (pr->pending_head);
2579 if (pr->client_request_list != NULL)
2580 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
2582 GNUNET_DATASTORE_cancel (pr->qe);
2585 pr->do_remove = GNUNET_YES;
2586 if (pr->task != GNUNET_SCHEDULER_NO_TASK)
2588 GNUNET_SCHEDULER_cancel (sched,
2590 pr->task = GNUNET_SCHEDULER_NO_TASK;
2592 GNUNET_break (GNUNET_YES ==
2593 GNUNET_CONTAINER_multihashmap_remove (query_request_map,
2597 case GNUNET_BLOCK_TYPE_SBLOCK:
2598 if (pr->namespace == NULL)
2603 if (0 != memcmp (pr->namespace,
2605 sizeof (GNUNET_HashCode)))
2607 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2608 _("Reply mismatched in terms of namespace. Discarded.\n"));
2609 return GNUNET_YES; /* wrong namespace */
2611 /* then: fall-through! */
2612 case GNUNET_BLOCK_TYPE_KBLOCK:
2613 case GNUNET_BLOCK_TYPE_NBLOCK:
2616 mingle_hash (&chash, pr->mingle, &mhash);
2617 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
2620 GNUNET_STATISTICS_update (stats,
2621 gettext_noop ("# duplicate replies discarded (bloomfilter)"),
2625 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2626 "Duplicate response `%s', discarding.\n",
2627 GNUNET_h2s (&mhash));
2629 return GNUNET_YES; /* duplicate */
2632 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2633 "New response `%s', adding to filter.\n",
2634 GNUNET_h2s (&mhash));
2637 if (pr->client_request_list != NULL)
2639 if (pr->replies_seen_size == pr->replies_seen_off)
2640 GNUNET_array_grow (pr->replies_seen,
2641 pr->replies_seen_size,
2642 pr->replies_seen_size * 2 + 4);
2643 pr->replies_seen[pr->replies_seen_off++] = chash;
2645 if ( (pr->bf == NULL) ||
2646 (pr->client_request_list != NULL) )
2647 refresh_bloomfilter (pr);
2648 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
2655 prq->priority += pr->remaining_priority;
2656 pr->remaining_priority = 0;
2657 if (NULL != pr->client_request_list)
2659 GNUNET_STATISTICS_update (stats,
2660 gettext_noop ("# replies received for local clients"),
2663 cl = pr->client_request_list->client_list;
2664 msize = sizeof (struct PutMessage) + prq->size;
2665 creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
2666 creply->msize = msize;
2667 creply->client_list = cl;
2668 GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
2672 pm = (struct PutMessage*) &creply[1];
2673 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2674 pm->header.size = htons (msize);
2675 pm->type = htonl (prq->type);
2676 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
2677 memcpy (&pm[1], prq->data, prq->size);
2681 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2682 "Transmitting result for query `%s' to client\n",
2685 cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
2687 GNUNET_TIME_UNIT_FOREVER_REL,
2688 &transmit_to_client,
2691 GNUNET_break (cl->th != NULL);
2694 prq->finished = GNUNET_YES;
2695 destroy_pending_request (pr);
2702 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2703 "Transmitting result for query `%s' to other peer (PID=%u)\n",
2705 (unsigned int) cp->pid);
2707 GNUNET_STATISTICS_update (stats,
2708 gettext_noop ("# replies received for other peers"),
2711 msize = sizeof (struct PutMessage) + prq->size;
2712 reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
2713 reply->cont = &transmit_reply_continuation;
2714 reply->cont_cls = pr;
2715 reply->msize = msize;
2716 reply->priority = UINT32_MAX; /* send replies first! */
2717 pm = (struct PutMessage*) &reply[1];
2718 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2719 pm->header.size = htons (msize);
2720 pm->type = htonl (prq->type);
2721 pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
2722 memcpy (&pm[1], prq->data, prq->size);
2723 add_to_pending_messages_for_peer (cp, reply, pr);
2730 * Continuation called to notify client about result of the
2733 * @param cls closure
2734 * @param success GNUNET_SYSERR on failure
2735 * @param msg NULL on success, otherwise an error message
2738 put_migration_continuation (void *cls,
2747 * Handle P2P "PUT" message.
2749 * @param cls closure, always NULL
2750 * @param other the other peer involved (sender or receiver, NULL
2751 * for loopback messages where we are both sender and receiver)
2752 * @param message the actual message
2753 * @param latency reported latency of the connection with 'other'
2754 * @param distance reported distance (DV) to 'other'
2755 * @return GNUNET_OK to keep the connection open,
2756 * GNUNET_SYSERR to close it (signal serious error)
2759 handle_p2p_put (void *cls,
2760 const struct GNUNET_PeerIdentity *other,
2761 const struct GNUNET_MessageHeader *message,
2762 struct GNUNET_TIME_Relative latency,
2765 const struct PutMessage *put;
2768 enum GNUNET_BLOCK_Type type;
2769 struct GNUNET_TIME_Absolute expiration;
2770 GNUNET_HashCode query;
2771 struct ProcessReplyClosure prq;
2772 const struct SBlock *sb;
2774 msize = ntohs (message->size);
2775 if (msize < sizeof (struct PutMessage))
2778 return GNUNET_SYSERR;
2780 put = (const struct PutMessage*) message;
2781 dsize = msize - sizeof (struct PutMessage);
2782 type = ntohl (put->type);
2783 expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
2786 GNUNET_BLOCK_check_block (type,
2791 GNUNET_break_op (0);
2792 return GNUNET_SYSERR;
2794 if (type == GNUNET_BLOCK_TYPE_ONDEMAND)
2795 return GNUNET_SYSERR;
2796 if (GNUNET_BLOCK_TYPE_SBLOCK == type)
2798 sb = (const struct SBlock*) &put[1];
2799 GNUNET_CRYPTO_hash (&sb->subspace,
2800 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2805 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2806 "Received result for query `%s' from peer `%4s'\n",
2807 GNUNET_h2s (&query),
2808 GNUNET_i2s (other));
2810 GNUNET_STATISTICS_update (stats,
2811 gettext_noop ("# replies received (overall)"),
2814 /* now, lookup 'query' */
2815 prq.data = (const void*) &put[1];
2817 prq.sender = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2818 &other->hashPubKey);
2823 prq.expiration = expiration;
2825 prq.finished = GNUNET_NO;
2826 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2830 if (prq.sender != NULL)
2832 prq.sender->inc_preference += CONTENT_BANDWIDTH_VALUE + 1000 * prq.priority;
2833 prq.sender->trust += prq.priority;
2835 if (GNUNET_YES == active_migration)
2838 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2839 "Replicating result for query `%s' with priority %u\n",
2840 GNUNET_h2s (&query),
2843 GNUNET_DATASTORE_put (dsh,
2844 0, &query, dsize, &put[1],
2845 type, prq.priority, 1 /* anonymity */,
2847 1 + prq.priority, MAX_DATASTORE_QUEUE,
2848 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
2849 &put_migration_continuation,
2856 /* **************************** P2P GET Handling ************************ */
2860 * Closure for 'check_duplicate_request_{peer,client}'.
2862 struct CheckDuplicateRequestClosure
2865 * The new request we should check if it already exists.
2867 const struct PendingRequest *pr;
2870 * Existing request found by the checker, NULL if none.
2872 struct PendingRequest *have;
2877 * Iterator over entries in the 'query_request_map' that
2878 * tries to see if we have the same request pending from
2879 * the same client already.
2881 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
2882 * @param key current key code (query, ignored, must match)
2883 * @param value value in the hash map (a 'struct PendingRequest'
2884 * that already exists)
2885 * @return GNUNET_YES if we should continue to
2886 * iterate (no match yet)
2887 * GNUNET_NO if not (match found).
2890 check_duplicate_request_client (void *cls,
2891 const GNUNET_HashCode * key,
2894 struct CheckDuplicateRequestClosure *cdc = cls;
2895 struct PendingRequest *have = value;
2897 if (have->client_request_list == NULL)
2899 if ( (cdc->pr->client_request_list->client_list->client == have->client_request_list->client_list->client) &&
2910 * We're processing (local) results for a search request
2911 * from another peer. Pass applicable results to the
2912 * peer and if we are done either clean up (operation
2913 * complete) or forward to other peers (more results possible).
2915 * @param cls our closure (struct LocalGetContext)
2916 * @param key key for the content
2917 * @param size number of bytes in data
2918 * @param data content stored
2919 * @param type type of the content
2920 * @param priority priority of the content
2921 * @param anonymity anonymity-level for the content
2922 * @param expiration expiration time for the content
2923 * @param uid unique identifier for the datum;
2924 * maybe 0 if no unique identifier is available
2927 process_local_reply (void *cls,
2928 const GNUNET_HashCode * key,
2931 enum GNUNET_BLOCK_Type type,
2934 struct GNUNET_TIME_Absolute
2938 struct PendingRequest *pr = cls;
2939 struct ProcessReplyClosure prq;
2940 struct CheckDuplicateRequestClosure cdrc;
2941 const struct SBlock *sb;
2942 GNUNET_HashCode dhash;
2943 GNUNET_HashCode mhash;
2944 GNUNET_HashCode query;
2949 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2950 "Done processing local replies, forwarding request to other peers.\n");
2953 if (pr->client_request_list != NULL)
2955 GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client,
2957 /* Figure out if this is a duplicate request and possibly
2958 merge 'struct PendingRequest' entries */
2961 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2963 &check_duplicate_request_client,
2965 if (cdrc.have != NULL)
2968 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2969 "Received request for block `%s' twice from client, will only request once.\n",
2970 GNUNET_h2s (&pr->query));
2973 destroy_pending_request (pr);
2978 /* no more results */
2979 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2980 pr->task = GNUNET_SCHEDULER_add_now (sched,
2981 &forward_request_task,
2986 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2987 "New local response to `%s' of type %u.\n",
2991 if (type == GNUNET_BLOCK_TYPE_ONDEMAND)
2994 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2995 "Found ONDEMAND block, performing on-demand encoding\n");
2997 GNUNET_STATISTICS_update (stats,
2998 gettext_noop ("# on-demand blocks matched requests"),
3002 GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
3003 anonymity, expiration, uid,
3004 &process_local_reply,
3007 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3010 /* check for duplicates */
3011 GNUNET_CRYPTO_hash (data, size, &dhash);
3012 mingle_hash (&dhash,
3015 if ( (pr->bf != NULL) &&
3017 GNUNET_CONTAINER_bloomfilter_test (pr->bf,
3021 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3022 "Result from datastore filtered by bloomfilter (duplicate).\n");
3024 GNUNET_STATISTICS_update (stats,
3025 gettext_noop ("# results filtered by query bloomfilter"),
3029 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3033 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3034 "Found result for query `%s' in local datastore\n",
3037 GNUNET_STATISTICS_update (stats,
3038 gettext_noop ("# results found locally"),
3041 pr->results_found++;
3042 memset (&prq, 0, sizeof (prq));
3044 prq.expiration = expiration;
3046 if (GNUNET_BLOCK_TYPE_SBLOCK == type)
3048 sb = (const struct SBlock*) data;
3049 GNUNET_CRYPTO_hash (&sb->subspace,
3050 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3053 if (GNUNET_OK != GNUNET_BLOCK_check_block (type,
3059 GNUNET_DATASTORE_remove (dsh,
3063 GNUNET_TIME_UNIT_FOREVER_REL,
3065 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3069 prq.priority = priority;
3070 prq.finished = GNUNET_NO;
3071 process_reply (&prq, key, pr);
3072 if (prq.finished == GNUNET_YES)
3075 return; /* done here */
3076 if ( (type == GNUNET_BLOCK_TYPE_DBLOCK) ||
3077 (type == GNUNET_BLOCK_TYPE_IBLOCK) )
3079 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
3082 if ( (pr->client_request_list == NULL) &&
3083 ( (GNUNET_YES == test_load_too_high()) ||
3084 (pr->results_found > 5 + 2 * pr->priority) ) )
3087 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3088 "Load too high, done with request\n");
3090 GNUNET_STATISTICS_update (stats,
3091 gettext_noop ("# processing result set cut short due to load"),
3094 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
3097 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3102 * We've received a request with the specified priority. Bound it
3103 * according to how much we trust the given peer.
3105 * @param prio_in requested priority
3106 * @param cp the peer making the request
3107 * @return effective priority
3110 bound_priority (uint32_t prio_in,
3111 struct ConnectedPeer *cp)
3113 #define N ((double)128.0)
3118 ld = test_load_too_high ();
3119 if (ld == GNUNET_SYSERR)
3120 return 0; /* excess resources */
3121 ret = change_host_trust (cp, prio_in);
3124 if (ret > current_priorities + N)
3125 rret = current_priorities + N;
3129 = (current_priorities * (N-1) + rret)/N;
3137 * Iterator over entries in the 'query_request_map' that
3138 * tries to see if we have the same request pending from
3139 * the same peer already.
3141 * @param cls closure (our 'struct CheckDuplicateRequestClosure')
3142 * @param key current key code (query, ignored, must match)
3143 * @param value value in the hash map (a 'struct PendingRequest'
3144 * that already exists)
3145 * @return GNUNET_YES if we should continue to
3146 * iterate (no match yet)
3147 * GNUNET_NO if not (match found).
3150 check_duplicate_request_peer (void *cls,
3151 const GNUNET_HashCode * key,
3154 struct CheckDuplicateRequestClosure *cdc = cls;
3155 struct PendingRequest *have = value;
3157 if (cdc->pr->target_pid == have->target_pid)
3167 * Handle P2P "GET" request.
3169 * @param cls closure, always NULL
3170 * @param other the other peer involved (sender or receiver, NULL
3171 * for loopback messages where we are both sender and receiver)
3172 * @param message the actual message
3173 * @param latency reported latency of the connection with 'other'
3174 * @param distance reported distance (DV) to 'other'
3175 * @return GNUNET_OK to keep the connection open,
3176 * GNUNET_SYSERR to close it (signal serious error)
3179 handle_p2p_get (void *cls,
3180 const struct GNUNET_PeerIdentity *other,
3181 const struct GNUNET_MessageHeader *message,
3182 struct GNUNET_TIME_Relative latency,
3185 struct PendingRequest *pr;
3186 struct ConnectedPeer *cp;
3187 struct ConnectedPeer *cps;
3188 struct CheckDuplicateRequestClosure cdc;
3189 struct GNUNET_TIME_Relative timeout;
3191 const struct GetMessage *gm;
3193 const GNUNET_HashCode *opt;
3196 uint32_t ttl_decrement;
3197 enum GNUNET_BLOCK_Type type;
3201 msize = ntohs(message->size);
3202 if (msize < sizeof (struct GetMessage))
3204 GNUNET_break_op (0);
3205 return GNUNET_SYSERR;
3207 gm = (const struct GetMessage*) message;
3208 type = ntohl (gm->type);
3211 case GNUNET_BLOCK_TYPE_ANY:
3212 case GNUNET_BLOCK_TYPE_DBLOCK:
3213 case GNUNET_BLOCK_TYPE_IBLOCK:
3214 case GNUNET_BLOCK_TYPE_KBLOCK:
3215 case GNUNET_BLOCK_TYPE_SBLOCK:
3218 GNUNET_break_op (0);
3219 return GNUNET_SYSERR;
3221 bm = ntohl (gm->hash_bitmap);
3229 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
3231 GNUNET_break_op (0);
3232 return GNUNET_SYSERR;
3234 opt = (const GNUNET_HashCode*) &gm[1];
3235 bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
3236 bm = ntohl (gm->hash_bitmap);
3237 if ( (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)) &&
3238 (type != GNUNET_BLOCK_TYPE_SBLOCK) )
3240 GNUNET_break_op (0);
3241 return GNUNET_SYSERR;
3244 cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3245 &other->hashPubKey);
3248 /* peer must have just disconnected */
3249 GNUNET_STATISTICS_update (stats,
3250 gettext_noop ("# requests dropped due to initiator not being connected"),
3253 return GNUNET_SYSERR;
3255 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
3256 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3263 if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
3264 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3265 "Failed to find RETURN-TO peer `%4s' in connection set. Dropping query.\n",
3266 GNUNET_i2s ((const struct GNUNET_PeerIdentity*) &opt[bits-1]));
3269 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3270 "Failed to find peer `%4s' in connection set. Dropping query.\n",
3271 GNUNET_i2s (other));
3273 GNUNET_STATISTICS_update (stats,
3274 gettext_noop ("# requests dropped due to missing reverse route"),
3277 /* FIXME: try connect? */
3280 /* note that we can really only check load here since otherwise
3281 peers could find out that we are overloaded by not being
3282 disconnected after sending us a malformed query... */
3284 /* FIXME: query priority should play
3285 a major role here! */
3286 ld = test_load_too_high ();
3287 if (GNUNET_YES == ld)
3290 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3291 "Dropping query from `%s', this peer is too busy.\n",
3292 GNUNET_i2s (other));
3294 GNUNET_STATISTICS_update (stats,
3295 gettext_noop ("# requests dropped due to high load"),
3300 /* FIXME: if ld == GNUNET_NO, forward
3301 instead of indirecting! */
3304 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3305 "Received request for `%s' of type %u from peer `%4s' with flags %u\n",
3306 GNUNET_h2s (&gm->query),
3307 (unsigned int) type,
3311 have_ns = (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE));
3312 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
3313 (have_ns ? sizeof(GNUNET_HashCode) : 0));
3316 pr->namespace = (GNUNET_HashCode*) &pr[1];
3317 memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
3320 pr->mingle = ntohl (gm->filter_mutator);
3321 if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
3322 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
3324 pr->anonymity_level = 1;
3325 pr->priority = bound_priority (ntohl (gm->priority), cps);
3326 pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
3327 pr->query = gm->query;
3328 /* decrement ttl (always) */
3329 ttl_decrement = 2 * TTL_DECREMENT +
3330 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3332 if ( (pr->ttl < 0) &&
3333 (((int32_t)(pr->ttl - ttl_decrement)) > 0) )
3336 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3337 "Dropping query from `%s' due to TTL underflow (%d - %u).\n",
3342 GNUNET_STATISTICS_update (stats,
3343 gettext_noop ("# requests dropped due TTL underflow"),
3346 /* integer underflow => drop (should be very rare)! */
3350 pr->ttl -= ttl_decrement;
3351 pr->start_time = GNUNET_TIME_absolute_get ();
3353 /* get bloom filter */
3356 pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
3359 pr->bf_size = bfsize;
3364 GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
3366 &check_duplicate_request_peer,
3368 if (cdc.have != NULL)
3370 if (cdc.have->start_time.value + cdc.have->ttl >=
3371 pr->start_time.value + pr->ttl)
3373 /* existing request has higher TTL, drop new one! */
3374 cdc.have->priority += pr->priority;
3375 destroy_pending_request (pr);
3377 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3378 "Have existing request with higher TTL, dropping new request.\n",
3379 GNUNET_i2s (other));
3381 GNUNET_STATISTICS_update (stats,
3382 gettext_noop ("# requests dropped due to higher-TTL request"),
3389 /* existing request has lower TTL, drop old one! */
3390 pr->priority += cdc.have->priority;
3391 /* Possible optimization: if we have applicable pending
3392 replies in 'cdc.have', we might want to move those over
3393 (this is a really rare special-case, so it is not clear
3394 that this would be worth it) */
3395 destroy_pending_request (cdc.have);
3396 /* keep processing 'pr'! */
3401 GNUNET_break (GNUNET_OK ==
3402 GNUNET_CONTAINER_multihashmap_put (query_request_map,
3405 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
3406 GNUNET_break (GNUNET_OK ==
3407 GNUNET_CONTAINER_multihashmap_put (peer_request_map,
3410 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
3412 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
3414 pr->start_time.value + pr->ttl);
3416 GNUNET_STATISTICS_update (stats,
3417 gettext_noop ("# P2P searches received"),
3420 GNUNET_STATISTICS_update (stats,
3421 gettext_noop ("# P2P searches active"),
3425 /* calculate change in traffic preference */
3426 cps->inc_preference += pr->priority * 1000 + QUERY_BANDWIDTH_VALUE;
3427 /* process locally */
3428 if (type == GNUNET_BLOCK_TYPE_DBLOCK)
3429 type = GNUNET_BLOCK_TYPE_ANY; /* to get on-demand as well */
3430 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
3431 (pr->priority + 1));
3432 pr->qe = GNUNET_DATASTORE_get (dsh,
3436 MAX_DATASTORE_QUEUE,
3438 &process_local_reply,
3441 /* Are multiple results possible? If so, start processing remotely now! */
3444 case GNUNET_BLOCK_TYPE_DBLOCK:
3445 case GNUNET_BLOCK_TYPE_IBLOCK:
3446 /* only one result, wait for datastore */
3449 if (pr->task == GNUNET_SCHEDULER_NO_TASK)
3450 pr->task = GNUNET_SCHEDULER_add_now (sched,
3451 &forward_request_task,
3455 /* make sure we don't track too many requests */
3456 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
3458 pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
3459 GNUNET_assert (pr != NULL);
3460 destroy_pending_request (pr);
3466 /* **************************** CS GET Handling ************************ */
3470 * Handle START_SEARCH-message (search request from client).
3472 * @param cls closure
3473 * @param client identification of the client
3474 * @param message the actual message
3477 handle_start_search (void *cls,
3478 struct GNUNET_SERVER_Client *client,
3479 const struct GNUNET_MessageHeader *message)
3481 static GNUNET_HashCode all_zeros;
3482 const struct SearchMessage *sm;
3483 struct ClientList *cl;
3484 struct ClientRequestList *crl;
3485 struct PendingRequest *pr;
3488 enum GNUNET_BLOCK_Type type;
3490 msize = ntohs (message->size);
3491 if ( (msize < sizeof (struct SearchMessage)) ||
3492 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
3495 GNUNET_SERVER_receive_done (client,
3499 GNUNET_STATISTICS_update (stats,
3500 gettext_noop ("# client searches received"),
3503 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
3504 sm = (const struct SearchMessage*) message;
3505 type = ntohl (sm->type);
3507 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3508 "Received request for `%s' of type %u from local client\n",
3509 GNUNET_h2s (&sm->query),
3510 (unsigned int) type);
3514 case GNUNET_BLOCK_TYPE_ANY:
3515 case GNUNET_BLOCK_TYPE_DBLOCK:
3516 case GNUNET_BLOCK_TYPE_IBLOCK:
3517 case GNUNET_BLOCK_TYPE_KBLOCK:
3518 case GNUNET_BLOCK_TYPE_SBLOCK:
3519 case GNUNET_BLOCK_TYPE_NBLOCK:
3523 GNUNET_SERVER_receive_done (client,
3529 while ( (cl != NULL) &&
3530 (cl->client != client) )
3534 cl = GNUNET_malloc (sizeof (struct ClientList));
3535 cl->client = client;
3536 GNUNET_SERVER_client_keep (client);
3537 cl->next = client_list;
3540 /* detect duplicate KBLOCK requests */
3541 if ( (type == GNUNET_BLOCK_TYPE_KBLOCK) ||
3542 (type == GNUNET_BLOCK_TYPE_NBLOCK) ||
3543 (type == GNUNET_BLOCK_TYPE_ANY) )
3546 while ( (crl != NULL) &&
3547 ( (0 != memcmp (&crl->req->query,
3549 sizeof (GNUNET_HashCode))) ||
3550 (crl->req->type != type) ) )
3555 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3556 "Have existing request, merging content-seen lists.\n");
3559 /* Duplicate request (used to send long list of
3560 known/blocked results); merge 'pr->replies_seen'
3561 and update bloom filter */
3562 GNUNET_array_grow (pr->replies_seen,
3563 pr->replies_seen_size,
3564 pr->replies_seen_off + sc);
3565 memcpy (&pr->replies_seen[pr->replies_seen_off],
3567 sc * sizeof (GNUNET_HashCode));
3568 pr->replies_seen_off += sc;
3569 refresh_bloomfilter (pr);
3570 GNUNET_STATISTICS_update (stats,
3571 gettext_noop ("# client searches updated (merged content seen list)"),
3574 GNUNET_SERVER_receive_done (client,
3579 GNUNET_STATISTICS_update (stats,
3580 gettext_noop ("# client searches active"),
3583 pr = GNUNET_malloc (sizeof (struct PendingRequest) +
3584 ((type == GNUNET_BLOCK_TYPE_SBLOCK) ? sizeof(GNUNET_HashCode) : 0));
3585 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
3586 memset (crl, 0, sizeof (struct ClientRequestList));
3587 crl->client_list = cl;
3588 GNUNET_CONTAINER_DLL_insert (cl->rl_head,
3593 pr->client_request_list = crl;
3594 GNUNET_array_grow (pr->replies_seen,
3595 pr->replies_seen_size,
3597 memcpy (pr->replies_seen,
3599 sc * sizeof (GNUNET_HashCode));
3600 pr->replies_seen_off = sc;
3601 pr->anonymity_level = ntohl (sm->anonymity_level);
3602 refresh_bloomfilter (pr);
3603 pr->query = sm->query;
3604 if (0 == (1 & ntohl (sm->options)))
3605 pr->local_only = GNUNET_NO;
3607 pr->local_only = GNUNET_YES;
3610 case GNUNET_BLOCK_TYPE_DBLOCK:
3611 case GNUNET_BLOCK_TYPE_IBLOCK:
3612 if (0 != memcmp (&sm->target,
3614 sizeof (GNUNET_HashCode)))
3615 pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
3617 case GNUNET_BLOCK_TYPE_SBLOCK:
3618 pr->namespace = (GNUNET_HashCode*) &pr[1];
3619 memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
3624 GNUNET_break (GNUNET_OK ==
3625 GNUNET_CONTAINER_multihashmap_put (query_request_map,
3628 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
3629 if (type == GNUNET_BLOCK_TYPE_DBLOCK)
3630 type = GNUNET_BLOCK_TYPE_ANY; /* get on-demand blocks too! */
3631 pr->qe = GNUNET_DATASTORE_get (dsh,
3635 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
3636 &process_local_reply,
3641 /* **************************** Startup ************************ */
3644 * Process fs requests.
3646 * @param s scheduler to use
3647 * @param server the initialized server
3648 * @param c configuration to use
3651 main_init (struct GNUNET_SCHEDULER_Handle *s,
3652 struct GNUNET_SERVER_Handle *server,
3653 const struct GNUNET_CONFIGURATION_Handle *c)
3655 static const struct GNUNET_CORE_MessageHandler p2p_handlers[] =
3658 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
3660 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
3663 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
3664 {&GNUNET_FS_handle_index_start, NULL,
3665 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
3666 {&GNUNET_FS_handle_index_list_get, NULL,
3667 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
3668 {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
3669 sizeof (struct UnindexMessage) },
3670 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
3674 unsigned long long enc = 128;
3678 stats = GNUNET_STATISTICS_create (sched, "fs", cfg);
3679 min_migration_delay = GNUNET_TIME_UNIT_SECONDS;
3681 GNUNET_CONFIGURATION_get_value_number (cfg,
3683 "MAX_PENDING_REQUESTS",
3684 &max_pending_requests)) ||
3686 GNUNET_CONFIGURATION_get_value_number (cfg,
3688 "EXPECTED_NEIGHBOUR_COUNT",
3691 GNUNET_CONFIGURATION_get_value_time (cfg,
3693 "MIN_MIGRATION_DELAY",
3694 &min_migration_delay)) )
3696 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3697 _("Configuration fails to specify certain parameters, assuming default values."));
3699 connected_peers = GNUNET_CONTAINER_multihashmap_create (enc);
3700 query_request_map = GNUNET_CONTAINER_multihashmap_create (max_pending_requests);
3701 peer_request_map = GNUNET_CONTAINER_multihashmap_create (enc);
3702 requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
3703 core = GNUNET_CORE_connect (sched,
3705 GNUNET_TIME_UNIT_FOREVER_REL,
3708 &peer_connect_handler,
3709 &peer_disconnect_handler,
3716 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3717 _("Failed to connect to `%s' service.\n"),
3719 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
3720 connected_peers = NULL;
3721 GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
3722 query_request_map = NULL;
3723 GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
3724 requests_by_expiration_heap = NULL;
3725 GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
3726 peer_request_map = NULL;
3729 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
3732 return GNUNET_SYSERR;
3734 /* FIXME: distinguish between sending and storing in options? */
3735 if (active_migration)
3737 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3738 _("Content migration is enabled, will start to gather data\n"));
3739 consider_migration_gathering ();
3741 GNUNET_SERVER_disconnect_notify (server,
3742 &handle_client_disconnect,
3744 GNUNET_assert (GNUNET_OK ==
3745 GNUNET_CONFIGURATION_get_value_filename (cfg,
3749 GNUNET_DISK_directory_create (trustDirectory);
3750 GNUNET_SCHEDULER_add_with_priority (sched,
3751 GNUNET_SCHEDULER_PRIORITY_HIGH,
3752 &cron_flush_trust, NULL);
3755 GNUNET_SERVER_add_handlers (server, handlers);
3756 GNUNET_SCHEDULER_add_delayed (sched,
3757 GNUNET_TIME_UNIT_FOREVER_REL,
3765 * Process fs requests.
3767 * @param cls closure
3768 * @param sched scheduler to use
3769 * @param server the initialized server
3770 * @param cfg configuration to use
3774 struct GNUNET_SCHEDULER_Handle *sched,
3775 struct GNUNET_SERVER_Handle *server,
3776 const struct GNUNET_CONFIGURATION_Handle *cfg)
3778 active_migration = GNUNET_CONFIGURATION_get_value_yesno (cfg,
3781 dsh = GNUNET_DATASTORE_connect (cfg,
3785 GNUNET_SCHEDULER_shutdown (sched);
3788 if ( (GNUNET_OK != GNUNET_FS_indexing_init (sched, cfg, dsh)) ||
3789 (GNUNET_OK != main_init (sched, server, cfg)) )
3791 GNUNET_SCHEDULER_shutdown (sched);
3792 GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
3800 * The main function for the fs service.
3802 * @param argc number of arguments from the command line
3803 * @param argv command line arguments
3804 * @return 0 ok, 1 on error
3807 main (int argc, char *const *argv)
3809 return (GNUNET_OK ==
3810 GNUNET_SERVICE_run (argc,
3813 GNUNET_SERVICE_OPTION_NONE,
3814 &run, NULL)) ? 0 : 1;
3817 /* end of gnunet-service-fs.c */