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