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