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