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