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