-fix #2598
[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 (! GSF_request_plan_reference_get_last_transmission_ (pr->public_data.pr_head, 
823                                                              prq->sender, 
824                                                              &last_transmission))
825       last_transmission.abs_value = GNUNET_TIME_UNIT_FOREVER_ABS.abs_value;
826     /* pass on to other peers / local clients */
827     pr->rh (pr->rh_cls, prq->eval, pr, prq->anonymity_level, prq->expiration,
828             last_transmission, prq->type, prq->data, prq->size);
829     return GNUNET_YES;
830   case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
831 #if INSANE_STATISTICS
832     GNUNET_STATISTICS_update (GSF_stats,
833                               gettext_noop
834                               ("# duplicate replies discarded (bloomfilter)"),
835                               1, GNUNET_NO);
836 #endif
837     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
838                 "Duplicate response, discarding.\n");
839     return GNUNET_YES;          /* duplicate */
840   case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
841     return GNUNET_YES;          /* wrong namespace */
842   case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
843     GNUNET_break (0);
844     return GNUNET_YES;
845   case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
846     GNUNET_break (0);
847     return GNUNET_YES;
848   case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
849     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Unsupported block type %u\n"),
850                 prq->type);
851     return GNUNET_NO;
852   }
853   /* update bloomfilter */
854   GNUNET_CRYPTO_hash (prq->data, prq->size, &chash);
855   GSF_pending_request_update_ (pr, &chash, 1);
856   if (NULL == prq->sender)
857   {
858     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
859                 "Found result for query `%s' in local datastore\n",
860                 GNUNET_h2s (key));
861     GNUNET_STATISTICS_update (GSF_stats,
862                               gettext_noop ("# results found locally"), 1,
863                               GNUNET_NO);
864   }
865   else
866   {
867     GSF_dht_lookup_ (pr);
868   }
869   prq->priority += pr->public_data.original_priority;
870   pr->public_data.priority = 0;
871   pr->public_data.original_priority = 0;
872   pr->public_data.results_found++;
873   prq->request_found = GNUNET_YES;
874   /* finally, pass on to other peer / local client */
875   if (! GSF_request_plan_reference_get_last_transmission_ (pr->public_data.pr_head,
876                                                            prq->sender, 
877                                                            &last_transmission))
878     last_transmission.abs_value = GNUNET_TIME_UNIT_FOREVER_ABS.abs_value;
879   pr->rh (pr->rh_cls, prq->eval, pr, 
880           prq->anonymity_level, prq->expiration,
881           last_transmission, prq->type, prq->data, prq->size);
882   return GNUNET_YES;
883 }
884
885
886 /**
887  * Context for the 'put_migration_continuation'.
888  */
889 struct PutMigrationContext
890 {
891
892   /**
893    * Start time for the operation.
894    */
895   struct GNUNET_TIME_Absolute start;
896
897   /**
898    * Request origin.
899    */
900   struct GNUNET_PeerIdentity origin;
901
902   /**
903    * GNUNET_YES if we had a matching request for this block,
904    * GNUNET_NO if not.
905    */
906   int requested;
907 };
908
909
910 /**
911  * Continuation called to notify client about result of the
912  * operation.
913  *
914  * @param cls closure
915  * @param success GNUNET_SYSERR on failure
916  * @param min_expiration minimum expiration time required for content to be stored
917  * @param msg NULL on success, otherwise an error message
918  */
919 static void
920 put_migration_continuation (void *cls, int success, 
921                             struct GNUNET_TIME_Absolute min_expiration,
922                             const char *msg)
923 {
924   struct PutMigrationContext *pmc = cls;
925   struct GSF_ConnectedPeer *cp;
926   struct GNUNET_TIME_Relative mig_pause;
927   struct GSF_PeerPerformanceData *ppd;
928
929   if (NULL != datastore_put_load)
930   {
931     if (GNUNET_SYSERR != success)
932     {
933       GNUNET_LOAD_update (datastore_put_load, 
934                           GNUNET_TIME_absolute_get_duration (pmc->start).rel_value);
935     }
936     else
937     {
938       /* on queue failure / timeout, increase the put load dramatically */
939       GNUNET_LOAD_update (datastore_put_load, 
940                           GNUNET_TIME_UNIT_MINUTES.rel_value);
941     }
942   }
943   cp = GSF_peer_get_ (&pmc->origin);
944   if (GNUNET_OK == success)
945   {
946     if (NULL != cp)
947     {
948       ppd = GSF_get_peer_performance_data_ (cp);
949       ppd->migration_delay.rel_value /= 2;
950     }
951     GNUNET_free (pmc);
952     return;
953   }
954   if ( (GNUNET_NO == success) && 
955        (GNUNET_NO == pmc->requested) && 
956        (NULL != cp) )
957   {
958     ppd = GSF_get_peer_performance_data_ (cp);
959     if (min_expiration.abs_value > 0)
960     {
961       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
962                   "Asking to stop migration for %s because datastore is full\n",
963                   GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (min_expiration), GNUNET_YES));
964       GSF_block_peer_migration_ (cp, min_expiration);      
965     }
966     else
967     {
968       ppd->migration_delay = GNUNET_TIME_relative_max (GNUNET_TIME_UNIT_SECONDS,
969                                                        ppd->migration_delay);
970       ppd->migration_delay = GNUNET_TIME_relative_min (GNUNET_TIME_UNIT_HOURS,
971                                                        ppd->migration_delay);
972       mig_pause.rel_value = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
973                                                       ppd->migration_delay.rel_value);
974       ppd->migration_delay = GNUNET_TIME_relative_multiply (ppd->migration_delay, 2);
975       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
976                   "Replicated content already exists locally, asking to stop migration for %s\n",
977                   GNUNET_STRINGS_relative_time_to_string (mig_pause, GNUNET_YES));
978       GSF_block_peer_migration_ (cp, GNUNET_TIME_relative_to_absolute (mig_pause));
979     }
980   }
981   GNUNET_free (pmc);
982   GNUNET_STATISTICS_update (GSF_stats,
983                             gettext_noop ("# Datastore `PUT' failures"), 1,
984                             GNUNET_NO);
985 }
986
987
988 /**
989  * Test if the DATABASE (PUT) load on this peer is too high
990  * to even consider processing the query at
991  * all.
992  *
993  * @return GNUNET_YES if the load is too high to do anything (load high)
994  *         GNUNET_NO to process normally (load normal or low)
995  */
996 static int
997 test_put_load_too_high (uint32_t priority)
998 {
999   double ld;
1000
1001   if (NULL == datastore_put_load)
1002     return GNUNET_NO;
1003   if (GNUNET_LOAD_get_average (datastore_put_load) < 50)
1004     return GNUNET_NO;           /* very fast */
1005   ld = GNUNET_LOAD_get_load (datastore_put_load);
1006   if (ld < 2.0 * (1 + priority))
1007     return GNUNET_NO;
1008   GNUNET_STATISTICS_update (GSF_stats,
1009                             gettext_noop
1010                             ("# storage requests dropped due to high load"), 1,
1011                             GNUNET_NO);
1012   return GNUNET_YES;
1013 }
1014
1015
1016 /**
1017  * Iterator called on each result obtained for a DHT
1018  * operation that expects a reply
1019  *
1020  * @param cls closure
1021  * @param exp when will this value expire
1022  * @param key key of the result
1023  * @param get_path peers on reply path (or NULL if not recorded)
1024  * @param get_path_length number of entries in get_path
1025  * @param put_path peers on the PUT path (or NULL if not recorded)
1026  * @param put_path_length number of entries in get_path
1027  * @param type type of the result
1028  * @param size number of bytes in data
1029  * @param data pointer to the result data
1030  */
1031 static void
1032 handle_dht_reply (void *cls, struct GNUNET_TIME_Absolute exp,
1033                   const struct GNUNET_HashCode * key,
1034                   const struct GNUNET_PeerIdentity *get_path,
1035                   unsigned int get_path_length,
1036                   const struct GNUNET_PeerIdentity *put_path,
1037                   unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
1038                   size_t size, const void *data)
1039 {
1040   struct GSF_PendingRequest *pr = cls;
1041   struct ProcessReplyClosure prq;
1042   struct PutMigrationContext *pmc;
1043
1044   GNUNET_STATISTICS_update (GSF_stats,
1045                             gettext_noop ("# Replies received from DHT"), 1,
1046                             GNUNET_NO);
1047   memset (&prq, 0, sizeof (prq));
1048   prq.data = data;
1049   prq.expiration = exp;
1050   /* do not allow migrated content to live longer than 1 year */
1051   prq.expiration = GNUNET_TIME_absolute_min (GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_YEARS),
1052                                              prq.expiration);
1053   prq.size = size;
1054   prq.type = type;
1055   process_reply (&prq, key, pr);
1056   if ((GNUNET_YES == active_to_migration) &&
1057       (GNUNET_NO == test_put_load_too_high (prq.priority)))
1058   {
1059     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1060                 "Replicating result for query `%s' with priority %u\n",
1061                 GNUNET_h2s (key), prq.priority);
1062     pmc = GNUNET_malloc (sizeof (struct PutMigrationContext));
1063     pmc->start = GNUNET_TIME_absolute_get ();
1064     pmc->requested = GNUNET_YES;
1065     if (NULL ==
1066         GNUNET_DATASTORE_put (GSF_dsh, 0, key, size, data, type, prq.priority,
1067                               1 /* anonymity */ ,
1068                               0 /* replication */ ,
1069                               exp, 1 + prq.priority, MAX_DATASTORE_QUEUE,
1070                               GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1071                               &put_migration_continuation, pmc))
1072     {
1073       put_migration_continuation (pmc, GNUNET_SYSERR, GNUNET_TIME_UNIT_ZERO_ABS, NULL);
1074     }
1075   }
1076 }
1077
1078
1079 /**
1080  * Consider looking up the data in the DHT (anonymity-level permitting).
1081  *
1082  * @param pr the pending request to process
1083  */
1084 void
1085 GSF_dht_lookup_ (struct GSF_PendingRequest *pr)
1086 {
1087   const void *xquery;
1088   size_t xquery_size;
1089   struct GNUNET_PeerIdentity pi;
1090   char buf[sizeof (struct GNUNET_HashCode) * 2] GNUNET_ALIGN;
1091
1092   if (0 != pr->public_data.anonymity_level)
1093     return;
1094   if (NULL != pr->gh)
1095   {
1096     GNUNET_DHT_get_stop (pr->gh);
1097     pr->gh = NULL;
1098   }
1099   xquery = NULL;
1100   xquery_size = 0;
1101   if (GNUNET_BLOCK_TYPE_FS_SBLOCK == pr->public_data.type)
1102   {
1103     xquery = buf;
1104     memcpy (buf, pr->public_data.namespace, sizeof (struct GNUNET_HashCode));
1105     xquery_size = sizeof (struct GNUNET_HashCode);
1106   }
1107   if (0 != (pr->public_data.options & GSF_PRO_FORWARD_ONLY))
1108   {
1109     GNUNET_assert (0 != pr->sender_pid);
1110     GNUNET_PEER_resolve (pr->sender_pid, &pi);
1111     memcpy (&buf[xquery_size], &pi, sizeof (struct GNUNET_PeerIdentity));
1112     xquery_size += sizeof (struct GNUNET_PeerIdentity);
1113   }
1114   pr->gh =
1115       GNUNET_DHT_get_start (GSF_dht, 
1116                             pr->public_data.type, &pr->public_data.query,
1117                             5 /* DEFAULT_GET_REPLICATION */ ,
1118                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
1119                             /* FIXME: can no longer pass pr->bf/pr->mingle... */
1120                             xquery, xquery_size, &handle_dht_reply, pr);
1121 }
1122
1123
1124 /**
1125  * Task that issues a warning if the datastore lookup takes too long.
1126  *
1127  * @param cls the 'struct GSF_PendingRequest'
1128  * @param tc task context
1129  */
1130 static void
1131 warn_delay_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1132 {
1133   struct GSF_PendingRequest *pr = cls;
1134
1135   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1136               _("Datastore lookup already took %s!\n"),
1137               GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (pr->qe_start), GNUNET_YES));
1138   pr->warn_task =
1139       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, &warn_delay_task,
1140                                     pr);
1141 }
1142
1143
1144 /**
1145  * Task that issues a warning if the datastore lookup takes too long.
1146  *
1147  * @param cls the 'struct GSF_PendingRequest'
1148  * @param tc task context
1149  */
1150 static void
1151 odc_warn_delay_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1152 {
1153   struct GSF_PendingRequest *pr = cls;
1154
1155   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1156               _("On-demand lookup already took %s!\n"),
1157               GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (pr->qe_start), GNUNET_YES));
1158   pr->warn_task =
1159       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1160                                     &odc_warn_delay_task, pr);
1161 }
1162
1163
1164 /**
1165  * We're processing (local) results for a search request
1166  * from another peer.  Pass applicable results to the
1167  * peer and if we are done either clean up (operation
1168  * complete) or forward to other peers (more results possible).
1169  *
1170  * @param cls our closure (struct PendingRequest)
1171  * @param key key for the content
1172  * @param size number of bytes in data
1173  * @param data content stored
1174  * @param type type of the content
1175  * @param priority priority of the content
1176  * @param anonymity anonymity-level for the content
1177  * @param expiration expiration time for the content
1178  * @param uid unique identifier for the datum;
1179  *        maybe 0 if no unique identifier is available
1180  */
1181 static void
1182 process_local_reply (void *cls, const struct GNUNET_HashCode * key, size_t size,
1183                      const void *data, enum GNUNET_BLOCK_Type type,
1184                      uint32_t priority, uint32_t anonymity,
1185                      struct GNUNET_TIME_Absolute expiration, uint64_t uid)
1186 {
1187   struct GSF_PendingRequest *pr = cls;
1188   GSF_LocalLookupContinuation cont;
1189   struct ProcessReplyClosure prq;
1190   struct GNUNET_HashCode query;
1191   unsigned int old_rf;
1192
1193   GNUNET_SCHEDULER_cancel (pr->warn_task);
1194   pr->warn_task = GNUNET_SCHEDULER_NO_TASK;
1195   if (NULL != pr->qe)
1196   {
1197     pr->qe = NULL;
1198     if (NULL == key)
1199     {
1200 #if INSANE_STATISTICS
1201       GNUNET_STATISTICS_update (GSF_stats,
1202                                 gettext_noop
1203                                 ("# Datastore lookups concluded (no results)"),
1204                                 1, GNUNET_NO);
1205 #endif
1206     }
1207     if (GNUNET_NO == pr->have_first_uid)
1208     {
1209       pr->first_uid = uid;
1210       pr->have_first_uid = 1;
1211     }
1212     else
1213     {
1214       if ((uid == pr->first_uid) && (key != NULL))
1215       {
1216         GNUNET_STATISTICS_update (GSF_stats,
1217                                   gettext_noop
1218                                   ("# Datastore lookups concluded (seen all)"),
1219                                   1, GNUNET_NO);
1220         key = NULL;             /* all replies seen! */
1221       }
1222       pr->have_first_uid++;
1223       if ((pr->have_first_uid > MAX_RESULTS) && (key != NULL))
1224       {
1225         GNUNET_STATISTICS_update (GSF_stats,
1226                                   gettext_noop
1227                                   ("# Datastore lookups aborted (more than MAX_RESULTS)"),
1228                                   1, GNUNET_NO);
1229         key = NULL;             /* all replies seen! */
1230       }
1231     }
1232   }
1233   if (NULL == key)
1234   {
1235     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1236                 "No further local responses available.\n");
1237 #if INSANE_STATISTICS
1238     if ((pr->public_data.type == GNUNET_BLOCK_TYPE_FS_DBLOCK) ||
1239         (pr->public_data.type == GNUNET_BLOCK_TYPE_FS_IBLOCK))
1240       GNUNET_STATISTICS_update (GSF_stats,
1241                                 gettext_noop
1242                                 ("# requested DBLOCK or IBLOCK not found"), 1,
1243                                 GNUNET_NO);
1244 #endif
1245     goto check_error_and_continue;
1246   }
1247   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1248               "Received reply for `%s' of type %d with UID %llu from datastore.\n",
1249               GNUNET_h2s (key), type, (unsigned long long) uid);
1250   if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
1251   {
1252     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1253                 "Found ONDEMAND block, performing on-demand encoding\n");
1254     GNUNET_STATISTICS_update (GSF_stats,
1255                               gettext_noop
1256                               ("# on-demand blocks matched requests"), 1,
1257                               GNUNET_NO);
1258     pr->qe_start = GNUNET_TIME_absolute_get ();
1259     pr->warn_task =
1260         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1261                                       &odc_warn_delay_task, pr);
1262     if (GNUNET_OK ==
1263         GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
1264                                           anonymity, expiration, uid,
1265                                           &process_local_reply, pr))
1266     {
1267       GNUNET_STATISTICS_update (GSF_stats,
1268                                 gettext_noop
1269                                 ("# on-demand lookups performed successfully"),
1270                                 1, GNUNET_NO);
1271       return;                   /* we're done */
1272     }
1273     GNUNET_STATISTICS_update (GSF_stats,
1274                               gettext_noop ("# on-demand lookups failed"), 1,
1275                               GNUNET_NO);
1276     GNUNET_SCHEDULER_cancel (pr->warn_task);
1277     pr->warn_task =
1278         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1279                                       &warn_delay_task, pr);
1280     pr->qe =
1281         GNUNET_DATASTORE_get_key (GSF_dsh, pr->local_result_offset - 1,
1282                                   &pr->public_data.query,
1283                                   pr->public_data.type ==
1284                                   GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1285                                   GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1286                                   (0 !=
1287                                    (GSF_PRO_PRIORITY_UNLIMITED &
1288                                     pr->public_data.options)) ? UINT_MAX : 1
1289                                   /* queue priority */ ,
1290                                   (0 !=
1291                                    (GSF_PRO_PRIORITY_UNLIMITED &
1292                                     pr->public_data.options)) ? UINT_MAX :
1293                                   datastore_queue_size
1294                                   /* max queue size */ ,
1295                                   GNUNET_TIME_UNIT_FOREVER_REL,
1296                                   &process_local_reply, pr);
1297     if (NULL != pr->qe)
1298       return;                   /* we're done */
1299     GNUNET_STATISTICS_update (GSF_stats,
1300                               gettext_noop
1301                               ("# Datastore lookups concluded (error queueing)"),
1302                               1, GNUNET_NO);
1303     goto check_error_and_continue;
1304   }
1305   old_rf = pr->public_data.results_found;
1306   memset (&prq, 0, sizeof (prq));
1307   prq.data = data;
1308   prq.expiration = expiration;
1309   prq.size = size;
1310   if (GNUNET_OK !=
1311       GNUNET_BLOCK_get_key (GSF_block_ctx, type, data, size, &query))
1312   {
1313     GNUNET_break (0);
1314     GNUNET_DATASTORE_remove (GSF_dsh, key, size, data, -1, -1,
1315                              GNUNET_TIME_UNIT_FOREVER_REL, NULL, NULL);
1316     pr->qe_start = GNUNET_TIME_absolute_get ();
1317     pr->warn_task =
1318         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1319                                       &warn_delay_task, pr);
1320     pr->qe =
1321         GNUNET_DATASTORE_get_key (GSF_dsh, pr->local_result_offset - 1,
1322                                   &pr->public_data.query,
1323                                   pr->public_data.type ==
1324                                   GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1325                                   GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1326                                   (0 !=
1327                                    (GSF_PRO_PRIORITY_UNLIMITED &
1328                                     pr->public_data.options)) ? UINT_MAX : 1
1329                                   /* queue priority */ ,
1330                                   (0 !=
1331                                    (GSF_PRO_PRIORITY_UNLIMITED &
1332                                     pr->public_data.options)) ? UINT_MAX :
1333                                   datastore_queue_size
1334                                   /* max queue size */ ,
1335                                   GNUNET_TIME_UNIT_FOREVER_REL,
1336                                   &process_local_reply, pr);
1337     if (pr->qe == NULL)
1338     {
1339       GNUNET_STATISTICS_update (GSF_stats,
1340                                 gettext_noop
1341                                 ("# Datastore lookups concluded (error queueing)"),
1342                                 1, GNUNET_NO);
1343       goto check_error_and_continue;
1344     }
1345     return;
1346   }
1347   prq.type = type;
1348   prq.priority = priority;
1349   prq.request_found = GNUNET_NO;
1350   prq.anonymity_level = anonymity;
1351   if ((old_rf == 0) && (pr->public_data.results_found == 0))
1352     GSF_update_datastore_delay_ (pr->public_data.start_time);
1353   process_reply (&prq, key, pr);
1354   pr->local_result = prq.eval;
1355   if (prq.eval == GNUNET_BLOCK_EVALUATION_OK_LAST)
1356   {
1357     GNUNET_STATISTICS_update (GSF_stats,
1358                               gettext_noop
1359                               ("# Datastore lookups concluded (found last result)"),
1360                               1, GNUNET_NO);
1361     goto check_error_and_continue;
1362   }
1363   if ((0 == (GSF_PRO_PRIORITY_UNLIMITED & pr->public_data.options)) &&
1364       ((GNUNET_YES == GSF_test_get_load_too_high_ (0)) ||
1365        (pr->public_data.results_found > 5 + 2 * pr->public_data.priority)))
1366   {
1367     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Load too high, done with request\n");
1368     GNUNET_STATISTICS_update (GSF_stats,
1369                               gettext_noop
1370                               ("# Datastore lookups concluded (load too high)"),
1371                               1, GNUNET_NO);
1372     goto check_error_and_continue;
1373   }
1374   pr->qe_start = GNUNET_TIME_absolute_get ();
1375   pr->warn_task =
1376       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, &warn_delay_task,
1377                                     pr);
1378   pr->qe =
1379       GNUNET_DATASTORE_get_key (GSF_dsh, pr->local_result_offset++,
1380                                 &pr->public_data.query,
1381                                 pr->public_data.type ==
1382                                 GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1383                                 GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1384                                 (0 !=
1385                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1386                                   public_data.options)) ? UINT_MAX : 1
1387                                 /* queue priority */ ,
1388                                 (0 !=
1389                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1390                                   public_data.options)) ? UINT_MAX :
1391                                 datastore_queue_size
1392                                 /* max queue size */ ,
1393                                 GNUNET_TIME_UNIT_FOREVER_REL,
1394                                 &process_local_reply, pr);
1395   /* check if we successfully queued another datastore request;
1396    * if so, return, otherwise call our continuation (if we have
1397    * any) */
1398 check_error_and_continue:
1399   if (NULL != pr->qe)
1400     return;
1401   if (GNUNET_SCHEDULER_NO_TASK != pr->warn_task)
1402   {
1403     GNUNET_SCHEDULER_cancel (pr->warn_task);
1404     pr->warn_task = GNUNET_SCHEDULER_NO_TASK;
1405   }
1406   if (NULL == (cont = pr->llc_cont))
1407     return;                     /* no continuation */
1408   pr->llc_cont = NULL;
1409   cont (pr->llc_cont_cls, pr, pr->local_result);
1410 }
1411
1412
1413 /**
1414  * Is the given target a legitimate peer for forwarding the given request?
1415  *
1416  * @param pr request
1417  * @param target
1418  * @return GNUNET_YES if this request could be forwarded to the given peer
1419  */
1420 int
1421 GSF_pending_request_test_target_ (struct GSF_PendingRequest *pr,
1422                                   const struct GNUNET_PeerIdentity *target)
1423 {
1424   struct GNUNET_PeerIdentity pi;
1425
1426   if (0 == pr->origin_pid)
1427     return GNUNET_YES;
1428   GNUNET_PEER_resolve (pr->origin_pid, &pi);
1429   return (0 ==
1430           memcmp (&pi, target,
1431                   sizeof (struct GNUNET_PeerIdentity))) ? GNUNET_NO :
1432       GNUNET_YES;
1433 }
1434
1435
1436 /**
1437  * Look up the request in the local datastore.
1438  *
1439  * @param pr the pending request to process
1440  * @param cont function to call at the end
1441  * @param cont_cls closure for cont
1442  */
1443 void
1444 GSF_local_lookup_ (struct GSF_PendingRequest *pr,
1445                    GSF_LocalLookupContinuation cont, void *cont_cls)
1446 {
1447   GNUNET_assert (NULL == pr->gh);
1448   GNUNET_assert (NULL == pr->llc_cont);
1449   pr->llc_cont = cont;
1450   pr->llc_cont_cls = cont_cls;
1451   pr->qe_start = GNUNET_TIME_absolute_get ();
1452   pr->warn_task =
1453       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, &warn_delay_task,
1454                                     pr);
1455 #if INSANE_STATISTICS
1456   GNUNET_STATISTICS_update (GSF_stats,
1457                             gettext_noop ("# Datastore lookups initiated"), 1,
1458                             GNUNET_NO);
1459 #endif
1460   pr->qe =
1461       GNUNET_DATASTORE_get_key (GSF_dsh, pr->local_result_offset++,
1462                                 &pr->public_data.query,
1463                                 pr->public_data.type ==
1464                                 GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1465                                 GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1466                                 (0 !=
1467                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1468                                   public_data.options)) ? UINT_MAX : 1
1469                                 /* queue priority */ ,
1470                                 (0 !=
1471                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1472                                   public_data.options)) ? UINT_MAX :
1473                                 datastore_queue_size
1474                                 /* max queue size */ ,
1475                                 GNUNET_TIME_UNIT_FOREVER_REL,
1476                                 &process_local_reply, pr);
1477   if (NULL != pr->qe)
1478     return;
1479   GNUNET_STATISTICS_update (GSF_stats,
1480                             gettext_noop
1481                             ("# Datastore lookups concluded (error queueing)"),
1482                             1, GNUNET_NO);
1483   GNUNET_SCHEDULER_cancel (pr->warn_task);
1484   pr->warn_task = GNUNET_SCHEDULER_NO_TASK;
1485   pr->llc_cont = NULL;
1486   if (NULL != cont)
1487     cont (cont_cls, pr, pr->local_result);
1488 }
1489
1490
1491
1492 /**
1493  * Handle P2P "CONTENT" message.  Checks that the message is
1494  * well-formed and then checks if there are any pending requests for
1495  * this content and possibly passes it on (to local clients or other
1496  * peers).  Does NOT perform migration (content caching at this peer).
1497  *
1498  * @param cp the other peer involved (sender or receiver, NULL
1499  *        for loopback messages where we are both sender and receiver)
1500  * @param message the actual message
1501  * @return GNUNET_OK if the message was well-formed,
1502  *         GNUNET_SYSERR if the message was malformed (close connection,
1503  *         do not cache under any circumstances)
1504  */
1505 int
1506 GSF_handle_p2p_content_ (struct GSF_ConnectedPeer *cp,
1507                          const struct GNUNET_MessageHeader *message)
1508 {
1509   const struct PutMessage *put;
1510   uint16_t msize;
1511   size_t dsize;
1512   enum GNUNET_BLOCK_Type type;
1513   struct GNUNET_TIME_Absolute expiration;
1514   struct GNUNET_HashCode query;
1515   struct ProcessReplyClosure prq;
1516   struct GNUNET_TIME_Relative block_time;
1517   double putl;
1518   struct PutMigrationContext *pmc;
1519
1520   msize = ntohs (message->size);
1521   if (msize < sizeof (struct PutMessage))
1522   {
1523     GNUNET_break_op (0);
1524     return GNUNET_SYSERR;
1525   }
1526   put = (const struct PutMessage *) message;
1527   dsize = msize - sizeof (struct PutMessage);
1528   type = ntohl (put->type);
1529   expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
1530   /* do not allow migrated content to live longer than 1 year */
1531   expiration = GNUNET_TIME_absolute_min (GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_YEARS),
1532                                          expiration);
1533   if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
1534     return GNUNET_SYSERR;
1535   if (GNUNET_OK !=
1536       GNUNET_BLOCK_get_key (GSF_block_ctx, type, &put[1], dsize, &query))
1537   {
1538     GNUNET_break_op (0);
1539     return GNUNET_SYSERR;
1540   }
1541   GNUNET_STATISTICS_update (GSF_stats,
1542                             gettext_noop ("# GAP PUT messages received"), 1,
1543                             GNUNET_NO);
1544   /* now, lookup 'query' */
1545   prq.data = (const void *) &put[1];
1546   prq.sender = cp;
1547   prq.size = dsize;
1548   prq.type = type;
1549   prq.expiration = expiration;
1550   prq.priority = 0;
1551   prq.anonymity_level = UINT32_MAX;
1552   prq.request_found = GNUNET_NO;
1553   GNUNET_CONTAINER_multihashmap_get_multiple (pr_map, &query, &process_reply,
1554                                               &prq);
1555   if (NULL != cp)
1556   {
1557     GSF_connected_peer_change_preference_ (cp,
1558                                            CONTENT_BANDWIDTH_VALUE +
1559                                            1000 * prq.priority);
1560     GSF_get_peer_performance_data_ (cp)->respect += prq.priority;
1561   }
1562   if ((GNUNET_YES == active_to_migration) &&
1563       (NULL != cp) &&
1564       (GNUNET_NO == test_put_load_too_high (prq.priority)))
1565   {
1566     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1567                 "Replicating result for query `%s' with priority %u\n",
1568                 GNUNET_h2s (&query), prq.priority);
1569     pmc = GNUNET_malloc (sizeof (struct PutMigrationContext));
1570     pmc->start = GNUNET_TIME_absolute_get ();
1571     pmc->requested = prq.request_found;
1572     GNUNET_assert (0 != GSF_get_peer_performance_data_ (cp)->pid);
1573     GNUNET_PEER_resolve (GSF_get_peer_performance_data_ (cp)->pid,
1574                          &pmc->origin);
1575     if (NULL ==
1576         GNUNET_DATASTORE_put (GSF_dsh, 0, &query, dsize, &put[1], type,
1577                               prq.priority, 1 /* anonymity */ ,
1578                               0 /* replication */ ,
1579                               expiration, 1 + prq.priority, MAX_DATASTORE_QUEUE,
1580                               GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1581                               &put_migration_continuation, pmc))
1582     {
1583       put_migration_continuation (pmc, GNUNET_SYSERR, GNUNET_TIME_UNIT_ZERO_ABS, NULL);
1584     }
1585   }
1586   else if (NULL != cp)
1587   {
1588     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1589                 "Choosing not to keep content `%s' (%d/%d)\n",
1590                 GNUNET_h2s (&query), active_to_migration,
1591                 test_put_load_too_high (prq.priority));
1592   }
1593   putl = GNUNET_LOAD_get_load (datastore_put_load);
1594   if ( (NULL != cp) && 
1595        (GNUNET_NO == prq.request_found) &&
1596        ( (GNUNET_YES != active_to_migration) ||
1597          (putl > 2.5 * (1 + prq.priority)) ) )
1598   {
1599     if (GNUNET_YES != active_to_migration)
1600       putl = 1.0 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 5);
1601     block_time =
1602         GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1603                                        5000 +
1604                                        GNUNET_CRYPTO_random_u32
1605                                        (GNUNET_CRYPTO_QUALITY_WEAK,
1606                                         (unsigned int) (60000 * putl * putl)));
1607     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
1608                 "Asking to stop migration for %llu ms because of load %f and events %d/%d\n",
1609                 (unsigned long long) block_time.rel_value,
1610                 putl,
1611                 active_to_migration,
1612                 (GNUNET_NO == prq.request_found));
1613     GSF_block_peer_migration_ (cp, GNUNET_TIME_relative_to_absolute (block_time));
1614   }
1615   return GNUNET_OK;
1616 }
1617
1618
1619 /**
1620  * Setup the subsystem.
1621  */
1622 void
1623 GSF_pending_request_init_ ()
1624 {
1625   unsigned long long dqs;
1626
1627   if (GNUNET_OK !=
1628       GNUNET_CONFIGURATION_get_value_number (GSF_cfg, "fs",
1629                                              "MAX_PENDING_REQUESTS",
1630                                              &max_pending_requests))
1631   {
1632     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_INFO,
1633                                "fs", "MAX_PENDING_REQUESTS");
1634   }
1635   if (GNUNET_OK !=
1636       GNUNET_CONFIGURATION_get_value_size (GSF_cfg, "fs", "DATASTORE_QUEUE_SIZE",
1637                                            &dqs))
1638   {
1639     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_INFO,
1640                                "fs", "DATASTORE_QUEUE_SIZE");
1641     dqs = 1024;
1642   }
1643   datastore_queue_size = (unsigned int) dqs;
1644
1645   active_to_migration =
1646       GNUNET_CONFIGURATION_get_value_yesno (GSF_cfg, "FS", "CONTENT_CACHING");
1647   datastore_put_load = GNUNET_LOAD_value_init (DATASTORE_LOAD_AUTODECLINE);
1648   pr_map = GNUNET_CONTAINER_multihashmap_create (32 * 1024, GNUNET_YES);
1649   requests_by_expiration_heap =
1650       GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1651 }
1652
1653
1654 /**
1655  * Shutdown the subsystem.
1656  */
1657 void
1658 GSF_pending_request_done_ ()
1659 {
1660   GNUNET_CONTAINER_multihashmap_iterate (pr_map, &clean_request, NULL);
1661   GNUNET_CONTAINER_multihashmap_destroy (pr_map);
1662   pr_map = NULL;
1663   GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
1664   requests_by_expiration_heap = NULL;
1665   GNUNET_LOAD_value_free (datastore_put_load);
1666   datastore_put_load = NULL;
1667 }
1668
1669
1670 /* end of gnunet-service-fs_pr.c */