-static struct GNUNET_LOAD_Value *datastore_get_load;
-
-/**
- * Datastore 'PUT' load tracking.
- */
-static struct GNUNET_LOAD_Value *datastore_put_load;
-
-/**
- * How long do requests typically stay in the routing table?
- */
-static struct GNUNET_LOAD_Value *rt_entry_lifetime;
-
-/**
- * We've just now completed a datastore request. Update our
- * datastore load calculations.
- *
- * @param start time when the datastore request was issued
- */
-static void
-update_datastore_delays (struct GNUNET_TIME_Absolute start)
-{
- struct GNUNET_TIME_Relative delay;
-
- delay = GNUNET_TIME_absolute_get_duration (start);
- GNUNET_LOAD_update (datastore_get_load,
- delay.rel_value);
-}
-
-
-/**
- * Get the filename under which we would store the GNUNET_HELLO_Message
- * for the given host and protocol.
- * @return filename of the form DIRECTORY/HOSTID
- */
-static char *
-get_trust_filename (const struct GNUNET_PeerIdentity *id)
-{
- struct GNUNET_CRYPTO_HashAsciiEncoded fil;
- char *fn;
-
- GNUNET_CRYPTO_hash_to_enc (&id->hashPubKey, &fil);
- GNUNET_asprintf (&fn, "%s%s%s", trustDirectory, DIR_SEPARATOR_STR, &fil);
- return fn;
-}
-
-
-
-/**
- * Transmit messages by copying it to the target buffer
- * "buf". "buf" will be NULL and "size" zero if the socket was closed
- * for writing in the meantime. In that case, do nothing
- * (the disconnect or shutdown handler will take care of the rest).
- * If we were able to transmit messages and there are still more
- * pending, ask core again for further calls to this function.
- *
- * @param cls closure, pointer to the 'struct ConnectedPeer*'
- * @param size number of bytes available in buf
- * @param buf where the callee should write the message
- * @return number of bytes written to buf
- */
-static size_t
-transmit_to_peer (void *cls,
- size_t size, void *buf);
-
-
-/* ******************* clean up functions ************************ */
-
-/**
- * Delete the given migration block.
- *
- * @param mb block to delete
- */
-static void
-delete_migration_block (struct MigrationReadyBlock *mb)
-{
- GNUNET_CONTAINER_DLL_remove (mig_head,
- mig_tail,
- mb);
- GNUNET_PEER_decrement_rcs (mb->target_list,
- MIGRATION_LIST_SIZE);
- mig_size--;
- GNUNET_free (mb);
-}
-
-
-/**
- * Compare the distance of two peers to a key.
- *
- * @param key key
- * @param p1 first peer
- * @param p2 second peer
- * @return GNUNET_YES if P1 is closer to key than P2
- */
-static int
-is_closer (const GNUNET_HashCode *key,
- const struct GNUNET_PeerIdentity *p1,
- const struct GNUNET_PeerIdentity *p2)
-{
- return GNUNET_CRYPTO_hash_xorcmp (&p1->hashPubKey,
- &p2->hashPubKey,
- key);
-}
-
-
-/**
- * Consider migrating content to a given peer.
- *
- * @param cls 'struct MigrationReadyBlock*' to select
- * targets for (or NULL for none)
- * @param key ID of the peer
- * @param value 'struct ConnectedPeer' of the peer
- * @return GNUNET_YES (always continue iteration)
- */
-static int
-consider_migration (void *cls,
- const GNUNET_HashCode *key,
- void *value)
-{
- struct MigrationReadyBlock *mb = cls;
- struct ConnectedPeer *cp = value;
- struct MigrationReadyBlock *pos;
- struct GNUNET_PeerIdentity cppid;
- struct GNUNET_PeerIdentity otherpid;
- struct GNUNET_PeerIdentity worstpid;
- size_t msize;
- unsigned int i;
- unsigned int repl;
-
- /* consider 'cp' as a migration target for mb */
- if (GNUNET_TIME_absolute_get_remaining (cp->migration_blocked).rel_value > 0)
- return GNUNET_YES; /* peer has requested no migration! */
- if (mb != NULL)
- {
- GNUNET_PEER_resolve (cp->pid,
- &cppid);
- repl = MIGRATION_LIST_SIZE;
- for (i=0;i<MIGRATION_LIST_SIZE;i++)
- {
- if (mb->target_list[i] == 0)
- {
- mb->target_list[i] = cp->pid;
- GNUNET_PEER_change_rc (mb->target_list[i], 1);
- repl = MIGRATION_LIST_SIZE;
- break;
- }
- GNUNET_PEER_resolve (mb->target_list[i],
- &otherpid);
- if ( (repl == MIGRATION_LIST_SIZE) &&
- is_closer (&mb->query,
- &cppid,
- &otherpid))
- {
- repl = i;
- worstpid = otherpid;
- }
- else if ( (repl != MIGRATION_LIST_SIZE) &&
- (is_closer (&mb->query,
- &worstpid,
- &otherpid) ) )
- {
- repl = i;
- worstpid = otherpid;
- }
- }
- if (repl != MIGRATION_LIST_SIZE)
- {
- GNUNET_PEER_change_rc (mb->target_list[repl], -1);
- mb->target_list[repl] = cp->pid;
- GNUNET_PEER_change_rc (mb->target_list[repl], 1);
- }
- }
-
- /* consider scheduling transmission to cp for content migration */
- if (cp->cth != NULL)
- return GNUNET_YES;
- msize = 0;
- pos = mig_head;
- while (pos != NULL)
- {
- for (i=0;i<MIGRATION_LIST_SIZE;i++)
- {
- if (cp->pid == pos->target_list[i])
- {
- if (msize == 0)
- msize = pos->size;
- else
- msize = GNUNET_MIN (msize,
- pos->size);
- break;
- }
- }
- pos = pos->next;
- }
- if (msize == 0)
- return GNUNET_YES; /* no content available */
-#if DEBUG_FS
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "Trying to migrate at least %u bytes to peer `%s'\n",
- msize,
- GNUNET_h2s (key));
-#endif
- if (cp->delayed_transmission_request_task != GNUNET_SCHEDULER_NO_TASK)
- {
- GNUNET_SCHEDULER_cancel (cp->delayed_transmission_request_task);
- cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
- }
- cp->cth
- = GNUNET_CORE_notify_transmit_ready (core,
- 0, GNUNET_TIME_UNIT_FOREVER_REL,
- (const struct GNUNET_PeerIdentity*) key,
- msize + sizeof (struct PutMessage),
- &transmit_to_peer,
- cp);
- return GNUNET_YES;
-}
-
-
-/**
- * Task that is run periodically to obtain blocks for content
- * migration
- *
- * @param cls unused
- * @param tc scheduler context (also unused)
- */
-static void
-gather_migration_blocks (void *cls,
- const struct GNUNET_SCHEDULER_TaskContext *tc);
-
-
-
-
-/**
- * Task that is run periodically to obtain blocks for DHT PUTs.
- *
- * @param cls type of blocks to gather
- * @param tc scheduler context (unused)
- */
-static void
-gather_dht_put_blocks (void *cls,
- const struct GNUNET_SCHEDULER_TaskContext *tc);
-
-
-/**
- * If the migration task is not currently running, consider
- * (re)scheduling it with the appropriate delay.
- */
-static void
-consider_migration_gathering ()
-{
- struct GNUNET_TIME_Relative delay;
-
- if (dsh == NULL)
- return;
- if (mig_qe != NULL)
- return;
- if (mig_task != GNUNET_SCHEDULER_NO_TASK)
- return;
- delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
- mig_size);
- delay = GNUNET_TIME_relative_divide (delay,
- MAX_MIGRATION_QUEUE);
- delay = GNUNET_TIME_relative_max (delay,
- min_migration_delay);
- mig_task = GNUNET_SCHEDULER_add_delayed (delay,
- &gather_migration_blocks,
- NULL);
-}
-
-
-/**
- * If the DHT PUT gathering task is not currently running, consider
- * (re)scheduling it with the appropriate delay.
- */
-static void
-consider_dht_put_gathering (void *cls)
-{
- struct GNUNET_TIME_Relative delay;
-
- if (dsh == NULL)
- return;
- if (dht_qe != NULL)
- return;
- if (dht_task != GNUNET_SCHEDULER_NO_TASK)
- return;
- if (zero_anonymity_count_estimate > 0)
- {
- delay = GNUNET_TIME_relative_divide (GNUNET_DHT_DEFAULT_REPUBLISH_FREQUENCY,
- zero_anonymity_count_estimate);
- delay = GNUNET_TIME_relative_min (delay,
- MAX_DHT_PUT_FREQ);
- }
- else
- {
- /* if we have NO zero-anonymity content yet, wait 5 minutes for some to
- (hopefully) appear */
- delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5);
- }
- dht_task = GNUNET_SCHEDULER_add_delayed (delay,
- &gather_dht_put_blocks,
- cls);
-}
-
-
-/**
- * Process content offered for migration.
- *
- * @param cls closure
- * @param key key for the content
- * @param size number of bytes in data
- * @param data content stored
- * @param type type of the content
- * @param priority priority of the content
- * @param anonymity anonymity-level for the content
- * @param expiration expiration time for the content
- * @param uid unique identifier for the datum;
- * maybe 0 if no unique identifier is available
- */
-static void
-process_migration_content (void *cls,
- const GNUNET_HashCode * key,
- size_t size,
- const void *data,
- enum GNUNET_BLOCK_Type type,
- uint32_t priority,
- uint32_t anonymity,
- struct GNUNET_TIME_Absolute
- expiration, uint64_t uid)
-{
- struct MigrationReadyBlock *mb;
-
- if (key == NULL)
- {
- mig_qe = NULL;
- if (mig_size < MAX_MIGRATION_QUEUE)
- consider_migration_gathering ();
- return;
- }
- if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
- {
- if (GNUNET_OK !=
- GNUNET_FS_handle_on_demand_block (key, size, data,
- type, priority, anonymity,
- expiration, uid,
- &process_migration_content,
- NULL))
- {
- GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
- }
- return;
- }
-#if DEBUG_FS
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "Retrieved block `%s' of type %u for migration\n",
- GNUNET_h2s (key),
- type);
-#endif
- mb = GNUNET_malloc (sizeof (struct MigrationReadyBlock) + size);
- mb->query = *key;
- mb->expiration = expiration;
- mb->size = size;
- mb->type = type;
- memcpy (&mb[1], data, size);
- GNUNET_CONTAINER_DLL_insert_after (mig_head,
- mig_tail,
- mig_tail,
- mb);
- mig_size++;
- GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
- &consider_migration,
- mb);
- GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
-}
-
-
-/**
- * Function called upon completion of the DHT PUT operation.
- */
-static void
-dht_put_continuation (void *cls,
- const struct GNUNET_SCHEDULER_TaskContext *tc)
-{
- GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
-}
-
-
-/**
- * Store content in DHT.
- *
- * @param cls closure
- * @param key key for the content
- * @param size number of bytes in data
- * @param data content stored
- * @param type type of the content
- * @param priority priority of the content
- * @param anonymity anonymity-level for the content
- * @param expiration expiration time for the content
- * @param uid unique identifier for the datum;
- * maybe 0 if no unique identifier is available
- */
-static void
-process_dht_put_content (void *cls,
- const GNUNET_HashCode * key,
- size_t size,
- const void *data,
- enum GNUNET_BLOCK_Type type,
- uint32_t priority,
- uint32_t anonymity,
- struct GNUNET_TIME_Absolute
- expiration, uint64_t uid)
-{
- static unsigned int counter;
- static GNUNET_HashCode last_vhash;
- static GNUNET_HashCode vhash;
-
- if (key == NULL)
- {
- dht_qe = NULL;
- consider_dht_put_gathering (cls);
- return;
- }
- /* slightly funky code to estimate the total number of values with zero
- anonymity from the maximum observed length of a monotonically increasing
- sequence of hashes over the contents */
- GNUNET_CRYPTO_hash (data, size, &vhash);
- if (GNUNET_CRYPTO_hash_cmp (&vhash, &last_vhash) <= 0)
- {
- if (zero_anonymity_count_estimate > 0)
- zero_anonymity_count_estimate /= 2;
- counter = 0;
- }
- last_vhash = vhash;
- if (counter < 31)
- counter++;
- if (zero_anonymity_count_estimate < (1 << counter))
- zero_anonymity_count_estimate = (1 << counter);
-#if DEBUG_FS
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "Retrieved block `%s' of type %u for DHT PUT\n",
- GNUNET_h2s (key),
- type);
-#endif
- GNUNET_DHT_put (dht_handle,
- key,
- DEFAULT_PUT_REPLICATION,
- GNUNET_DHT_RO_NONE,
- type,
- size,
- data,
- expiration,
- GNUNET_TIME_UNIT_FOREVER_REL,
- &dht_put_continuation,
- cls);
-}
-
-
-/**
- * Task that is run periodically to obtain blocks for content
- * migration
- *
- * @param cls unused
- * @param tc scheduler context (also unused)
- */
-static void
-gather_migration_blocks (void *cls,
- const struct GNUNET_SCHEDULER_TaskContext *tc)
-{
- mig_task = GNUNET_SCHEDULER_NO_TASK;
- if (dsh != NULL)
- {
- mig_qe = GNUNET_DATASTORE_get_random (dsh, 0, UINT_MAX,
- GNUNET_TIME_UNIT_FOREVER_REL,
- &process_migration_content, NULL);
- GNUNET_assert (mig_qe != NULL);
- }
-}
-
-
-/**
- * Task that is run periodically to obtain blocks for DHT PUTs.
- *
- * @param cls type of blocks to gather
- * @param tc scheduler context (unused)
- */
-static void
-gather_dht_put_blocks (void *cls,
- const struct GNUNET_SCHEDULER_TaskContext *tc)
-{
- dht_task = GNUNET_SCHEDULER_NO_TASK;
- if (dsh != NULL)
- {
- if (dht_put_type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
- dht_put_type = GNUNET_BLOCK_TYPE_FS_KBLOCK;
- dht_qe = GNUNET_DATASTORE_get_zero_anonymity (dsh, 0, UINT_MAX,
- GNUNET_TIME_UNIT_FOREVER_REL,
- dht_put_type++,
- &process_dht_put_content, NULL);
- GNUNET_assert (dht_qe != NULL);
- }
-}
-
-
-/**
- * We're done with a particular message list entry.
- * Free all associated resources.
- *
- * @param pml entry to destroy
- */
-static void
-destroy_pending_message_list_entry (struct PendingMessageList *pml)
-{
- GNUNET_CONTAINER_DLL_remove (pml->req->pending_head,
- pml->req->pending_tail,
- pml);
- GNUNET_CONTAINER_DLL_remove (pml->target->pending_messages_head,
- pml->target->pending_messages_tail,
- pml->pm);
- pml->target->pending_requests--;
- GNUNET_free (pml->pm);
- GNUNET_free (pml);
-}
-
-
-/**
- * Destroy the given pending message (and call the respective
- * continuation).
- *
- * @param pm message to destroy
- * @param tpid id of peer that the message was delivered to, or 0 for none
- */
-static void
-destroy_pending_message (struct PendingMessage *pm,
- GNUNET_PEER_Id tpid)
-{
- struct PendingMessageList *pml = pm->pml;
- TransmissionContinuation cont;
- void *cont_cls;
-
- cont = pm->cont;
- cont_cls = pm->cont_cls;
- if (pml != NULL)
- {
- GNUNET_assert (pml->pm == pm);
- GNUNET_assert ( (tpid == 0) || (tpid == pml->target->pid) );
- destroy_pending_message_list_entry (pml);
- }
- else
- {
- GNUNET_free (pm);
- }
- if (cont != NULL)
- cont (cont_cls, tpid);
-}
-
-
-/**
- * We're done processing a particular request.
- * Free all associated resources.
- *
- * @param pr request to destroy
- */
-static void
-destroy_pending_request (struct PendingRequest *pr)
-{
- struct GNUNET_PeerIdentity pid;
- unsigned int i;
-
- if (pr->hnode != NULL)
- {
- GNUNET_CONTAINER_heap_remove_node (requests_by_expiration_heap,
- pr->hnode);
- pr->hnode = NULL;
- }
- if (NULL == pr->client_request_list)
- {
- GNUNET_STATISTICS_update (stats,
- gettext_noop ("# P2P searches active"),
- -1,
- GNUNET_NO);
- }
- else
- {
- GNUNET_STATISTICS_update (stats,
- gettext_noop ("# client searches active"),
- -1,
- GNUNET_NO);
- }
- if (GNUNET_YES ==
- GNUNET_CONTAINER_multihashmap_remove (query_request_map,
- &pr->query,
- pr))
- {
- GNUNET_LOAD_update (rt_entry_lifetime,
- GNUNET_TIME_absolute_get_duration (pr->start_time).rel_value);
- }
- if (pr->qe != NULL)
- {
- GNUNET_DATASTORE_cancel (pr->qe);
- pr->qe = NULL;
- }
- if (pr->dht_get != NULL)
- {
- GNUNET_DHT_get_stop (pr->dht_get);
- pr->dht_get = NULL;
- }
- if (pr->client_request_list != NULL)
- {
- GNUNET_CONTAINER_DLL_remove (pr->client_request_list->client_list->rl_head,
- pr->client_request_list->client_list->rl_tail,
- pr->client_request_list);
- GNUNET_free (pr->client_request_list);
- pr->client_request_list = NULL;
- }
- if (pr->cp != NULL)
- {
- GNUNET_PEER_resolve (pr->cp->pid,
- &pid);
- (void) GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
- &pid.hashPubKey,
- pr);
- pr->cp = NULL;
- }
- if (pr->bf != NULL)
- {
- GNUNET_CONTAINER_bloomfilter_free (pr->bf);
- pr->bf = NULL;
- }
- if (pr->pirc != NULL)
- {
- GNUNET_CORE_peer_change_preference_cancel (pr->pirc->irc);
- pr->pirc->irc = NULL;
- pr->pirc = NULL;
- }
- if (pr->replies_seen != NULL)
- {
- GNUNET_free (pr->replies_seen);
- pr->replies_seen = NULL;
- }
- if (pr->task != GNUNET_SCHEDULER_NO_TASK)
- {
- GNUNET_SCHEDULER_cancel (pr->task);
- pr->task = GNUNET_SCHEDULER_NO_TASK;
- }
- while (NULL != pr->pending_head)
- destroy_pending_message_list_entry (pr->pending_head);
- GNUNET_PEER_change_rc (pr->target_pid, -1);
- if (pr->used_targets != NULL)
- {
- for (i=0;i<pr->used_targets_off;i++)
- GNUNET_PEER_change_rc (pr->used_targets[i].pid, -1);
- GNUNET_free (pr->used_targets);
- pr->used_targets_off = 0;
- pr->used_targets_size = 0;
- pr->used_targets = NULL;
- }
- GNUNET_free (pr);
-}
-
-
-/**
- * Find latency information in 'atsi'.
- *
- * @param atsi performance data
- * @return connection latency
- */
-static struct GNUNET_TIME_Relative
-get_latency (const struct GNUNET_TRANSPORT_ATS_Information *atsi)
-{
- /* FIXME: extract latency data from 'atsi' */
- return GNUNET_TIME_UNIT_SECONDS;
-}
-
-
-/**
- * Method called whenever a given peer connects.
- *
- * @param cls closure, not used
- * @param peer peer identity this notification is about
- * @param atsi performance information
- */
-static void
-peer_connect_handler (void *cls,
- const struct
- GNUNET_PeerIdentity * peer,
- const struct GNUNET_TRANSPORT_ATS_Information *atsi)
-{
- struct ConnectedPeer *cp;
- struct MigrationReadyBlock *pos;
- char *fn;
- uint32_t trust;
- struct GNUNET_TIME_Relative latency;
-
- latency = get_latency (atsi);
- cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
- &peer->hashPubKey);
- if (NULL != cp)
- {
- GNUNET_break (0);
- return;
- }
- cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
- cp->transmission_delay = GNUNET_LOAD_value_init (latency);
- cp->pid = GNUNET_PEER_intern (peer);
-
- fn = get_trust_filename (peer);
- if ((GNUNET_DISK_file_test (fn) == GNUNET_YES) &&
- (sizeof (trust) == GNUNET_DISK_fn_read (fn, &trust, sizeof (trust))))
- cp->disk_trust = cp->trust = ntohl (trust);
- GNUNET_free (fn);
-
- GNUNET_break (GNUNET_OK ==
- GNUNET_CONTAINER_multihashmap_put (connected_peers,
- &peer->hashPubKey,
- cp,
- GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
-
- pos = mig_head;
- while (NULL != pos)
- {
- (void) consider_migration (pos, &peer->hashPubKey, cp);
- pos = pos->next;
- }
-}
-
-
-/**
- * Method called whenever a given peer has a status change.
- *
- * @param cls closure
- * @param peer peer identity this notification is about
- * @param bandwidth_in available amount of inbound bandwidth
- * @param bandwidth_out available amount of outbound bandwidth
- * @param timeout absolute time when this peer will time out
- * unless we see some further activity from it
- * @param atsi status information
- */
-static void
-peer_status_handler (void *cls,
- const struct
- GNUNET_PeerIdentity * peer,
- struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
- struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
- struct GNUNET_TIME_Absolute timeout,
- const struct GNUNET_TRANSPORT_ATS_Information *atsi)
-{
- struct ConnectedPeer *cp;
- struct GNUNET_TIME_Relative latency;
-
- latency = get_latency (atsi);
- cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
- &peer->hashPubKey);
- if (cp == NULL)
- {
- GNUNET_break (0);
- return;
- }
- GNUNET_LOAD_value_set_decline (cp->transmission_delay,
- latency);
-}
-
-
-
-/**
- * Increase the host credit by a value.
- *
- * @param host which peer to change the trust value on
- * @param value is the int value by which the
- * host credit is to be increased or decreased
- * @returns the actual change in trust (positive or negative)
- */
-static int
-change_host_trust (struct ConnectedPeer *host, int value)
-{
- if (value == 0)
- return 0;
- GNUNET_assert (host != NULL);
- if (value > 0)
- {
- if (host->trust + value < host->trust)
- {
- value = UINT32_MAX - host->trust;
- host->trust = UINT32_MAX;
- }
- else
- host->trust += value;
- }
- else
- {
- if (host->trust < -value)
- {
- value = -host->trust;
- host->trust = 0;
- }
- else
- host->trust += value;
- }
- return value;
-}
-
-
-/**
- * Write host-trust information to a file - flush the buffer entry!
- */
-static int
-flush_trust (void *cls,
- const GNUNET_HashCode *key,
- void *value)
-{
- struct ConnectedPeer *host = value;
- char *fn;
- uint32_t trust;
- struct GNUNET_PeerIdentity pid;
-
- if (host->trust == host->disk_trust)
- return GNUNET_OK; /* unchanged */
- GNUNET_PEER_resolve (host->pid,
- &pid);
- fn = get_trust_filename (&pid);
- if (host->trust == 0)
- {
- if ((0 != UNLINK (fn)) && (errno != ENOENT))
- GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
- GNUNET_ERROR_TYPE_BULK, "unlink", fn);
- }
- else
- {
- trust = htonl (host->trust);
- if (sizeof(uint32_t) == GNUNET_DISK_fn_write (fn, &trust,
- sizeof(uint32_t),
- GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE
- | GNUNET_DISK_PERM_GROUP_READ | GNUNET_DISK_PERM_OTHER_READ))
- host->disk_trust = host->trust;
- }
- GNUNET_free (fn);
- return GNUNET_OK;
-}
-
-/**
- * Call this method periodically to scan data/hosts for new hosts.
- */
-static void
-cron_flush_trust (void *cls,
- const struct GNUNET_SCHEDULER_TaskContext *tc)
-{
-
- if (NULL == connected_peers)
- return;
- GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
- &flush_trust,
- NULL);
- if (NULL == tc)
- return;
- if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
- return;
- GNUNET_SCHEDULER_add_delayed (TRUST_FLUSH_FREQ, &cron_flush_trust, NULL);
-}
-
-
-/**
- * Free (each) request made by the peer.
- *
- * @param cls closure, points to peer that the request belongs to
- * @param key current key code
- * @param value value in the hash map
- * @return GNUNET_YES (we should continue to iterate)
- */
-static int
-destroy_request (void *cls,
- const GNUNET_HashCode * key,
- void *value)
-{
- const struct GNUNET_PeerIdentity * peer = cls;
- struct PendingRequest *pr = value;
-
- GNUNET_break (GNUNET_YES ==
- GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
- &peer->hashPubKey,
- pr));
- destroy_pending_request (pr);
- return GNUNET_YES;
-}
-
-
-/**
- * Method called whenever a peer disconnects.
- *
- * @param cls closure, not used
- * @param peer peer identity this notification is about
- */
-static void
-peer_disconnect_handler (void *cls,
- const struct
- GNUNET_PeerIdentity * peer)
-{
- struct ConnectedPeer *cp;
- struct PendingMessage *pm;
- unsigned int i;
- struct MigrationReadyBlock *pos;
- struct MigrationReadyBlock *next;
-
- GNUNET_CONTAINER_multihashmap_get_multiple (peer_request_map,
- &peer->hashPubKey,
- &destroy_request,
- (void*) peer);
- cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
- &peer->hashPubKey);
- if (cp == NULL)
- return;
- for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
- {
- if (NULL != cp->last_client_replies[i])
- {
- GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
- cp->last_client_replies[i] = NULL;
- }
- }
- GNUNET_break (GNUNET_YES ==
- GNUNET_CONTAINER_multihashmap_remove (connected_peers,
- &peer->hashPubKey,
- cp));
- if (cp->irc != NULL)
- {
- GNUNET_CORE_peer_change_preference_cancel (cp->irc);
- cp->irc = NULL;
- cp->pr->pirc = NULL;
- cp->pr = NULL;
- }
-
- /* remove this peer from migration considerations; schedule
- alternatives */
- next = mig_head;
- while (NULL != (pos = next))
- {
- next = pos->next;
- for (i=0;i<MIGRATION_LIST_SIZE;i++)
- {
- if (pos->target_list[i] == cp->pid)
- {
- GNUNET_PEER_change_rc (pos->target_list[i], -1);
- pos->target_list[i] = 0;
- }
- }
- if (pos->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers))
- {
- delete_migration_block (pos);
- consider_migration_gathering ();
- continue;
- }
- GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
- &consider_migration,
- pos);
- }
- GNUNET_PEER_change_rc (cp->pid, -1);
- GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
- if (NULL != cp->cth)
- {
- GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
- cp->cth = NULL;
- }
- if (cp->delayed_transmission_request_task != GNUNET_SCHEDULER_NO_TASK)
- {
- GNUNET_SCHEDULER_cancel (cp->delayed_transmission_request_task);
- cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
- }
- while (NULL != (pm = cp->pending_messages_head))
- destroy_pending_message (pm, 0 /* delivery failed */);
- GNUNET_LOAD_value_free (cp->transmission_delay);
- GNUNET_break (0 == cp->pending_requests);
- GNUNET_free (cp);
-}
-
-
-/**
- * Iterator over hash map entries that removes all occurences
- * of the given 'client' from the 'last_client_replies' of the
- * given connected peer.
- *
- * @param cls closure, the 'struct GNUNET_SERVER_Client*' to remove
- * @param key current key code (unused)
- * @param value value in the hash map (the 'struct ConnectedPeer*' to change)
- * @return GNUNET_YES (we should continue to iterate)
- */
-static int
-remove_client_from_last_client_replies (void *cls,
- const GNUNET_HashCode * key,
- void *value)
-{
- struct GNUNET_SERVER_Client *client = cls;
- struct ConnectedPeer *cp = value;
- unsigned int i;
-
- for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
- {
- if (cp->last_client_replies[i] == client)
- {
- GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
- cp->last_client_replies[i] = NULL;
- }
- }
- return GNUNET_YES;
-}
-
-
-/**
- * A client disconnected. Remove all of its pending queries.
- *
- * @param cls closure, NULL
- * @param client identification of the client
- */
-static void
-handle_client_disconnect (void *cls,
- struct GNUNET_SERVER_Client
- * client)
-{
- struct ClientList *pos;
- struct ClientList *prev;
- struct ClientRequestList *rcl;
- struct ClientResponseMessage *creply;
-
- if (client == NULL)
- return;
- prev = NULL;
- pos = client_list;
- while ( (NULL != pos) &&
- (pos->client != client) )
- {
- prev = pos;
- pos = pos->next;
- }
- if (pos == NULL)
- return; /* no requests pending for this client */
- while (NULL != (rcl = pos->rl_head))
- {
- GNUNET_log (GNUNET_ERROR_TYPE_INFO,
- "Destroying pending request `%s' on disconnect\n",
- GNUNET_h2s (&rcl->req->query));
- destroy_pending_request (rcl->req);
- }
- if (prev == NULL)
- client_list = pos->next;
- else
- prev->next = pos->next;
- if (pos->th != NULL)
- {
- GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
- pos->th = NULL;
- }
- while (NULL != (creply = pos->res_head))
- {
- GNUNET_CONTAINER_DLL_remove (pos->res_head,
- pos->res_tail,
- creply);
- GNUNET_free (creply);
- }
- GNUNET_SERVER_client_drop (pos->client);
- GNUNET_free (pos);
- GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
- &remove_client_from_last_client_replies,
- client);
-}
-
-
-/**
- * Iterator to free peer entries.
- *
- * @param cls closure, unused
- * @param key current key code
- * @param value value in the hash map (peer entry)
- * @return GNUNET_YES (we should continue to iterate)
- */
-static int
-clean_peer (void *cls,
- const GNUNET_HashCode * key,
- void *value)
-{
- peer_disconnect_handler (NULL, (const struct GNUNET_PeerIdentity*) key);
- return GNUNET_YES;
-}
-
-
-/**
- * Task run during shutdown.
- *
- * @param cls unused
- * @param tc unused
- */
-static void
-shutdown_task (void *cls,
- const struct GNUNET_SCHEDULER_TaskContext *tc)
-{
- if (mig_qe != NULL)
- {
- GNUNET_DATASTORE_cancel (mig_qe);
- mig_qe = NULL;
- }
- if (dht_qe != NULL)
- {
- GNUNET_DATASTORE_cancel (dht_qe);
- dht_qe = NULL;
- }
- if (GNUNET_SCHEDULER_NO_TASK != mig_task)
- {
- GNUNET_SCHEDULER_cancel (mig_task);
- mig_task = GNUNET_SCHEDULER_NO_TASK;
- }
- if (GNUNET_SCHEDULER_NO_TASK != dht_task)
- {
- GNUNET_SCHEDULER_cancel (dht_task);
- dht_task = GNUNET_SCHEDULER_NO_TASK;
- }
- while (client_list != NULL)
- handle_client_disconnect (NULL,
- client_list->client);
- cron_flush_trust (NULL, NULL);
- GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
- &clean_peer,
- NULL);
- GNUNET_break (0 == GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap));
- GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
- requests_by_expiration_heap = 0;
- GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
- connected_peers = NULL;
- GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (query_request_map));
- GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
- query_request_map = NULL;
- GNUNET_LOAD_value_free (rt_entry_lifetime);
- rt_entry_lifetime = NULL;
- GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (peer_request_map));
- GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
- peer_request_map = NULL;
- GNUNET_assert (NULL != core);
- GNUNET_CORE_disconnect (core);
- core = NULL;
- if (stats != NULL)
- {
- GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
- stats = NULL;
- }
- if (dsh != NULL)
- {
- GNUNET_DATASTORE_disconnect (dsh,
- GNUNET_NO);
- dsh = NULL;
- }
- while (mig_head != NULL)
- delete_migration_block (mig_head);
- GNUNET_assert (0 == mig_size);
- GNUNET_DHT_disconnect (dht_handle);
- dht_handle = NULL;
- GNUNET_LOAD_value_free (datastore_get_load);
- datastore_get_load = NULL;
- GNUNET_LOAD_value_free (datastore_put_load);
- datastore_put_load = NULL;
- GNUNET_BLOCK_context_destroy (block_ctx);
- block_ctx = NULL;
- GNUNET_CONFIGURATION_destroy (block_cfg);
- block_cfg = NULL;
- cfg = NULL;
- GNUNET_free_non_null (trustDirectory);
- trustDirectory = NULL;
-}
-
-
-/* ******************* Utility functions ******************** */
-
-
-/**
- * We've had to delay a request for transmission to core, but now
- * we should be ready. Run it.
- *
- * @param cls the 'struct ConnectedPeer' for which a request was delayed
- * @param tc task context (unused)
- */
-static void
-delayed_transmission_request (void *cls,
- const struct GNUNET_SCHEDULER_TaskContext *tc)
-{
- struct ConnectedPeer *cp = cls;
- struct GNUNET_PeerIdentity pid;
- struct PendingMessage *pm;
-
- pm = cp->pending_messages_head;
- cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
- GNUNET_assert (cp->cth == NULL);
- if (pm == NULL)
- return;
- GNUNET_PEER_resolve (cp->pid,
- &pid);
- cp->last_transmission_request_start = GNUNET_TIME_absolute_get ();
- cp->cth = GNUNET_CORE_notify_transmit_ready (core,
- pm->priority,
- GNUNET_CONSTANTS_SERVICE_TIMEOUT,
- &pid,
- pm->msize,
- &transmit_to_peer,
- cp);
-}
-
-
-/**
- * Transmit messages by copying it to the target buffer
- * "buf". "buf" will be NULL and "size" zero if the socket was closed
- * for writing in the meantime. In that case, do nothing
- * (the disconnect or shutdown handler will take care of the rest).
- * If we were able to transmit messages and there are still more
- * pending, ask core again for further calls to this function.
- *
- * @param cls closure, pointer to the 'struct ConnectedPeer*'
- * @param size number of bytes available in buf
- * @param buf where the callee should write the message
- * @return number of bytes written to buf
- */
-static size_t
-transmit_to_peer (void *cls,
- size_t size, void *buf)
-{
- struct ConnectedPeer *cp = cls;
- char *cbuf = buf;
- struct PendingMessage *pm;
- struct PendingMessage *next_pm;
- struct GNUNET_TIME_Absolute now;
- struct GNUNET_TIME_Relative min_delay;
- struct MigrationReadyBlock *mb;
- struct MigrationReadyBlock *next;
- struct PutMessage migm;
- size_t msize;
- unsigned int i;
- struct GNUNET_PeerIdentity pid;
-
- cp->cth = NULL;
- if (NULL == buf)
- {
-#if DEBUG_FS
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "Dropping message, core too busy.\n");
-#endif
- GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
- "Dropping message, core too busy.\n");
- GNUNET_LOAD_update (cp->transmission_delay,
- UINT64_MAX);
-
- if (NULL != (pm = cp->pending_messages_head))
- {
- GNUNET_CONTAINER_DLL_remove (cp->pending_messages_head,
- cp->pending_messages_tail,
- pm);
- cp->pending_requests--;
- destroy_pending_message (pm, 0);
- }
- if (NULL != (pm = cp->pending_messages_head))
- {
- GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == cp->delayed_transmission_request_task);
- min_delay = GNUNET_TIME_absolute_get_remaining (pm->delay_until);
- cp->delayed_transmission_request_task
- = GNUNET_SCHEDULER_add_delayed (min_delay,
- &delayed_transmission_request,
- cp);
- }
- return 0;
- }
- GNUNET_LOAD_update (cp->transmission_delay,
- GNUNET_TIME_absolute_get_duration (cp->last_transmission_request_start).rel_value);
- now = GNUNET_TIME_absolute_get ();
- msize = 0;
- min_delay = GNUNET_TIME_UNIT_FOREVER_REL;
- next_pm = cp->pending_messages_head;
- while ( (NULL != (pm = next_pm) ) &&
- (pm->msize <= size) )
- {
- next_pm = pm->next;
- if (pm->delay_until.abs_value > now.abs_value)
- {
- min_delay = GNUNET_TIME_relative_min (min_delay,
- GNUNET_TIME_absolute_get_remaining (pm->delay_until));
- continue;
- }
- memcpy (&cbuf[msize], &pm[1], pm->msize);
- msize += pm->msize;
- size -= pm->msize;
- if (NULL == pm->pml)
- {
- GNUNET_CONTAINER_DLL_remove (cp->pending_messages_head,
- cp->pending_messages_tail,
- pm);
- cp->pending_requests--;
- }
- destroy_pending_message (pm, cp->pid);
- }
- if (pm != NULL)
- min_delay = GNUNET_TIME_UNIT_ZERO;
- if (NULL != cp->pending_messages_head)
- {
- GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == cp->delayed_transmission_request_task);
- cp->delayed_transmission_request_task
- = GNUNET_SCHEDULER_add_delayed (min_delay,
- &delayed_transmission_request,
- cp);
- }
- if (pm == NULL)
- {
- GNUNET_PEER_resolve (cp->pid,
- &pid);
- next = mig_head;
- while (NULL != (mb = next))
- {
- next = mb->next;
- for (i=0;i<MIGRATION_LIST_SIZE;i++)
- {
- if ( (cp->pid == mb->target_list[i]) &&
- (mb->size + sizeof (migm) <= size) )
- {
- GNUNET_PEER_change_rc (mb->target_list[i], -1);
- mb->target_list[i] = 0;
- mb->used_targets++;
- memset (&migm, 0, sizeof (migm));
- migm.header.size = htons (sizeof (migm) + mb->size);
- migm.header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
- migm.type = htonl (mb->type);
- migm.expiration = GNUNET_TIME_absolute_hton (mb->expiration);
- memcpy (&cbuf[msize], &migm, sizeof (migm));
- msize += sizeof (migm);
- size -= sizeof (migm);
- memcpy (&cbuf[msize], &mb[1], mb->size);
- msize += mb->size;
- size -= mb->size;
-#if DEBUG_FS
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "Pushing migration block `%s' (%u bytes) to `%s'\n",
- GNUNET_h2s (&mb->query),
- (unsigned int) mb->size,
- GNUNET_i2s (&pid));
-#endif
- break;
- }
- else
- {
-#if DEBUG_FS
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "Migration block `%s' (%u bytes) is not on migration list for peer `%s'\n",
- GNUNET_h2s (&mb->query),
- (unsigned int) mb->size,
- GNUNET_i2s (&pid));
-#endif
- }
- }
- if ( (mb->used_targets >= MIGRATION_TARGET_COUNT) ||
- (mb->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers)) )
- {
- delete_migration_block (mb);
- consider_migration_gathering ();
- }
- }
- consider_migration (NULL,
- &pid.hashPubKey,
- cp);
- }
-#if DEBUG_FS
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "Transmitting %u bytes to peer with PID %u\n",
- (unsigned int) msize,
- (unsigned int) cp->pid);
-#endif
- return msize;
-}
-
-
-/**
- * Add a message to the set of pending messages for the given peer.
- *
- * @param cp peer to send message to
- * @param pm message to queue
- * @param pr request on which behalf this message is being queued
- */
-static void
-add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
- struct PendingMessage *pm,
- struct PendingRequest *pr)
-{
- struct PendingMessage *pos;
- struct PendingMessageList *pml;
- struct GNUNET_PeerIdentity pid;
-
- GNUNET_assert (pm->next == NULL);
- GNUNET_assert (pm->pml == NULL);
- if (pr != NULL)
- {
- pml = GNUNET_malloc (sizeof (struct PendingMessageList));
- pml->req = pr;
- pml->target = cp;
- pml->pm = pm;
- pm->pml = pml;
- GNUNET_CONTAINER_DLL_insert (pr->pending_head,
- pr->pending_tail,
- pml);
- }
- pos = cp->pending_messages_head;
- while ( (pos != NULL) &&
- (pm->priority < pos->priority) )
- pos = pos->next;
- GNUNET_CONTAINER_DLL_insert_after (cp->pending_messages_head,
- cp->pending_messages_tail,
- pos,
- pm);
- cp->pending_requests++;
- if (cp->pending_requests > MAX_QUEUE_PER_PEER)
- {
- GNUNET_STATISTICS_update (stats,
- gettext_noop ("# P2P searches discarded (queue length bound)"),
- 1,
- GNUNET_NO);
- destroy_pending_message (cp->pending_messages_tail, 0);
- }
- GNUNET_PEER_resolve (cp->pid, &pid);
- if (NULL != cp->cth)
- {
- GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
- cp->cth = NULL;
- }
- if (cp->delayed_transmission_request_task != GNUNET_SCHEDULER_NO_TASK)
- {
- GNUNET_SCHEDULER_cancel (cp->delayed_transmission_request_task);
- cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
- }
- /* need to schedule transmission */
- cp->last_transmission_request_start = GNUNET_TIME_absolute_get ();
- cp->cth = GNUNET_CORE_notify_transmit_ready (core,
- cp->pending_messages_head->priority,
- MAX_TRANSMIT_DELAY,
- &pid,
- cp->pending_messages_head->msize,
- &transmit_to_peer,
- cp);
- if (cp->cth == NULL)
- {
-#if DEBUG_FS
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "Failed to schedule transmission with core!\n");
-#endif
- GNUNET_STATISTICS_update (stats,
- gettext_noop ("# CORE transmission failures"),
- 1,
- GNUNET_NO);
- }
-}
-
-
-/**
- * Test if the DATABASE (GET) load on this peer is too high
- * to even consider processing the query at
- * all.
- *
- * @return GNUNET_YES if the load is too high to do anything (load high)
- * GNUNET_NO to process normally (load normal)
- * GNUNET_SYSERR to process for free (load low)
- */
-static int
-test_get_load_too_high (uint32_t priority)
-{
- double ld;
-
- ld = GNUNET_LOAD_get_load (datastore_get_load);
- if (ld < 1)
- return GNUNET_SYSERR;
- if (ld <= priority)
- return GNUNET_NO;
- return GNUNET_YES;
-}
-
-
-
-
-/**
- * Test if the DATABASE (PUT) load on this peer is too high
- * to even consider processing the query at
- * all.
- *
- * @return GNUNET_YES if the load is too high to do anything (load high)
- * GNUNET_NO to process normally (load normal or low)
- */
-static int
-test_put_load_too_high (uint32_t priority)
-{
- double ld;
-
- if (GNUNET_LOAD_get_average (datastore_put_load) < 50)
- return GNUNET_NO; /* very fast */
- ld = GNUNET_LOAD_get_load (datastore_put_load);
- if (ld < 2.0 * (1 + priority))
- return GNUNET_NO;
- GNUNET_STATISTICS_update (stats,
- gettext_noop ("# storage requests dropped due to high load"),
- 1,
- GNUNET_NO);
- return GNUNET_YES;
-}
-
-
-/* ******************* Pending Request Refresh Task ******************** */
-
-
-
-/**
- * We use a random delay to make the timing of requests less
- * predictable. This function returns such a random delay. We add a base
- * delay of MAX_CORK_DELAY (1s).
- *
- * FIXME: make schedule dependent on the specifics of the request?
- * Or bandwidth and number of connected peers and load?
- *
- * @return random delay to use for some request, between 1s and 1000+TTL_DECREMENT ms
- */
-static struct GNUNET_TIME_Relative
-get_processing_delay ()
-{
- return
- GNUNET_TIME_relative_add (GNUNET_CONSTANTS_MAX_CORK_DELAY,
- GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
- GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
- TTL_DECREMENT)));
-}
-
-
-/**
- * We're processing a GET request from another peer and have decided
- * to forward it to other peers. This function is called periodically
- * and should forward the request to other peers until we have all
- * possible replies. If we have transmitted the *only* reply to
- * the initiator we should destroy the pending request. If we have
- * many replies in the queue to the initiator, we should delay sending
- * out more queries until the reply queue has shrunk some.
- *
- * @param cls our "struct ProcessGetContext *"
- * @param tc unused
- */
-static void
-forward_request_task (void *cls,
- const struct GNUNET_SCHEDULER_TaskContext *tc);
-
-
-/**
- * Function called after we either failed or succeeded
- * at transmitting a query to a peer.
- *
- * @param cls the requests "struct PendingRequest*"
- * @param tpid ID of receiving peer, 0 on transmission error
- */
-static void
-transmit_query_continuation (void *cls,
- GNUNET_PEER_Id tpid)
-{
- struct PendingRequest *pr = cls;
- unsigned int i;
-
- GNUNET_STATISTICS_update (stats,
- gettext_noop ("# queries scheduled for forwarding"),
- -1,
- GNUNET_NO);
- if (tpid == 0)
- {
-#if DEBUG_FS
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "Transmission of request failed, will try again later.\n");
-#endif
- if (pr->task == GNUNET_SCHEDULER_NO_TASK)
- pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
- &forward_request_task,
- pr);
- return;
- }
-#if DEBUG_FS
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "Transmitted query `%s'\n",
- GNUNET_h2s (&pr->query));
-#endif
- GNUNET_STATISTICS_update (stats,
- gettext_noop ("# queries forwarded"),
- 1,
- GNUNET_NO);
- for (i=0;i<pr->used_targets_off;i++)
- if (pr->used_targets[i].pid == tpid)
- break; /* found match! */
- if (i == pr->used_targets_off)
- {
- /* need to create new entry */
- if (pr->used_targets_off == pr->used_targets_size)
- GNUNET_array_grow (pr->used_targets,
- pr->used_targets_size,
- pr->used_targets_size * 2 + 2);
- GNUNET_PEER_change_rc (tpid, 1);
- pr->used_targets[pr->used_targets_off].pid = tpid;
- pr->used_targets[pr->used_targets_off].num_requests = 0;
- i = pr->used_targets_off++;
- }
- pr->used_targets[i].last_request_time = GNUNET_TIME_absolute_get ();
- pr->used_targets[i].num_requests++;
- if (pr->task == GNUNET_SCHEDULER_NO_TASK)
- pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
- &forward_request_task,
- pr);
-}
-
-
-/**
- * How many bytes should a bloomfilter be if we have already seen
- * entry_count responses? Note that BLOOMFILTER_K gives us the number
- * of bits set per entry. Furthermore, we should not re-size the
- * filter too often (to keep it cheap).
- *
- * Since other peers will also add entries but not resize the filter,
- * we should generally pick a slightly larger size than what the
- * strict math would suggest.
- *
- * @return must be a power of two and smaller or equal to 2^15.
- */
-static size_t
-compute_bloomfilter_size (unsigned int entry_count)
-{
- size_t size;
- unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
- uint16_t max = 1 << 15;
-
- if (entry_count > max)
- return max;
- size = 8;
- while ((size < max) && (size < ideal))
- size *= 2;
- if (size > max)
- return max;
- return size;
-}
-
-
-/**
- * Recalculate our bloom filter for filtering replies. This function
- * will create a new bloom filter from scratch, so it should only be
- * called if we have no bloomfilter at all (and hence can create a
- * fresh one of minimal size without problems) OR if our peer is the
- * initiator (in which case we may resize to larger than mimimum size).
- *
- * @param pr request for which the BF is to be recomputed
- */
-static void
-refresh_bloomfilter (struct PendingRequest *pr)
-{
- unsigned int i;
- size_t nsize;
- GNUNET_HashCode mhash;
-
- nsize = compute_bloomfilter_size (pr->replies_seen_off);
- if (nsize == pr->bf_size)
- return; /* size not changed */
- if (pr->bf != NULL)
- GNUNET_CONTAINER_bloomfilter_free (pr->bf);
- pr->bf_size = nsize;
- pr->mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
- pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
- pr->bf_size,
- BLOOMFILTER_K);
- for (i=0;i<pr->replies_seen_off;i++)
- {
- GNUNET_BLOCK_mingle_hash (&pr->replies_seen[i],
- pr->mingle,
- &mhash);
- GNUNET_CONTAINER_bloomfilter_add (pr->bf, &mhash);
- }
-}
-
-
-/**
- * Function called after we've tried to reserve a certain amount of
- * bandwidth for a reply. Check if we succeeded and if so send our
- * query.
- *
- * @param cls the requests "struct PendingRequest*"
- * @param peer identifies the peer
- * @param bpm_out set to the current bandwidth limit (sending) for this peer
- * @param amount set to the amount that was actually reserved or unreserved
- * @param preference current traffic preference for the given peer
- */
-static void
-target_reservation_cb (void *cls,
- const struct
- GNUNET_PeerIdentity * peer,
- struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
- int amount,
- uint64_t preference)
-{
- struct PendingRequest *pr = cls;
- struct ConnectedPeer *cp;
- struct PendingMessage *pm;
- struct GetMessage *gm;
- GNUNET_HashCode *ext;
- char *bfdata;
- size_t msize;
- unsigned int k;
- int no_route;
- uint32_t bm;
- unsigned int i;
-
- /* (3) transmit, update ttl/priority */
- cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
- &peer->hashPubKey);
- if (cp == NULL)
- {
- /* Peer must have just left */
-#if DEBUG_FS
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "Selected peer disconnected!\n");
-#endif
- if (pr->task == GNUNET_SCHEDULER_NO_TASK)
- pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
- &forward_request_task,
- pr);
- return;
- }
- cp->irc = NULL;
- pr->pirc = NULL;
- if (peer == NULL)
- {
- /* error in communication with core, try again later */
- if (pr->task == GNUNET_SCHEDULER_NO_TASK)
- pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
- &forward_request_task,
- pr);
- return;
- }
- no_route = GNUNET_NO;
- if (amount == 0)
- {
- if (pr->cp == NULL)
- {
-#if DEBUG_FS > 1
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "Failed to reserve bandwidth for reply (got %d/%u bytes only)!\n",
- amount,
- DBLOCK_SIZE);
-#endif
- GNUNET_STATISTICS_update (stats,
- gettext_noop ("# reply bandwidth reservation requests failed"),
- 1,
- GNUNET_NO);
- if (pr->task == GNUNET_SCHEDULER_NO_TASK)
- pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
- &forward_request_task,
- pr);
- return; /* this target round failed */
- }
- no_route = GNUNET_YES;
- }
-
- GNUNET_STATISTICS_update (stats,
- gettext_noop ("# queries scheduled for forwarding"),
- 1,
- GNUNET_NO);
- for (i=0;i<pr->used_targets_off;i++)
- if (pr->used_targets[i].pid == cp->pid)
- {
- GNUNET_STATISTICS_update (stats,
- gettext_noop ("# queries retransmitted to same target"),
- 1,
- GNUNET_NO);
- break;
- }
-
- /* build message and insert message into priority queue */
-#if DEBUG_FS
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "Forwarding request `%s' to `%4s'!\n",
- GNUNET_h2s (&pr->query),
- GNUNET_i2s (peer));
-#endif
- k = 0;
- bm = 0;
- if (GNUNET_YES == no_route)
- {
- bm |= GET_MESSAGE_BIT_RETURN_TO;
- k++;
- }
- if (pr->namespace != NULL)
- {
- bm |= GET_MESSAGE_BIT_SKS_NAMESPACE;
- k++;
- }
- if (pr->target_pid != 0)
- {
- bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
- k++;
- }
- msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
- GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
- pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
- pm->msize = msize;
- gm = (struct GetMessage*) &pm[1];
- gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
- gm->header.size = htons (msize);
- gm->type = htonl (pr->type);
- pr->remaining_priority /= 2;
- gm->priority = htonl (pr->remaining_priority);
- gm->ttl = htonl (pr->ttl);
- gm->filter_mutator = htonl(pr->mingle);
- gm->hash_bitmap = htonl (bm);
- gm->query = pr->query;
- ext = (GNUNET_HashCode*) &gm[1];
- k = 0;
- if (GNUNET_YES == no_route)
- GNUNET_PEER_resolve (pr->cp->pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
- if (pr->namespace != NULL)
- memcpy (&ext[k++], pr->namespace, sizeof (GNUNET_HashCode));
- if (pr->target_pid != 0)
- GNUNET_PEER_resolve (pr->target_pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
- bfdata = (char *) &ext[k];
- if (pr->bf != NULL)
- GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
- bfdata,
- pr->bf_size);
- pm->cont = &transmit_query_continuation;
- pm->cont_cls = pr;
- cp->last_request_times[(cp->last_request_times_off++) % MAX_QUEUE_PER_PEER] = GNUNET_TIME_absolute_get ();
- add_to_pending_messages_for_peer (cp, pm, pr);
-}
-
-
-/**
- * Closure used for "target_peer_select_cb".
- */
-struct PeerSelectionContext
-{
- /**
- * The request for which we are selecting
- * peers.
- */
- struct PendingRequest *pr;
-
- /**
- * Current "prime" target.
- */
- struct GNUNET_PeerIdentity target;
-
- /**
- * How much do we like this target?
- */
- double target_score;
-
- /**
- * Does it make sense to we re-try quickly again?
- */
- int fast_retry;
-
-};
-
-
-/**
- * Function called for each connected peer to determine
- * which one(s) would make good targets for forwarding.
- *
- * @param cls closure (struct PeerSelectionContext)
- * @param key current key code (peer identity)
- * @param value value in the hash map (struct ConnectedPeer)
- * @return GNUNET_YES if we should continue to
- * iterate,
- * GNUNET_NO if not.
- */
-static int
-target_peer_select_cb (void *cls,
- const GNUNET_HashCode * key,
- void *value)
-{
- struct PeerSelectionContext *psc = cls;
- struct ConnectedPeer *cp = value;
- struct PendingRequest *pr = psc->pr;
- struct GNUNET_TIME_Relative delay;
- double score;
- unsigned int i;
- unsigned int pc;
-
- /* 1) check that this peer is not the initiator */
- if (cp == pr->cp)
- {
-#if DEBUG_FS
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "Skipping initiator in forwarding selection\n");
-#endif
- return GNUNET_YES; /* skip */
- }
- if (cp->irc != NULL)
- {
- psc->fast_retry = GNUNET_YES;
- return GNUNET_YES; /* skip: already querying core about this peer for other reasons */
- }
-
- /* 2) check if we have already (recently) forwarded to this peer */
- /* 2a) this particular request */
- pc = 0;
- for (i=0;i<pr->used_targets_off;i++)
- if (pr->used_targets[i].pid == cp->pid)
- {
- pc = pr->used_targets[i].num_requests;
- GNUNET_assert (pc > 0);
- /* FIXME: make re-enabling a peer independent of how often
- this function is called??? */
- if (0 != GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
- RETRY_PROBABILITY_INV * pc))
- {
-#if DEBUG_FS
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "NOT re-trying query that was previously transmitted %u times\n",
- (unsigned int) pc);
-#endif
- return GNUNET_YES; /* skip */
- }
- break;
- }
-#if DEBUG_FS
- if (0 < pc)
- {
- GNUNET_log (GNUNET_ERROR_TYPE_INFO,
- "Re-trying query that was previously transmitted %u times to this peer\n",
- (unsigned int) pc);
- }
-#endif
- /* 2b) many other requests to this peer */
- delay = GNUNET_TIME_absolute_get_duration (cp->last_request_times[cp->last_request_times_off % MAX_QUEUE_PER_PEER]);
- if (delay.rel_value <= cp->avg_delay.rel_value)
- {
-#if DEBUG_FS
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "NOT sending query since we send %u others to this peer in the last %llums\n",
- MAX_QUEUE_PER_PEER,
- cp->avg_delay.rel_value);
-#endif
- return GNUNET_YES; /* skip */
- }
-
- /* 3) calculate how much we'd like to forward to this peer,
- starting with a random value that is strong enough
- to at least give any peer a chance sometimes
- (compared to the other factors that come later) */
- /* 3a) count successful (recent) routes from cp for same source */
- if (pr->cp != NULL)
- {
- score = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
- P2P_SUCCESS_LIST_SIZE);
- for (i=0;i<P2P_SUCCESS_LIST_SIZE;i++)
- if (cp->last_p2p_replies[i] == pr->cp->pid)
- score += 1.0; /* likely successful based on hot path */
- }
- else
- {
- score = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
- CS2P_SUCCESS_LIST_SIZE);
- for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
- if (cp->last_client_replies[i] == pr->client_request_list->client_list->client)
- score += 1.0; /* likely successful based on hot path */
- }
- /* 3b) include latency */
- if (cp->avg_delay.rel_value < 4 * TTL_DECREMENT)
- score += 1.0; /* likely fast based on latency */
- /* 3c) include priorities */
- if (cp->avg_priority <= pr->remaining_priority / 2.0)
- score += 1.0; /* likely successful based on priorities */
- /* 3d) penalize for queue size */
- score -= (2.0 * cp->pending_requests / (double) MAX_QUEUE_PER_PEER);
- /* 3e) include peer proximity */
- score -= (2.0 * (GNUNET_CRYPTO_hash_distance_u32 (key,
- &pr->query)) / (double) UINT32_MAX);
- /* 4) super-bonus for being the known target */
- if (pr->target_pid == cp->pid)
- score += 100.0;
- /* store best-fit in closure */
- score++; /* avoid zero */
- if (score > psc->target_score)
- {
- psc->target_score = score;
- psc->target.hashPubKey = *key;
- }
-#if DEBUG_FS
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "Peer `%s' gets score %f for forwarding query, max is %8f\n",
- GNUNET_h2s (key),
- score,
- psc->target_score);
-#endif
- return GNUNET_YES;
-}
-
-
-/**
- * The priority level imposes a bound on the maximum
- * value for the ttl that can be requested.
- *
- * @param ttl_in requested ttl
- * @param prio given priority
- * @return ttl_in if ttl_in is below the limit,
- * otherwise the ttl-limit for the given priority
- */
-static int32_t
-bound_ttl (int32_t ttl_in, uint32_t prio)
-{
- unsigned long long allowed;
-
- if (ttl_in <= 0)
- return ttl_in;
- allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
- if (ttl_in > allowed)
- {
- if (allowed >= (1 << 30))
- return 1 << 30;
- return allowed;
- }
- return ttl_in;
-}
-
-
-/**
- * Iterator called on each result obtained for a DHT
- * operation that expects a reply
- *
- * @param cls closure
- * @param exp when will this value expire
- * @param key key of the result
- * @param get_path NULL-terminated array of pointers
- * to the peers on reverse GET path (or NULL if not recorded)
- * @param put_path NULL-terminated array of pointers
- * to the peers on the PUT path (or NULL if not recorded)
- * @param type type of the result
- * @param size number of bytes in data
- * @param data pointer to the result data
- */
-static void
-process_dht_reply (void *cls,
- struct GNUNET_TIME_Absolute exp,
- const GNUNET_HashCode * key,
- const struct GNUNET_PeerIdentity * const *get_path,
- const struct GNUNET_PeerIdentity * const *put_path,
- enum GNUNET_BLOCK_Type type,
- size_t size,
- const void *data);
-
-
-/**
- * We're processing a GET request and have decided
- * to forward it to other peers. This function is called periodically
- * and should forward the request to other peers until we have all
- * possible replies. If we have transmitted the *only* reply to
- * the initiator we should destroy the pending request. If we have
- * many replies in the queue to the initiator, we should delay sending
- * out more queries until the reply queue has shrunk some.
- *
- * @param cls our "struct ProcessGetContext *"
- * @param tc unused
- */
-static void
-forward_request_task (void *cls,
- const struct GNUNET_SCHEDULER_TaskContext *tc)
-{
- struct PendingRequest *pr = cls;
- struct PeerSelectionContext psc;
- struct ConnectedPeer *cp;
- struct GNUNET_TIME_Relative delay;
-
- pr->task = GNUNET_SCHEDULER_NO_TASK;
- if (pr->pirc != NULL)
- {
-#if DEBUG_FS
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "Forwarding of query `%s' not attempted due to pending local lookup!\n",
- GNUNET_h2s (&pr->query));
-#endif
- return; /* already pending */
- }
- if (GNUNET_YES == pr->local_only)
- return; /* configured to not do P2P search */
- /* (0) try DHT */
- if ( (0 == pr->anonymity_level) &&
- (GNUNET_YES != pr->forward_only) &&
- (pr->type != GNUNET_BLOCK_TYPE_FS_DBLOCK) &&
- (pr->type != GNUNET_BLOCK_TYPE_FS_IBLOCK) )
- {
- pr->dht_get = GNUNET_DHT_get_start (dht_handle,
- GNUNET_TIME_UNIT_FOREVER_REL,
- pr->type,
- &pr->query,
- DEFAULT_GET_REPLICATION,
- GNUNET_DHT_RO_NONE,
- pr->bf,
- pr->mingle,
- pr->namespace,
- (pr->namespace != NULL) ? sizeof (GNUNET_HashCode) : 0,
- &process_dht_reply,
- pr);
- }
- /* (1) select target */
- psc.pr = pr;
- psc.target_score = -DBL_MAX;
- psc.fast_retry = GNUNET_NO;
- GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
- &target_peer_select_cb,
- &psc);
- if (psc.target_score == -DBL_MAX)
- {
- if (psc.fast_retry == GNUNET_YES)
- delay = GNUNET_TIME_UNIT_MILLISECONDS; /* FIXME: store adaptive fast-retry value in 'pr' */
- else
- delay = get_processing_delay ();
-#if DEBUG_FS
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "No peer selected for forwarding of query `%s', will try again in %llu ms!\n",
- GNUNET_h2s (&pr->query),
- delay.rel_value);
-#endif
- pr->task = GNUNET_SCHEDULER_add_delayed (delay,
- &forward_request_task,
- pr);
- return; /* nobody selected */
- }
- /* (3) update TTL/priority */
- if (pr->client_request_list != NULL)
- {
- /* FIXME: use better algorithm!? */
- if (0 == GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
- 4))
- pr->priority++;
- /* bound priority we use by priorities we see from other peers
- rounded up (must round up so that we can see non-zero
- priorities, but round up as little as possible to make it
- plausible that we forwarded another peers request) */
- if (pr->priority > current_priorities + 1.0)
- pr->priority = (uint32_t) current_priorities + 1.0;
- pr->ttl = bound_ttl (pr->ttl + TTL_DECREMENT * 2,
- pr->priority);
-#if DEBUG_FS
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "Trying query `%s' with priority %u and TTL %d.\n",
- GNUNET_h2s (&pr->query),
- pr->priority,
- pr->ttl);
-#endif
- }
-
- /* (3) reserve reply bandwidth */
- if (GNUNET_NO == pr->forward_only)
- {
- cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
- &psc.target.hashPubKey);
- GNUNET_assert (NULL != cp);
- GNUNET_assert (cp->irc == NULL);
- pr->pirc = cp;
- cp->pr = pr;
- cp->irc = GNUNET_CORE_peer_change_preference (core,
- &psc.target,
- GNUNET_CONSTANTS_SERVICE_TIMEOUT,
- GNUNET_BANDWIDTH_value_init (UINT32_MAX),
- DBLOCK_SIZE * 2,
- cp->inc_preference,
- &target_reservation_cb,
- pr);
- GNUNET_assert (cp->irc != NULL);
- cp->inc_preference = 0;
- }
- else
- {
- /* force forwarding */
- static struct GNUNET_BANDWIDTH_Value32NBO zerobw;
- target_reservation_cb (pr, &psc.target,
- zerobw, 0, 0.0);
- }
-}
-
-
-/* **************************** P2P PUT Handling ************************ */
-
-
-/**
- * Function called after we either failed or succeeded
- * at transmitting a reply to a peer.
- *
- * @param cls the requests "struct PendingRequest*"
- * @param tpid ID of receiving peer, 0 on transmission error
- */
-static void
-transmit_reply_continuation (void *cls,
- GNUNET_PEER_Id tpid)
-{
- struct PendingRequest *pr = cls;
-
- switch (pr->type)
- {
- case GNUNET_BLOCK_TYPE_FS_DBLOCK:
- case GNUNET_BLOCK_TYPE_FS_IBLOCK:
- /* only one reply expected, done with the request! */
- destroy_pending_request (pr);
- break;
- case GNUNET_BLOCK_TYPE_ANY:
- case GNUNET_BLOCK_TYPE_FS_KBLOCK:
- case GNUNET_BLOCK_TYPE_FS_SBLOCK:
- break;
- default:
- GNUNET_break (0);
- break;
- }
-}
-
-
-/**
- * Transmit the given message by copying it to the target buffer
- * "buf". "buf" will be NULL and "size" zero if the socket was closed
- * for writing in the meantime. In that case, do nothing
- * (the disconnect or shutdown handler will take care of the rest).
- * If we were able to transmit messages and there are still more
- * pending, ask core again for further calls to this function.
- *
- * @param cls closure, pointer to the 'struct ClientList*'
- * @param size number of bytes available in buf
- * @param buf where the callee should write the message
- * @return number of bytes written to buf
- */
-static size_t
-transmit_to_client (void *cls,
- size_t size, void *buf)
-{
- struct ClientList *cl = cls;
- char *cbuf = buf;
- struct ClientResponseMessage *creply;
- size_t msize;
-
- cl->th = NULL;
- if (NULL == buf)
- {
-#if DEBUG_FS
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "Not sending reply, client communication problem.\n");
-#endif
- return 0;
- }
- msize = 0;
- while ( (NULL != (creply = cl->res_head) ) &&
- (creply->msize <= size) )
- {
- memcpy (&cbuf[msize], &creply[1], creply->msize);
- msize += creply->msize;
- size -= creply->msize;
- GNUNET_CONTAINER_DLL_remove (cl->res_head,
- cl->res_tail,
- creply);
- GNUNET_free (creply);
- }
- if (NULL != creply)
- cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
- creply->msize,
- GNUNET_TIME_UNIT_FOREVER_REL,
- &transmit_to_client,
- cl);
-#if DEBUG_FS
- GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
- "Transmitted %u bytes to client\n",
- (unsigned int) msize);
-#endif
- return msize;
-}
-
-
-/**
- * Closure for "process_reply" function.
- */
-struct ProcessReplyClosure
-{
- /**
- * The data for the reply.
- */
- const void *data;
-
- /**
- * Who gave us this reply? NULL for local host (or DHT)
- */
- struct ConnectedPeer *sender;
-
- /**
- * When the reply expires.
- */
- struct GNUNET_TIME_Absolute expiration;
-
- /**
- * Size of data.
- */
- size_t size;
-
- /**
- * Type of the block.
- */
- enum GNUNET_BLOCK_Type type;
-
- /**
- * How much was this reply worth to us?
- */
- uint32_t priority;
-
- /**
- * Evaluation result (returned).
- */
- enum GNUNET_BLOCK_EvaluationResult eval;
-
- /**
- * Did we finish processing the associated request?
- */
- int finished;
-
- /**
- * Did we find a matching request?
- */
- int request_found;
-};