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