-fix block download calculation
[oweals/gnunet.git] / src / fs / gnunet-service-fs_pr.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2010, 2011, 2012 Christian Grothoff (and other contributing authors)
4
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.
9
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.
14
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.
19 */
20
21 /**
22  * @file fs/gnunet-service-fs_pr.c
23  * @brief API to handle pending requests
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_load_lib.h"
28 #include "gnunet-service-fs.h"
29 #include "gnunet-service-fs_cp.h"
30 #include "gnunet-service-fs_indexing.h"
31 #include "gnunet-service-fs_pe.h"
32 #include "gnunet-service-fs_pr.h"
33
34 /**
35  * Maximum size of the datastore queue for P2P operations.  Needs to
36  * be large enough to queue MAX_QUEUE_PER_PEER operations for roughly
37  * the number of active (connected) peers.
38  */
39 #define MAX_DATASTORE_QUEUE (16 * MAX_QUEUE_PER_PEER)
40
41 /**
42  * Bandwidth value of a 0-priority content (must be fairly high
43  * compared to query since content is typically significantly larger
44  * -- and more valueable since it can take many queries to get one
45  * piece of content).
46  */
47 #define CONTENT_BANDWIDTH_VALUE 800
48
49 /**
50  * Hard limit on the number of results we may get from the datastore per query.
51  */
52 #define MAX_RESULTS (100 * 1024)
53
54 /**
55  * Collect an instane number of statistics?  May cause excessive IPC.
56  */
57 #define INSANE_STATISTICS GNUNET_NO
58
59 /**
60  * An active request.
61  */
62 struct GSF_PendingRequest
63 {
64   /**
65    * Public data for the request.
66    */
67   struct GSF_PendingRequestData public_data;
68
69   /**
70    * Function to call if we encounter a reply.
71    */
72   GSF_PendingRequestReplyHandler rh;
73
74   /**
75    * Closure for 'rh'
76    */
77   void *rh_cls;
78
79   /**
80    * Array of hash codes of replies we've already seen.
81    */
82   struct GNUNET_HashCode *replies_seen;
83
84   /**
85    * Bloomfilter masking replies we've already seen.
86    */
87   struct GNUNET_CONTAINER_BloomFilter *bf;
88
89   /**
90    * Entry for this pending request in the expiration heap, or NULL.
91    */
92   struct GNUNET_CONTAINER_HeapNode *hnode;
93
94   /**
95    * Datastore queue entry for this request (or NULL for none).
96    */
97   struct GNUNET_DATASTORE_QueueEntry *qe;
98
99   /**
100    * DHT request handle for this request (or NULL for none).
101    */
102   struct GNUNET_DHT_GetHandle *gh;
103
104   /**
105    * Function to call upon completion of the local get
106    * request, or NULL for none.
107    */
108   GSF_LocalLookupContinuation llc_cont;
109
110   /**
111    * Closure for llc_cont.
112    */
113   void *llc_cont_cls;
114
115   /**
116    * Last result from the local datastore lookup evaluation.
117    */
118   enum GNUNET_BLOCK_EvaluationResult local_result;
119
120   /**
121    * Identity of the peer that we should use for the 'sender'
122    * (recipient of the response) when forwarding (0 for none).
123    */
124   GNUNET_PEER_Id sender_pid;
125
126   /**
127    * Identity of the peer that we should never forward this query
128    * to since it originated this query (0 for none).
129    */
130   GNUNET_PEER_Id origin_pid;
131
132   /**
133    * Time we started the last datastore lookup.
134    */
135   struct GNUNET_TIME_Absolute qe_start;
136
137   /**
138    * Task that warns us if the local datastore lookup takes too long.
139    */
140   GNUNET_SCHEDULER_TaskIdentifier warn_task;
141
142   /**
143    * Current offset for querying our local datastore for results.
144    * Starts at a random value, incremented until we get the same
145    * UID again (detected using 'first_uid'), which is then used
146    * to termiante the iteration.
147    */
148   uint64_t local_result_offset;
149
150   /**
151    * Unique ID of the first result from the local datastore;
152    * used to detect wrap-around of the offset.
153    */
154   uint64_t first_uid;
155
156   /**
157    * Number of valid entries in the 'replies_seen' array.
158    */
159   unsigned int replies_seen_count;
160
161   /**
162    * Length of the 'replies_seen' array.
163    */
164   unsigned int replies_seen_size;
165
166   /**
167    * Mingle value we currently use for the bf.
168    */
169   uint32_t mingle;
170
171   /**
172    * Do we have a first UID yet?
173    */
174   unsigned int have_first_uid;
175
176 };
177
178
179 /**
180  * All pending requests, ordered by the query.  Entries
181  * are of type 'struct GSF_PendingRequest*'.
182  */
183 static struct GNUNET_CONTAINER_MultiHashMap *pr_map;
184
185
186 /**
187  * Datastore 'PUT' load tracking.
188  */
189 static struct GNUNET_LOAD_Value *datastore_put_load;
190
191
192 /**
193  * Are we allowed to migrate content to this peer.
194  */
195 static int active_to_migration;
196
197
198 /**
199  * Size of the datastore queue we assume for common requests.
200  * Determined based on the network quota.
201  */
202 static unsigned int datastore_queue_size;
203
204 /**
205  * Heap with the request that will expire next at the top.  Contains
206  * pointers of type "struct PendingRequest*"; these will *also* be
207  * aliased from the "requests_by_peer" data structures and the
208  * "requests_by_query" table.  Note that requests from our clients
209  * don't expire and are thus NOT in the "requests_by_expiration"
210  * (or the "requests_by_peer" tables).
211  */
212 static struct GNUNET_CONTAINER_Heap *requests_by_expiration_heap;
213
214
215 /**
216  * Maximum number of requests (from other peers, overall) that we're
217  * willing to have pending at any given point in time.  Can be changed
218  * via the configuration file (32k is just the default).
219  */
220 static unsigned long long max_pending_requests = (32 * 1024);
221
222
223
224 /**
225  * Recalculate our bloom filter for filtering replies.  This function
226  * will create a new bloom filter from scratch, so it should only be
227  * called if we have no bloomfilter at all (and hence can create a
228  * fresh one of minimal size without problems) OR if our peer is the
229  * initiator (in which case we may resize to larger than mimimum size).
230  *
231  * @param pr request for which the BF is to be recomputed
232  */
233 static void
234 refresh_bloomfilter (struct GSF_PendingRequest *pr)
235 {
236   if (pr->bf != NULL)
237     GNUNET_CONTAINER_bloomfilter_free (pr->bf);
238   pr->mingle =
239       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
240   pr->bf =
241       GNUNET_BLOCK_construct_bloomfilter (pr->mingle, pr->replies_seen,
242                                           pr->replies_seen_count);
243 }
244
245
246 /**
247  * Create a new pending request.
248  *
249  * @param options request options
250  * @param type type of the block that is being requested
251  * @param query key for the lookup
252  * @param namespace namespace to lookup, NULL for no namespace
253  * @param target preferred target for the request, NULL for none
254  * @param bf_data raw data for bloom filter for known replies, can be NULL
255  * @param bf_size number of bytes in bf_data
256  * @param mingle mingle value for bf
257  * @param anonymity_level desired anonymity level
258  * @param priority maximum outgoing cummulative request priority to use
259  * @param ttl current time-to-live for the request
260  * @param sender_pid peer ID to use for the sender when forwarding, 0 for none
261  * @param origin_pid peer ID of origin of query (do not loop back)
262  * @param replies_seen hash codes of known local replies
263  * @param replies_seen_count size of the 'replies_seen' array
264  * @param rh handle to call when we get a reply
265  * @param rh_cls closure for rh
266  * @return handle for the new pending request
267  */
268 struct GSF_PendingRequest *
269 GSF_pending_request_create_ (enum GSF_PendingRequestOptions options,
270                              enum GNUNET_BLOCK_Type type,
271                              const struct GNUNET_HashCode * query,
272                              const struct GNUNET_HashCode * namespace,
273                              const struct GNUNET_PeerIdentity *target,
274                              const char *bf_data, size_t bf_size,
275                              uint32_t mingle, uint32_t anonymity_level,
276                              uint32_t priority, int32_t ttl,
277                              GNUNET_PEER_Id sender_pid,
278                              GNUNET_PEER_Id origin_pid,
279                              const struct GNUNET_HashCode * replies_seen,
280                              unsigned int replies_seen_count,
281                              GSF_PendingRequestReplyHandler rh, void *rh_cls)
282 {
283   struct GSF_PendingRequest *pr;
284   struct GSF_PendingRequest *dpr;
285   size_t extra;
286   struct GNUNET_HashCode *eptr;
287
288   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
289               "Creating request handle for `%s' of type %d\n",
290               GNUNET_h2s (query), type);
291 #if INSANE_STATISTICS
292   GNUNET_STATISTICS_update (GSF_stats,
293                             gettext_noop ("# Pending requests created"), 1,
294                             GNUNET_NO);
295 #endif
296   extra = 0;
297   if (GNUNET_BLOCK_TYPE_FS_SBLOCK == type)
298     extra += sizeof (struct GNUNET_HashCode);
299   if (NULL != target)
300     extra += sizeof (struct GNUNET_PeerIdentity);
301   pr = GNUNET_malloc (sizeof (struct GSF_PendingRequest) + extra);
302   pr->local_result_offset =
303       GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
304   pr->public_data.query = *query;
305   eptr = (struct GNUNET_HashCode *) &pr[1];
306   if (GNUNET_BLOCK_TYPE_FS_SBLOCK == type)
307   {
308     GNUNET_assert (NULL != namespace);        
309     pr->public_data.namespace = eptr;
310     memcpy (eptr, namespace, sizeof (struct GNUNET_HashCode));
311     eptr++;
312   }
313   if (NULL != target)
314   {
315     pr->public_data.target = (struct GNUNET_PeerIdentity *) eptr;
316     memcpy (eptr, target, sizeof (struct GNUNET_PeerIdentity));
317   }
318   pr->public_data.anonymity_level = anonymity_level;
319   pr->public_data.priority = priority;
320   pr->public_data.original_priority = priority;
321   pr->public_data.options = options;
322   pr->public_data.type = type;
323   pr->public_data.start_time = GNUNET_TIME_absolute_get ();
324   pr->sender_pid = sender_pid;
325   pr->origin_pid = origin_pid;
326   pr->rh = rh;
327   pr->rh_cls = rh_cls;
328   GNUNET_assert ((sender_pid != 0) || (0 == (options & GSF_PRO_FORWARD_ONLY)));
329   if (ttl >= 0)
330     pr->public_data.ttl =
331         GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_multiply
332                                           (GNUNET_TIME_UNIT_SECONDS,
333                                            (uint32_t) ttl));
334   else
335     pr->public_data.ttl =
336         GNUNET_TIME_absolute_subtract (pr->public_data.start_time,
337                                        GNUNET_TIME_relative_multiply
338                                        (GNUNET_TIME_UNIT_SECONDS,
339                                         (uint32_t) (-ttl)));
340   if (replies_seen_count > 0)
341   {
342     pr->replies_seen_size = replies_seen_count;
343     pr->replies_seen =
344         GNUNET_malloc (sizeof (struct GNUNET_HashCode) * pr->replies_seen_size);
345     memcpy (pr->replies_seen, replies_seen,
346             replies_seen_count * sizeof (struct GNUNET_HashCode));
347     pr->replies_seen_count = replies_seen_count;
348   }
349   if (NULL != bf_data)
350   {
351     pr->bf =
352         GNUNET_CONTAINER_bloomfilter_init (bf_data, bf_size,
353                                            GNUNET_CONSTANTS_BLOOMFILTER_K);
354     pr->mingle = mingle;
355   }
356   else if ((replies_seen_count > 0) &&
357            (0 != (options & GSF_PRO_BLOOMFILTER_FULL_REFRESH)))
358   {
359     refresh_bloomfilter (pr);
360   }
361   GNUNET_CONTAINER_multihashmap_put (pr_map, 
362                                      &pr->public_data.query, pr,
363                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
364   if (0 == (options & GSF_PRO_REQUEST_NEVER_EXPIRES))
365   {
366     pr->hnode =
367         GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap, pr,
368                                       pr->public_data.ttl.abs_value);
369     /* make sure we don't track too many requests */
370     while (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) >
371            max_pending_requests)
372     {
373       dpr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
374       GNUNET_assert (dpr != NULL);
375       if (pr == dpr)
376         break;                  /* let the request live briefly... */
377       if (NULL != dpr->rh)
378         dpr->rh (dpr->rh_cls, GNUNET_BLOCK_EVALUATION_REQUEST_VALID, dpr,
379                  UINT32_MAX, GNUNET_TIME_UNIT_FOREVER_ABS, GNUNET_TIME_UNIT_FOREVER_ABS,
380                  GNUNET_BLOCK_TYPE_ANY, NULL, 0);
381       GSF_pending_request_cancel_ (dpr, GNUNET_YES);
382     }
383   }
384   GNUNET_STATISTICS_update (GSF_stats,
385                             gettext_noop ("# Pending requests active"), 1,
386                             GNUNET_NO);
387   return pr;
388 }
389
390 /**
391  * Obtain the public data associated with a pending request
392  *
393  * @param pr pending request
394  * @return associated public data
395  */
396 struct GSF_PendingRequestData *
397 GSF_pending_request_get_data_ (struct GSF_PendingRequest *pr)
398 {
399   return &pr->public_data;
400 }
401
402
403 /**
404  * Test if two pending requests are compatible (would generate
405  * the same query modulo filters and should thus be processed
406  * jointly).
407  *
408  * @param pra a pending request
409  * @param prb another pending request
410  * @return GNUNET_OK if the requests are compatible
411  */
412 int
413 GSF_pending_request_is_compatible_ (struct GSF_PendingRequest *pra,
414                                     struct GSF_PendingRequest *prb)
415 {
416   if ((pra->public_data.type != prb->public_data.type) ||
417       (0 !=
418        memcmp (&pra->public_data.query, &prb->public_data.query,
419                sizeof (struct GNUNET_HashCode))) ||
420       ((pra->public_data.type == GNUNET_BLOCK_TYPE_FS_SBLOCK) &&
421        (0 !=
422         memcmp (pra->public_data.namespace, 
423                 prb->public_data.namespace,
424                 sizeof (struct GNUNET_HashCode)))))
425     return GNUNET_NO;
426   return GNUNET_OK;
427 }
428
429
430
431 /**
432  * Update a given pending request with additional replies
433  * that have been seen.
434  *
435  * @param pr request to update
436  * @param replies_seen hash codes of replies that we've seen
437  * @param replies_seen_count size of the replies_seen array
438  */
439 void
440 GSF_pending_request_update_ (struct GSF_PendingRequest *pr,
441                              const struct GNUNET_HashCode * replies_seen,
442                              unsigned int replies_seen_count)
443 {
444   unsigned int i;
445   struct GNUNET_HashCode mhash;
446
447   if (replies_seen_count + pr->replies_seen_count < pr->replies_seen_count)
448     return;                     /* integer overflow */
449   if (0 != (pr->public_data.options & GSF_PRO_BLOOMFILTER_FULL_REFRESH))
450   {
451     /* we're responsible for the BF, full refresh */
452     if (replies_seen_count + pr->replies_seen_count > pr->replies_seen_size)
453       GNUNET_array_grow (pr->replies_seen, pr->replies_seen_size,
454                          replies_seen_count + pr->replies_seen_count);
455     memcpy (&pr->replies_seen[pr->replies_seen_count], replies_seen,
456             sizeof (struct GNUNET_HashCode) * replies_seen_count);
457     pr->replies_seen_count += replies_seen_count;
458     refresh_bloomfilter (pr);
459   }
460   else
461   {
462     if (NULL == pr->bf)
463     {
464       /* we're not the initiator, but the initiator did not give us
465        * any bloom-filter, so we need to create one on-the-fly */
466       pr->mingle =
467           GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
468       pr->bf =
469           GNUNET_BLOCK_construct_bloomfilter (pr->mingle, replies_seen,
470                                               replies_seen_count);
471     }
472     else
473     {
474       for (i = 0; i < pr->replies_seen_count; i++)
475       {
476         GNUNET_BLOCK_mingle_hash (&replies_seen[i], pr->mingle, &mhash);
477         GNUNET_CONTAINER_bloomfilter_add (pr->bf, &mhash);
478       }
479     }
480   }
481 }
482
483
484 /**
485  * Generate the message corresponding to the given pending request for
486  * transmission to other peers (or at least determine its size).
487  *
488  * @param pr request to generate the message for
489  * @param buf_size number of bytes available in buf
490  * @param buf where to copy the message (can be NULL)
491  * @return number of bytes needed (if > buf_size) or used
492  */
493 size_t
494 GSF_pending_request_get_message_ (struct GSF_PendingRequest *pr,
495                                   size_t buf_size, void *buf)
496 {
497   char lbuf[GNUNET_SERVER_MAX_MESSAGE_SIZE];
498   struct GetMessage *gm;
499   struct GNUNET_HashCode *ext;
500   size_t msize;
501   unsigned int k;
502   uint32_t bm;
503   uint32_t prio;
504   size_t bf_size;
505   struct GNUNET_TIME_Absolute now;
506   int64_t ttl;
507   int do_route;
508
509   if (buf_size > 0)
510     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
511                 "Building request message for `%s' of type %d\n",
512                 GNUNET_h2s (&pr->public_data.query), pr->public_data.type);
513   k = 0;
514   bm = 0;
515   do_route = (0 == (pr->public_data.options & GSF_PRO_FORWARD_ONLY));
516   if ((!do_route) && (pr->sender_pid == 0))
517   {
518     GNUNET_break (0);
519     do_route = GNUNET_YES;
520   }
521   if (!do_route)
522   {
523     bm |= GET_MESSAGE_BIT_RETURN_TO;
524     k++;
525   }
526   if (GNUNET_BLOCK_TYPE_FS_SBLOCK == pr->public_data.type)
527   {
528     bm |= GET_MESSAGE_BIT_SKS_NAMESPACE;
529     k++;
530   }
531   if (NULL != pr->public_data.target)
532   {
533     bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
534     k++;
535   }
536   bf_size = GNUNET_CONTAINER_bloomfilter_get_size (pr->bf);
537   msize = sizeof (struct GetMessage) + bf_size + k * sizeof (struct GNUNET_HashCode);
538   GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
539   if (buf_size < msize)
540     return msize;
541   gm = (struct GetMessage *) lbuf;
542   gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
543   gm->header.size = htons (msize);
544   gm->type = htonl (pr->public_data.type);
545   if (do_route)
546     prio =
547         GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
548                                   pr->public_data.priority + 1);
549   else
550     prio = 0;
551   pr->public_data.priority -= prio;
552   pr->public_data.num_transmissions++;
553   pr->public_data.respect_offered += prio;
554   gm->priority = htonl (prio);
555   now = GNUNET_TIME_absolute_get ();
556   ttl = (int64_t) (pr->public_data.ttl.abs_value - now.abs_value);
557   gm->ttl = htonl (ttl / 1000);
558   gm->filter_mutator = htonl (pr->mingle);
559   gm->hash_bitmap = htonl (bm);
560   gm->query = pr->public_data.query;
561   ext = (struct GNUNET_HashCode *) & gm[1];
562   k = 0;
563   if (!do_route)
564     GNUNET_PEER_resolve (pr->sender_pid,
565                          (struct GNUNET_PeerIdentity *) &ext[k++]);
566   if (GNUNET_BLOCK_TYPE_FS_SBLOCK == pr->public_data.type)
567     memcpy (&ext[k++], pr->public_data.namespace, sizeof (struct GNUNET_HashCode));
568   if (NULL != pr->public_data.target)
569     memcpy (&ext[k++],
570             pr->public_data.target,
571             sizeof (struct GNUNET_PeerIdentity));
572   if (pr->bf != NULL)
573     GNUNET_assert (GNUNET_SYSERR !=
574                    GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
575                                                               (char *) &ext[k],
576                                                               bf_size));
577   memcpy (buf, gm, msize);
578   return msize;
579 }
580
581
582 /**
583  * Iterator to free pending requests.
584  *
585  * @param cls closure, unused
586  * @param key current key code
587  * @param value value in the hash map (pending request)
588  * @return GNUNET_YES (we should continue to iterate)
589  */
590 static int
591 clean_request (void *cls, const struct GNUNET_HashCode * key, void *value)
592 {
593   struct GSF_PendingRequest *pr = value;
594   GSF_LocalLookupContinuation cont;
595
596   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
597               "Cleaning up pending request for `%s'.\n", GNUNET_h2s (key));
598   if (NULL != (cont = pr->llc_cont))
599   {
600     pr->llc_cont = NULL;
601     cont (pr->llc_cont_cls, pr, pr->local_result);
602   }
603   GSF_plan_notify_request_done_ (pr);
604   GNUNET_free_non_null (pr->replies_seen);
605   if (NULL != pr->bf)
606   {
607     GNUNET_CONTAINER_bloomfilter_free (pr->bf);
608     pr->bf = NULL;
609   }
610   GNUNET_PEER_change_rc (pr->sender_pid, -1);
611   pr->sender_pid = 0;
612   GNUNET_PEER_change_rc (pr->origin_pid, -1);
613   pr->origin_pid = 0;
614   if (NULL != pr->hnode)
615   {
616     GNUNET_CONTAINER_heap_remove_node (pr->hnode);
617     pr->hnode = NULL;
618   }
619   if (NULL != pr->qe)
620   {
621     GNUNET_DATASTORE_cancel (pr->qe);
622     pr->qe = NULL;
623   }
624   if (NULL != pr->gh)
625   {
626     GNUNET_DHT_get_stop (pr->gh);
627     pr->gh = NULL;
628   }
629   if (GNUNET_SCHEDULER_NO_TASK != pr->warn_task)
630   {
631     GNUNET_SCHEDULER_cancel (pr->warn_task);
632     pr->warn_task = GNUNET_SCHEDULER_NO_TASK;
633   }
634   GNUNET_assert (GNUNET_OK ==
635                  GNUNET_CONTAINER_multihashmap_remove (pr_map,
636                                                        &pr->public_data.query,
637                                                        pr));
638   GNUNET_STATISTICS_update (GSF_stats,
639                             gettext_noop ("# Pending requests active"), -1,
640                             GNUNET_NO);
641   GNUNET_free (pr);
642   return GNUNET_YES;
643 }
644
645
646 /**
647  * Explicitly cancel a pending request.
648  *
649  * @param pr request to cancel
650  * @param full_cleanup fully purge the request
651  */
652 void
653 GSF_pending_request_cancel_ (struct GSF_PendingRequest *pr, int full_cleanup)
654 {
655   GSF_LocalLookupContinuation cont;
656
657   if (NULL == pr_map)
658     return;                     /* already cleaned up! */
659   if (GNUNET_YES != full_cleanup)
660   {
661     /* make request inactive (we're no longer interested in more results),
662      * but do NOT remove from our data-structures, we still need it there
663      * to prevent the request from looping */
664     pr->rh = NULL;
665     if (NULL != (cont = pr->llc_cont))
666     {
667       pr->llc_cont = NULL;
668       cont (pr->llc_cont_cls, pr, pr->local_result);
669     }
670     GSF_plan_notify_request_done_ (pr);
671     if (NULL != pr->qe)
672     {
673       GNUNET_DATASTORE_cancel (pr->qe);
674       pr->qe = NULL;
675     }
676     if (NULL != pr->gh)
677     {
678       GNUNET_DHT_get_stop (pr->gh);
679       pr->gh = NULL;
680     }
681     if (GNUNET_SCHEDULER_NO_TASK != pr->warn_task)
682     {
683       GNUNET_SCHEDULER_cancel (pr->warn_task);
684       pr->warn_task = GNUNET_SCHEDULER_NO_TASK;
685     }
686     return;
687   }
688   GNUNET_assert (GNUNET_YES ==
689                  clean_request (NULL, &pr->public_data.query, pr));
690 }
691
692
693 /**
694  * Iterate over all pending requests.
695  *
696  * @param it function to call for each request
697  * @param cls closure for it
698  */
699 void
700 GSF_iterate_pending_requests_ (GSF_PendingRequestIterator it, void *cls)
701 {
702   GNUNET_CONTAINER_multihashmap_iterate (pr_map,
703                                          (GNUNET_CONTAINER_HashMapIterator) it,
704                                          cls);
705 }
706
707
708
709
710 /**
711  * Closure for "process_reply" function.
712  */
713 struct ProcessReplyClosure
714 {
715   /**
716    * The data for the reply.
717    */
718   const void *data;
719
720   /**
721    * Who gave us this reply? NULL for local host (or DHT)
722    */
723   struct GSF_ConnectedPeer *sender;
724
725   /**
726    * When the reply expires.
727    */
728   struct GNUNET_TIME_Absolute expiration;
729
730   /**
731    * Size of data.
732    */
733   size_t size;
734
735   /**
736    * Type of the block.
737    */
738   enum GNUNET_BLOCK_Type type;
739
740   /**
741    * How much was this reply worth to us?
742    */
743   uint32_t priority;
744
745   /**
746    * Anonymity requirements for this reply.
747    */
748   uint32_t anonymity_level;
749
750   /**
751    * Evaluation result (returned).
752    */
753   enum GNUNET_BLOCK_EvaluationResult eval;
754
755   /**
756    * Did we find a matching request?
757    */
758   int request_found;
759 };
760
761
762 /**
763  * Update the performance data for the sender (if any) since
764  * the sender successfully answered one of our queries.
765  *
766  * @param prq information about the sender
767  * @param pr request that was satisfied
768  */
769 static void
770 update_request_performance_data (struct ProcessReplyClosure *prq,
771                                  struct GSF_PendingRequest *pr)
772 {
773   if (prq->sender == NULL)
774     return;
775   GSF_peer_update_performance_ (prq->sender, pr->public_data.start_time,
776                                 prq->priority);
777 }
778
779
780 /**
781  * We have received a reply; handle it!
782  *
783  * @param cls response (struct ProcessReplyClosure)
784  * @param key our query
785  * @param value value in the hash map (info about the query)
786  * @return GNUNET_YES (we should continue to iterate)
787  */
788 static int
789 process_reply (void *cls, const struct GNUNET_HashCode * key, void *value)
790 {
791   struct ProcessReplyClosure *prq = cls;
792   struct GSF_PendingRequest *pr = value;
793   struct GNUNET_HashCode chash;
794   struct GNUNET_TIME_Absolute last_transmission;
795
796   if (NULL == pr->rh)
797     return GNUNET_YES;
798   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
799               "Matched result (type %u) for query `%s' with pending request\n",
800               (unsigned int) prq->type, GNUNET_h2s (key));
801   GNUNET_STATISTICS_update (GSF_stats,
802                             gettext_noop ("# replies received and matched"), 1,
803                             GNUNET_NO);
804   prq->eval =
805       GNUNET_BLOCK_evaluate (GSF_block_ctx, prq->type, key, &pr->bf, pr->mingle,
806                              pr->public_data.namespace,
807                              (prq->type ==
808                               GNUNET_BLOCK_TYPE_FS_SBLOCK) ?
809                              sizeof (struct GNUNET_HashCode) : 0, prq->data,
810                              prq->size);
811   switch (prq->eval)
812   {
813   case GNUNET_BLOCK_EVALUATION_OK_MORE:
814     update_request_performance_data (prq, pr);
815     break;
816   case GNUNET_BLOCK_EVALUATION_OK_LAST:
817     /* short cut: stop processing early, no BF-update, etc. */
818     update_request_performance_data (prq, pr);
819     GNUNET_LOAD_update (GSF_rt_entry_lifetime,
820                         GNUNET_TIME_absolute_get_duration (pr->
821                                                            public_data.start_time).rel_value);
822     if (GNUNET_YES !=
823         GSF_request_plan_reference_get_last_transmission_ (pr->public_data.pr_head, 
824                                                            prq->sender, 
825                                                            &last_transmission))
826       last_transmission.abs_value = GNUNET_TIME_UNIT_FOREVER_ABS.abs_value;
827     /* pass on to other peers / local clients */
828     pr->rh (pr->rh_cls, prq->eval, pr, prq->anonymity_level, prq->expiration,
829             last_transmission, prq->type, prq->data, prq->size);
830     return GNUNET_YES;
831   case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
832 #if INSANE_STATISTICS
833     GNUNET_STATISTICS_update (GSF_stats,
834                               gettext_noop
835                               ("# duplicate replies discarded (bloomfilter)"),
836                               1, GNUNET_NO);
837 #endif
838     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
839                 "Duplicate response, discarding.\n");
840     return GNUNET_YES;          /* duplicate */
841   case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
842     return GNUNET_YES;          /* wrong namespace */
843   case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
844     GNUNET_break (0);
845     return GNUNET_YES;
846   case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
847     GNUNET_break (0);
848     return GNUNET_YES;
849   case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
850     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Unsupported block type %u\n"),
851                 prq->type);
852     return GNUNET_NO;
853   }
854   /* update bloomfilter */
855   GNUNET_CRYPTO_hash (prq->data, prq->size, &chash);
856   GSF_pending_request_update_ (pr, &chash, 1);
857   if (NULL == prq->sender)
858   {
859     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
860                 "Found result for query `%s' in local datastore\n",
861                 GNUNET_h2s (key));
862     GNUNET_STATISTICS_update (GSF_stats,
863                               gettext_noop ("# results found locally"), 1,
864                               GNUNET_NO);
865   }
866   else
867   {
868     GSF_dht_lookup_ (pr);
869   }
870   prq->priority += pr->public_data.original_priority;
871   pr->public_data.priority = 0;
872   pr->public_data.original_priority = 0;
873   pr->public_data.results_found++;
874   prq->request_found = GNUNET_YES;
875   /* finally, pass on to other peer / local client */
876   if (! GSF_request_plan_reference_get_last_transmission_ (pr->public_data.pr_head,
877                                                            prq->sender, 
878                                                            &last_transmission))
879     last_transmission.abs_value = GNUNET_TIME_UNIT_FOREVER_ABS.abs_value;
880   pr->rh (pr->rh_cls, prq->eval, pr, 
881           prq->anonymity_level, prq->expiration,
882           last_transmission, prq->type, prq->data, prq->size);
883   return GNUNET_YES;
884 }
885
886
887 /**
888  * Context for the 'put_migration_continuation'.
889  */
890 struct PutMigrationContext
891 {
892
893   /**
894    * Start time for the operation.
895    */
896   struct GNUNET_TIME_Absolute start;
897
898   /**
899    * Request origin.
900    */
901   struct GNUNET_PeerIdentity origin;
902
903   /**
904    * GNUNET_YES if we had a matching request for this block,
905    * GNUNET_NO if not.
906    */
907   int requested;
908 };
909
910
911 /**
912  * Continuation called to notify client about result of the
913  * operation.
914  *
915  * @param cls closure
916  * @param success GNUNET_SYSERR on failure
917  * @param min_expiration minimum expiration time required for content to be stored
918  * @param msg NULL on success, otherwise an error message
919  */
920 static void
921 put_migration_continuation (void *cls, int success, 
922                             struct GNUNET_TIME_Absolute min_expiration,
923                             const char *msg)
924 {
925   struct PutMigrationContext *pmc = cls;
926   struct GSF_ConnectedPeer *cp;
927   struct GNUNET_TIME_Relative mig_pause;
928   struct GSF_PeerPerformanceData *ppd;
929
930   if (NULL != datastore_put_load)
931   {
932     if (GNUNET_SYSERR != success)
933     {
934       GNUNET_LOAD_update (datastore_put_load, 
935                           GNUNET_TIME_absolute_get_duration (pmc->start).rel_value);
936     }
937     else
938     {
939       /* on queue failure / timeout, increase the put load dramatically */
940       GNUNET_LOAD_update (datastore_put_load, 
941                           GNUNET_TIME_UNIT_MINUTES.rel_value);
942     }
943   }
944   cp = GSF_peer_get_ (&pmc->origin);
945   if (GNUNET_OK == success)
946   {
947     if (NULL != cp)
948     {
949       ppd = GSF_get_peer_performance_data_ (cp);
950       ppd->migration_delay.rel_value /= 2;
951     }
952     GNUNET_free (pmc);
953     return;
954   }
955   if ( (GNUNET_NO == success) && 
956        (GNUNET_NO == pmc->requested) && 
957        (NULL != cp) )
958   {
959     ppd = GSF_get_peer_performance_data_ (cp);
960     if (min_expiration.abs_value > 0)
961     {
962       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
963                   "Asking to stop migration for %s because datastore is full\n",
964                   GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (min_expiration), GNUNET_YES));
965       GSF_block_peer_migration_ (cp, min_expiration);      
966     }
967     else
968     {
969       ppd->migration_delay = GNUNET_TIME_relative_max (GNUNET_TIME_UNIT_SECONDS,
970                                                        ppd->migration_delay);
971       ppd->migration_delay = GNUNET_TIME_relative_min (GNUNET_TIME_UNIT_HOURS,
972                                                        ppd->migration_delay);
973       mig_pause.rel_value = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
974                                                       ppd->migration_delay.rel_value);
975       ppd->migration_delay = GNUNET_TIME_relative_multiply (ppd->migration_delay, 2);
976       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
977                   "Replicated content already exists locally, asking to stop migration for %s\n",
978                   GNUNET_STRINGS_relative_time_to_string (mig_pause, GNUNET_YES));
979       GSF_block_peer_migration_ (cp, GNUNET_TIME_relative_to_absolute (mig_pause));
980     }
981   }
982   GNUNET_free (pmc);
983   GNUNET_STATISTICS_update (GSF_stats,
984                             gettext_noop ("# Datastore `PUT' failures"), 1,
985                             GNUNET_NO);
986 }
987
988
989 /**
990  * Test if the DATABASE (PUT) load on this peer is too high
991  * to even consider processing the query at
992  * all.
993  *
994  * @return GNUNET_YES if the load is too high to do anything (load high)
995  *         GNUNET_NO to process normally (load normal or low)
996  */
997 static int
998 test_put_load_too_high (uint32_t priority)
999 {
1000   double ld;
1001
1002   if (NULL == datastore_put_load)
1003     return GNUNET_NO;
1004   if (GNUNET_LOAD_get_average (datastore_put_load) < 50)
1005     return GNUNET_NO;           /* very fast */
1006   ld = GNUNET_LOAD_get_load (datastore_put_load);
1007   if (ld < 2.0 * (1 + priority))
1008     return GNUNET_NO;
1009   GNUNET_STATISTICS_update (GSF_stats,
1010                             gettext_noop
1011                             ("# storage requests dropped due to high load"), 1,
1012                             GNUNET_NO);
1013   return GNUNET_YES;
1014 }
1015
1016
1017 /**
1018  * Iterator called on each result obtained for a DHT
1019  * operation that expects a reply
1020  *
1021  * @param cls closure
1022  * @param exp when will this value expire
1023  * @param key key of the result
1024  * @param get_path peers on reply path (or NULL if not recorded)
1025  * @param get_path_length number of entries in get_path
1026  * @param put_path peers on the PUT path (or NULL if not recorded)
1027  * @param put_path_length number of entries in get_path
1028  * @param type type of the result
1029  * @param size number of bytes in data
1030  * @param data pointer to the result data
1031  */
1032 static void
1033 handle_dht_reply (void *cls, struct GNUNET_TIME_Absolute exp,
1034                   const struct GNUNET_HashCode * key,
1035                   const struct GNUNET_PeerIdentity *get_path,
1036                   unsigned int get_path_length,
1037                   const struct GNUNET_PeerIdentity *put_path,
1038                   unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
1039                   size_t size, const void *data)
1040 {
1041   struct GSF_PendingRequest *pr = cls;
1042   struct ProcessReplyClosure prq;
1043   struct PutMigrationContext *pmc;
1044
1045   GNUNET_STATISTICS_update (GSF_stats,
1046                             gettext_noop ("# Replies received from DHT"), 1,
1047                             GNUNET_NO);
1048   memset (&prq, 0, sizeof (prq));
1049   prq.data = data;
1050   prq.expiration = exp;
1051   /* do not allow migrated content to live longer than 1 year */
1052   prq.expiration = GNUNET_TIME_absolute_min (GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_YEARS),
1053                                              prq.expiration);
1054   prq.size = size;
1055   prq.type = type;
1056   process_reply (&prq, key, pr);
1057   if ((GNUNET_YES == active_to_migration) &&
1058       (GNUNET_NO == test_put_load_too_high (prq.priority)))
1059   {
1060     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1061                 "Replicating result for query `%s' with priority %u\n",
1062                 GNUNET_h2s (key), prq.priority);
1063     pmc = GNUNET_malloc (sizeof (struct PutMigrationContext));
1064     pmc->start = GNUNET_TIME_absolute_get ();
1065     pmc->requested = GNUNET_YES;
1066     if (NULL ==
1067         GNUNET_DATASTORE_put (GSF_dsh, 0, key, size, data, type, prq.priority,
1068                               1 /* anonymity */ ,
1069                               0 /* replication */ ,
1070                               exp, 1 + prq.priority, MAX_DATASTORE_QUEUE,
1071                               GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1072                               &put_migration_continuation, pmc))
1073     {
1074       put_migration_continuation (pmc, GNUNET_SYSERR, GNUNET_TIME_UNIT_ZERO_ABS, NULL);
1075     }
1076   }
1077 }
1078
1079
1080 /**
1081  * Consider looking up the data in the DHT (anonymity-level permitting).
1082  *
1083  * @param pr the pending request to process
1084  */
1085 void
1086 GSF_dht_lookup_ (struct GSF_PendingRequest *pr)
1087 {
1088   const void *xquery;
1089   size_t xquery_size;
1090   struct GNUNET_PeerIdentity pi;
1091   char buf[sizeof (struct GNUNET_HashCode) * 2] GNUNET_ALIGN;
1092
1093   if (0 != pr->public_data.anonymity_level)
1094     return;
1095   if (NULL != pr->gh)
1096   {
1097     GNUNET_DHT_get_stop (pr->gh);
1098     pr->gh = NULL;
1099   }
1100   xquery = NULL;
1101   xquery_size = 0;
1102   if (GNUNET_BLOCK_TYPE_FS_SBLOCK == pr->public_data.type)
1103   {
1104     xquery = buf;
1105     memcpy (buf, pr->public_data.namespace, sizeof (struct GNUNET_HashCode));
1106     xquery_size = sizeof (struct GNUNET_HashCode);
1107   }
1108   if (0 != (pr->public_data.options & GSF_PRO_FORWARD_ONLY))
1109   {
1110     GNUNET_assert (0 != pr->sender_pid);
1111     GNUNET_PEER_resolve (pr->sender_pid, &pi);
1112     memcpy (&buf[xquery_size], &pi, sizeof (struct GNUNET_PeerIdentity));
1113     xquery_size += sizeof (struct GNUNET_PeerIdentity);
1114   }
1115   pr->gh =
1116       GNUNET_DHT_get_start (GSF_dht, 
1117                             pr->public_data.type, &pr->public_data.query,
1118                             5 /* DEFAULT_GET_REPLICATION */ ,
1119                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
1120                             /* FIXME: can no longer pass pr->bf/pr->mingle... */
1121                             xquery, xquery_size, &handle_dht_reply, pr);
1122 }
1123
1124
1125 /**
1126  * Task that issues a warning if the datastore lookup takes too long.
1127  *
1128  * @param cls the 'struct GSF_PendingRequest'
1129  * @param tc task context
1130  */
1131 static void
1132 warn_delay_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1133 {
1134   struct GSF_PendingRequest *pr = cls;
1135
1136   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1137               _("Datastore lookup already took %s!\n"),
1138               GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (pr->qe_start), GNUNET_YES));
1139   pr->warn_task =
1140       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, &warn_delay_task,
1141                                     pr);
1142 }
1143
1144
1145 /**
1146  * Task that issues a warning if the datastore lookup takes too long.
1147  *
1148  * @param cls the 'struct GSF_PendingRequest'
1149  * @param tc task context
1150  */
1151 static void
1152 odc_warn_delay_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1153 {
1154   struct GSF_PendingRequest *pr = cls;
1155
1156   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1157               _("On-demand lookup already took %s!\n"),
1158               GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (pr->qe_start), GNUNET_YES));
1159   pr->warn_task =
1160       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1161                                     &odc_warn_delay_task, pr);
1162 }
1163
1164
1165 /**
1166  * We're processing (local) results for a search request
1167  * from another peer.  Pass applicable results to the
1168  * peer and if we are done either clean up (operation
1169  * complete) or forward to other peers (more results possible).
1170  *
1171  * @param cls our closure (struct PendingRequest)
1172  * @param key key for the content
1173  * @param size number of bytes in data
1174  * @param data content stored
1175  * @param type type of the content
1176  * @param priority priority of the content
1177  * @param anonymity anonymity-level for the content
1178  * @param expiration expiration time for the content
1179  * @param uid unique identifier for the datum;
1180  *        maybe 0 if no unique identifier is available
1181  */
1182 static void
1183 process_local_reply (void *cls, const struct GNUNET_HashCode * key, size_t size,
1184                      const void *data, enum GNUNET_BLOCK_Type type,
1185                      uint32_t priority, uint32_t anonymity,
1186                      struct GNUNET_TIME_Absolute expiration, uint64_t uid)
1187 {
1188   struct GSF_PendingRequest *pr = cls;
1189   GSF_LocalLookupContinuation cont;
1190   struct ProcessReplyClosure prq;
1191   struct GNUNET_HashCode query;
1192   unsigned int old_rf;
1193
1194   GNUNET_SCHEDULER_cancel (pr->warn_task);
1195   pr->warn_task = GNUNET_SCHEDULER_NO_TASK;
1196   if (NULL != pr->qe)
1197   {
1198     pr->qe = NULL;
1199     if (NULL == key)
1200     {
1201 #if INSANE_STATISTICS
1202       GNUNET_STATISTICS_update (GSF_stats,
1203                                 gettext_noop
1204                                 ("# Datastore lookups concluded (no results)"),
1205                                 1, GNUNET_NO);
1206 #endif
1207     }
1208     if (GNUNET_NO == pr->have_first_uid)
1209     {
1210       pr->first_uid = uid;
1211       pr->have_first_uid = 1;
1212     }
1213     else
1214     {
1215       if ((uid == pr->first_uid) && (key != NULL))
1216       {
1217         GNUNET_STATISTICS_update (GSF_stats,
1218                                   gettext_noop
1219                                   ("# Datastore lookups concluded (seen all)"),
1220                                   1, GNUNET_NO);
1221         key = NULL;             /* all replies seen! */
1222       }
1223       pr->have_first_uid++;
1224       if ((pr->have_first_uid > MAX_RESULTS) && (key != NULL))
1225       {
1226         GNUNET_STATISTICS_update (GSF_stats,
1227                                   gettext_noop
1228                                   ("# Datastore lookups aborted (more than MAX_RESULTS)"),
1229                                   1, GNUNET_NO);
1230         key = NULL;             /* all replies seen! */
1231       }
1232     }
1233   }
1234   if (NULL == key)
1235   {
1236     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1237                 "No further local responses available.\n");
1238 #if INSANE_STATISTICS
1239     if ((pr->public_data.type == GNUNET_BLOCK_TYPE_FS_DBLOCK) ||
1240         (pr->public_data.type == GNUNET_BLOCK_TYPE_FS_IBLOCK))
1241       GNUNET_STATISTICS_update (GSF_stats,
1242                                 gettext_noop
1243                                 ("# requested DBLOCK or IBLOCK not found"), 1,
1244                                 GNUNET_NO);
1245 #endif
1246     goto check_error_and_continue;
1247   }
1248   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1249               "Received reply for `%s' of type %d with UID %llu from datastore.\n",
1250               GNUNET_h2s (key), type, (unsigned long long) uid);
1251   if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
1252   {
1253     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1254                 "Found ONDEMAND block, performing on-demand encoding\n");
1255     GNUNET_STATISTICS_update (GSF_stats,
1256                               gettext_noop
1257                               ("# on-demand blocks matched requests"), 1,
1258                               GNUNET_NO);
1259     pr->qe_start = GNUNET_TIME_absolute_get ();
1260     pr->warn_task =
1261         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1262                                       &odc_warn_delay_task, pr);
1263     if (GNUNET_OK ==
1264         GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
1265                                           anonymity, expiration, uid,
1266                                           &process_local_reply, pr))
1267     {
1268       GNUNET_STATISTICS_update (GSF_stats,
1269                                 gettext_noop
1270                                 ("# on-demand lookups performed successfully"),
1271                                 1, GNUNET_NO);
1272       return;                   /* we're done */
1273     }
1274     GNUNET_STATISTICS_update (GSF_stats,
1275                               gettext_noop ("# on-demand lookups failed"), 1,
1276                               GNUNET_NO);
1277     GNUNET_SCHEDULER_cancel (pr->warn_task);
1278     pr->warn_task =
1279         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1280                                       &warn_delay_task, pr);
1281     pr->qe =
1282         GNUNET_DATASTORE_get_key (GSF_dsh, pr->local_result_offset - 1,
1283                                   &pr->public_data.query,
1284                                   pr->public_data.type ==
1285                                   GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1286                                   GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1287                                   (0 !=
1288                                    (GSF_PRO_PRIORITY_UNLIMITED &
1289                                     pr->public_data.options)) ? UINT_MAX : 1
1290                                   /* queue priority */ ,
1291                                   (0 !=
1292                                    (GSF_PRO_PRIORITY_UNLIMITED &
1293                                     pr->public_data.options)) ? UINT_MAX :
1294                                   datastore_queue_size
1295                                   /* max queue size */ ,
1296                                   GNUNET_TIME_UNIT_FOREVER_REL,
1297                                   &process_local_reply, pr);
1298     if (NULL != pr->qe)
1299       return;                   /* we're done */
1300     GNUNET_STATISTICS_update (GSF_stats,
1301                               gettext_noop
1302                               ("# Datastore lookups concluded (error queueing)"),
1303                               1, GNUNET_NO);
1304     goto check_error_and_continue;
1305   }
1306   old_rf = pr->public_data.results_found;
1307   memset (&prq, 0, sizeof (prq));
1308   prq.data = data;
1309   prq.expiration = expiration;
1310   prq.size = size;
1311   if (GNUNET_OK !=
1312       GNUNET_BLOCK_get_key (GSF_block_ctx, type, data, size, &query))
1313   {
1314     GNUNET_break (0);
1315     GNUNET_DATASTORE_remove (GSF_dsh, key, size, data, -1, -1,
1316                              GNUNET_TIME_UNIT_FOREVER_REL, NULL, NULL);
1317     pr->qe_start = GNUNET_TIME_absolute_get ();
1318     pr->warn_task =
1319         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1320                                       &warn_delay_task, pr);
1321     pr->qe =
1322         GNUNET_DATASTORE_get_key (GSF_dsh, pr->local_result_offset - 1,
1323                                   &pr->public_data.query,
1324                                   pr->public_data.type ==
1325                                   GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1326                                   GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1327                                   (0 !=
1328                                    (GSF_PRO_PRIORITY_UNLIMITED &
1329                                     pr->public_data.options)) ? UINT_MAX : 1
1330                                   /* queue priority */ ,
1331                                   (0 !=
1332                                    (GSF_PRO_PRIORITY_UNLIMITED &
1333                                     pr->public_data.options)) ? UINT_MAX :
1334                                   datastore_queue_size
1335                                   /* max queue size */ ,
1336                                   GNUNET_TIME_UNIT_FOREVER_REL,
1337                                   &process_local_reply, pr);
1338     if (pr->qe == NULL)
1339     {
1340       GNUNET_STATISTICS_update (GSF_stats,
1341                                 gettext_noop
1342                                 ("# Datastore lookups concluded (error queueing)"),
1343                                 1, GNUNET_NO);
1344       goto check_error_and_continue;
1345     }
1346     return;
1347   }
1348   prq.type = type;
1349   prq.priority = priority;
1350   prq.request_found = GNUNET_NO;
1351   prq.anonymity_level = anonymity;
1352   if ((old_rf == 0) && (pr->public_data.results_found == 0))
1353     GSF_update_datastore_delay_ (pr->public_data.start_time);
1354   process_reply (&prq, key, pr);
1355   pr->local_result = prq.eval;
1356   if (prq.eval == GNUNET_BLOCK_EVALUATION_OK_LAST)
1357   {
1358     GNUNET_STATISTICS_update (GSF_stats,
1359                               gettext_noop
1360                               ("# Datastore lookups concluded (found last result)"),
1361                               1, GNUNET_NO);
1362     goto check_error_and_continue;
1363   }
1364   if ((0 == (GSF_PRO_PRIORITY_UNLIMITED & pr->public_data.options)) &&
1365       ((GNUNET_YES == GSF_test_get_load_too_high_ (0)) ||
1366        (pr->public_data.results_found > 5 + 2 * pr->public_data.priority)))
1367   {
1368     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Load too high, done with request\n");
1369     GNUNET_STATISTICS_update (GSF_stats,
1370                               gettext_noop
1371                               ("# Datastore lookups concluded (load too high)"),
1372                               1, GNUNET_NO);
1373     goto check_error_and_continue;
1374   }
1375   pr->qe_start = GNUNET_TIME_absolute_get ();
1376   pr->warn_task =
1377       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, &warn_delay_task,
1378                                     pr);
1379   pr->qe =
1380       GNUNET_DATASTORE_get_key (GSF_dsh, pr->local_result_offset++,
1381                                 &pr->public_data.query,
1382                                 pr->public_data.type ==
1383                                 GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1384                                 GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1385                                 (0 !=
1386                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1387                                   public_data.options)) ? UINT_MAX : 1
1388                                 /* queue priority */ ,
1389                                 (0 !=
1390                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1391                                   public_data.options)) ? UINT_MAX :
1392                                 datastore_queue_size
1393                                 /* max queue size */ ,
1394                                 GNUNET_TIME_UNIT_FOREVER_REL,
1395                                 &process_local_reply, pr);
1396   /* check if we successfully queued another datastore request;
1397    * if so, return, otherwise call our continuation (if we have
1398    * any) */
1399 check_error_and_continue:
1400   if (NULL != pr->qe)
1401     return;
1402   if (GNUNET_SCHEDULER_NO_TASK != pr->warn_task)
1403   {
1404     GNUNET_SCHEDULER_cancel (pr->warn_task);
1405     pr->warn_task = GNUNET_SCHEDULER_NO_TASK;
1406   }
1407   if (NULL == (cont = pr->llc_cont))
1408     return;                     /* no continuation */
1409   pr->llc_cont = NULL;
1410   cont (pr->llc_cont_cls, pr, pr->local_result);
1411 }
1412
1413
1414 /**
1415  * Is the given target a legitimate peer for forwarding the given request?
1416  *
1417  * @param pr request
1418  * @param target
1419  * @return GNUNET_YES if this request could be forwarded to the given peer
1420  */
1421 int
1422 GSF_pending_request_test_target_ (struct GSF_PendingRequest *pr,
1423                                   const struct GNUNET_PeerIdentity *target)
1424 {
1425   struct GNUNET_PeerIdentity pi;
1426
1427   if (0 == pr->origin_pid)
1428     return GNUNET_YES;
1429   GNUNET_PEER_resolve (pr->origin_pid, &pi);
1430   return (0 ==
1431           memcmp (&pi, target,
1432                   sizeof (struct GNUNET_PeerIdentity))) ? GNUNET_NO :
1433       GNUNET_YES;
1434 }
1435
1436
1437 /**
1438  * Look up the request in the local datastore.
1439  *
1440  * @param pr the pending request to process
1441  * @param cont function to call at the end
1442  * @param cont_cls closure for cont
1443  */
1444 void
1445 GSF_local_lookup_ (struct GSF_PendingRequest *pr,
1446                    GSF_LocalLookupContinuation cont, void *cont_cls)
1447 {
1448   GNUNET_assert (NULL == pr->gh);
1449   GNUNET_assert (NULL == pr->llc_cont);
1450   pr->llc_cont = cont;
1451   pr->llc_cont_cls = cont_cls;
1452   pr->qe_start = GNUNET_TIME_absolute_get ();
1453   pr->warn_task =
1454       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, &warn_delay_task,
1455                                     pr);
1456 #if INSANE_STATISTICS
1457   GNUNET_STATISTICS_update (GSF_stats,
1458                             gettext_noop ("# Datastore lookups initiated"), 1,
1459                             GNUNET_NO);
1460 #endif
1461   pr->qe =
1462       GNUNET_DATASTORE_get_key (GSF_dsh, pr->local_result_offset++,
1463                                 &pr->public_data.query,
1464                                 pr->public_data.type ==
1465                                 GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1466                                 GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1467                                 (0 !=
1468                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1469                                   public_data.options)) ? UINT_MAX : 1
1470                                 /* queue priority */ ,
1471                                 (0 !=
1472                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1473                                   public_data.options)) ? UINT_MAX :
1474                                 datastore_queue_size
1475                                 /* max queue size */ ,
1476                                 GNUNET_TIME_UNIT_FOREVER_REL,
1477                                 &process_local_reply, pr);
1478   if (NULL != pr->qe)
1479     return;
1480   GNUNET_STATISTICS_update (GSF_stats,
1481                             gettext_noop
1482                             ("# Datastore lookups concluded (error queueing)"),
1483                             1, GNUNET_NO);
1484   GNUNET_SCHEDULER_cancel (pr->warn_task);
1485   pr->warn_task = GNUNET_SCHEDULER_NO_TASK;
1486   pr->llc_cont = NULL;
1487   if (NULL != cont)
1488     cont (cont_cls, pr, pr->local_result);
1489 }
1490
1491
1492
1493 /**
1494  * Handle P2P "CONTENT" message.  Checks that the message is
1495  * well-formed and then checks if there are any pending requests for
1496  * this content and possibly passes it on (to local clients or other
1497  * peers).  Does NOT perform migration (content caching at this peer).
1498  *
1499  * @param cp the other peer involved (sender or receiver, NULL
1500  *        for loopback messages where we are both sender and receiver)
1501  * @param message the actual message
1502  * @return GNUNET_OK if the message was well-formed,
1503  *         GNUNET_SYSERR if the message was malformed (close connection,
1504  *         do not cache under any circumstances)
1505  */
1506 int
1507 GSF_handle_p2p_content_ (struct GSF_ConnectedPeer *cp,
1508                          const struct GNUNET_MessageHeader *message)
1509 {
1510   const struct PutMessage *put;
1511   uint16_t msize;
1512   size_t dsize;
1513   enum GNUNET_BLOCK_Type type;
1514   struct GNUNET_TIME_Absolute expiration;
1515   struct GNUNET_HashCode query;
1516   struct ProcessReplyClosure prq;
1517   struct GNUNET_TIME_Relative block_time;
1518   double putl;
1519   struct PutMigrationContext *pmc;
1520
1521   msize = ntohs (message->size);
1522   if (msize < sizeof (struct PutMessage))
1523   {
1524     GNUNET_break_op (0);
1525     return GNUNET_SYSERR;
1526   }
1527   put = (const struct PutMessage *) message;
1528   dsize = msize - sizeof (struct PutMessage);
1529   type = ntohl (put->type);
1530   expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
1531   /* do not allow migrated content to live longer than 1 year */
1532   expiration = GNUNET_TIME_absolute_min (GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_YEARS),
1533                                          expiration);
1534   if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
1535     return GNUNET_SYSERR;
1536   if (GNUNET_OK !=
1537       GNUNET_BLOCK_get_key (GSF_block_ctx, type, &put[1], dsize, &query))
1538   {
1539     GNUNET_break_op (0);
1540     return GNUNET_SYSERR;
1541   }
1542   GNUNET_STATISTICS_update (GSF_stats,
1543                             gettext_noop ("# GAP PUT messages received"), 1,
1544                             GNUNET_NO);
1545   /* now, lookup 'query' */
1546   prq.data = (const void *) &put[1];
1547   prq.sender = cp;
1548   prq.size = dsize;
1549   prq.type = type;
1550   prq.expiration = expiration;
1551   prq.priority = 0;
1552   prq.anonymity_level = UINT32_MAX;
1553   prq.request_found = GNUNET_NO;
1554   GNUNET_CONTAINER_multihashmap_get_multiple (pr_map, &query, &process_reply,
1555                                               &prq);
1556   if (NULL != cp)
1557   {
1558     GSF_connected_peer_change_preference_ (cp,
1559                                            CONTENT_BANDWIDTH_VALUE +
1560                                            1000 * prq.priority);
1561     GSF_get_peer_performance_data_ (cp)->respect += prq.priority;
1562   }
1563   if ((GNUNET_YES == active_to_migration) &&
1564       (NULL != cp) &&
1565       (GNUNET_NO == test_put_load_too_high (prq.priority)))
1566   {
1567     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1568                 "Replicating result for query `%s' with priority %u\n",
1569                 GNUNET_h2s (&query), prq.priority);
1570     pmc = GNUNET_malloc (sizeof (struct PutMigrationContext));
1571     pmc->start = GNUNET_TIME_absolute_get ();
1572     pmc->requested = prq.request_found;
1573     GNUNET_assert (0 != GSF_get_peer_performance_data_ (cp)->pid);
1574     GNUNET_PEER_resolve (GSF_get_peer_performance_data_ (cp)->pid,
1575                          &pmc->origin);
1576     if (NULL ==
1577         GNUNET_DATASTORE_put (GSF_dsh, 0, &query, dsize, &put[1], type,
1578                               prq.priority, 1 /* anonymity */ ,
1579                               0 /* replication */ ,
1580                               expiration, 1 + prq.priority, MAX_DATASTORE_QUEUE,
1581                               GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1582                               &put_migration_continuation, pmc))
1583     {
1584       put_migration_continuation (pmc, GNUNET_SYSERR, GNUNET_TIME_UNIT_ZERO_ABS, NULL);
1585     }
1586   }
1587   else if (NULL != cp)
1588   {
1589     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1590                 "Choosing not to keep content `%s' (%d/%d)\n",
1591                 GNUNET_h2s (&query), active_to_migration,
1592                 test_put_load_too_high (prq.priority));
1593   }
1594   putl = GNUNET_LOAD_get_load (datastore_put_load);
1595   if ( (NULL != cp) && 
1596        (GNUNET_NO == prq.request_found) &&
1597        ( (GNUNET_YES != active_to_migration) ||
1598          (putl > 2.5 * (1 + prq.priority)) ) )
1599   {
1600     if (GNUNET_YES != active_to_migration)
1601       putl = 1.0 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 5);
1602     block_time =
1603         GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1604                                        5000 +
1605                                        GNUNET_CRYPTO_random_u32
1606                                        (GNUNET_CRYPTO_QUALITY_WEAK,
1607                                         (unsigned int) (60000 * putl * putl)));
1608     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
1609                 "Asking to stop migration for %llu ms because of load %f and events %d/%d\n",
1610                 (unsigned long long) block_time.rel_value,
1611                 putl,
1612                 active_to_migration,
1613                 (GNUNET_NO == prq.request_found));
1614     GSF_block_peer_migration_ (cp, GNUNET_TIME_relative_to_absolute (block_time));
1615   }
1616   return GNUNET_OK;
1617 }
1618
1619
1620 /**
1621  * Setup the subsystem.
1622  */
1623 void
1624 GSF_pending_request_init_ ()
1625 {
1626   unsigned long long dqs;
1627
1628   if (GNUNET_OK !=
1629       GNUNET_CONFIGURATION_get_value_number (GSF_cfg, "fs",
1630                                              "MAX_PENDING_REQUESTS",
1631                                              &max_pending_requests))
1632   {
1633     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_INFO,
1634                                "fs", "MAX_PENDING_REQUESTS");
1635   }
1636   if (GNUNET_OK !=
1637       GNUNET_CONFIGURATION_get_value_size (GSF_cfg, "fs", "DATASTORE_QUEUE_SIZE",
1638                                            &dqs))
1639   {
1640     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_INFO,
1641                                "fs", "DATASTORE_QUEUE_SIZE");
1642     dqs = 1024;
1643   }
1644   datastore_queue_size = (unsigned int) dqs;
1645
1646   active_to_migration =
1647       GNUNET_CONFIGURATION_get_value_yesno (GSF_cfg, "FS", "CONTENT_CACHING");
1648   datastore_put_load = GNUNET_LOAD_value_init (DATASTORE_LOAD_AUTODECLINE);
1649   pr_map = GNUNET_CONTAINER_multihashmap_create (32 * 1024, GNUNET_YES);
1650   requests_by_expiration_heap =
1651       GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1652 }
1653
1654
1655 /**
1656  * Shutdown the subsystem.
1657  */
1658 void
1659 GSF_pending_request_done_ ()
1660 {
1661   GNUNET_CONTAINER_multihashmap_iterate (pr_map, &clean_request, NULL);
1662   GNUNET_CONTAINER_multihashmap_destroy (pr_map);
1663   pr_map = NULL;
1664   GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
1665   requests_by_expiration_heap = NULL;
1666   GNUNET_LOAD_value_free (datastore_put_load);
1667   datastore_put_load = NULL;
1668 }
1669
1670
1671 /* end of gnunet-service-fs_pr.c */