starting to use stream in fs
[oweals/gnunet.git] / src / fs / gnunet-service-fs_pr.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2010, 2011, 2012 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  * Maximum size of the datastore queue for P2P operations.  Needs to
36  * be large enough to queue MAX_QUEUE_PER_PEER operations for roughly
37  * the number of active (connected) peers.
38  */
39 #define MAX_DATASTORE_QUEUE (16 * MAX_QUEUE_PER_PEER)
40
41 /**
42  * Bandwidth value of a 0-priority content (must be fairly high
43  * compared to query since content is typically significantly larger
44  * -- and more valueable since it can take many queries to get one
45  * piece of content).
46  */
47 #define CONTENT_BANDWIDTH_VALUE 800
48
49 /**
50  * Hard limit on the number of results we may get from the datastore per query.
51  */
52 #define MAX_RESULTS (100 * 1024)
53
54 /**
55  * Collect an instane number of statistics?  May cause excessive IPC.
56  */
57 #define INSANE_STATISTICS GNUNET_NO
58
59 /**
60  * An active request.
61  */
62 struct GSF_PendingRequest
63 {
64   /**
65    * Public data for the request.
66    */
67   struct GSF_PendingRequestData public_data;
68
69   /**
70    * Function to call if we encounter a reply.
71    */
72   GSF_PendingRequestReplyHandler rh;
73
74   /**
75    * Closure for 'rh'
76    */
77   void *rh_cls;
78
79   /**
80    * Array of hash codes of replies we've already seen.
81    */
82   struct GNUNET_HashCode *replies_seen;
83
84   /**
85    * Bloomfilter masking replies we've already seen.
86    */
87   struct GNUNET_CONTAINER_BloomFilter *bf;
88
89   /**
90    * Entry for this pending request in the expiration heap, or NULL.
91    */
92   struct GNUNET_CONTAINER_HeapNode *hnode;
93
94   /**
95    * Datastore queue entry for this request (or NULL for none).
96    */
97   struct GNUNET_DATASTORE_QueueEntry *qe;
98
99   /**
100    * DHT request handle for this request (or NULL for none).
101    */
102   struct GNUNET_DHT_GetHandle *gh;
103
104   /**
105    * Function to call upon completion of the local get
106    * request, or NULL for none.
107    */
108   GSF_LocalLookupContinuation llc_cont;
109
110   /**
111    * Closure for llc_cont.
112    */
113   void *llc_cont_cls;
114
115   /**
116    * Last result from the local datastore lookup evaluation.
117    */
118   enum GNUNET_BLOCK_EvaluationResult local_result;
119
120   /**
121    * Identity of the peer that we should use for the 'sender'
122    * (recipient of the response) when forwarding (0 for none).
123    */
124   GNUNET_PEER_Id sender_pid;
125
126   /**
127    * Identity of the peer that we should never forward this query
128    * to since it originated this query (0 for none).
129    */
130   GNUNET_PEER_Id origin_pid;
131
132   /**
133    * Time we started the last datastore lookup.
134    */
135   struct GNUNET_TIME_Absolute qe_start;
136
137   /**
138    * Task that warns us if the local datastore lookup takes too long.
139    */
140   GNUNET_SCHEDULER_TaskIdentifier warn_task;
141
142   /**
143    * Current offset for querying our local datastore for results.
144    * Starts at a random value, incremented until we get the same
145    * UID again (detected using 'first_uid'), which is then used
146    * to termiante the iteration.
147    */
148   uint64_t local_result_offset;
149
150   /**
151    * Unique ID of the first result from the local datastore;
152    * used to detect wrap-around of the offset.
153    */
154   uint64_t first_uid;
155
156   /**
157    * Number of valid entries in the 'replies_seen' array.
158    */
159   unsigned int replies_seen_count;
160
161   /**
162    * Length of the 'replies_seen' array.
163    */
164   unsigned int replies_seen_size;
165
166   /**
167    * Mingle value we currently use for the bf.
168    */
169   uint32_t mingle;
170
171   /**
172    * Do we have a first UID yet?
173    */
174   unsigned int have_first_uid;
175
176 };
177
178
179 /**
180  * All pending requests, ordered by the query.  Entries
181  * are of type 'struct GSF_PendingRequest*'.
182  */
183 static struct GNUNET_CONTAINER_MultiHashMap *pr_map;
184
185
186 /**
187  * Datastore 'PUT' load tracking.
188  */
189 static struct GNUNET_LOAD_Value *datastore_put_load;
190
191
192 /**
193  * Are we allowed to migrate content to this peer.
194  */
195 static int active_to_migration;
196
197
198 /**
199  * Size of the datastore queue we assume for common requests.
200  * Determined based on the network quota.
201  */
202 static unsigned int datastore_queue_size;
203
204 /**
205  * Heap with the request that will expire next at the top.  Contains
206  * pointers of type "struct PendingRequest*"; these will *also* be
207  * aliased from the "requests_by_peer" data structures and the
208  * "requests_by_query" table.  Note that requests from our clients
209  * don't expire and are thus NOT in the "requests_by_expiration"
210  * (or the "requests_by_peer" tables).
211  */
212 static struct GNUNET_CONTAINER_Heap *requests_by_expiration_heap;
213
214
215 /**
216  * Maximum number of requests (from other peers, overall) that we're
217  * willing to have pending at any given point in time.  Can be changed
218  * via the configuration file (32k is just the default).
219  */
220 static unsigned long long max_pending_requests = (32 * 1024);
221
222
223
224 /**
225  * Recalculate our bloom filter for filtering replies.  This function
226  * will create a new bloom filter from scratch, so it should only be
227  * called if we have no bloomfilter at all (and hence can create a
228  * fresh one of minimal size without problems) OR if our peer is the
229  * initiator (in which case we may resize to larger than mimimum size).
230  *
231  * @param pr request for which the BF is to be recomputed
232  */
233 static void
234 refresh_bloomfilter (struct GSF_PendingRequest *pr)
235 {
236   if (pr->bf != NULL)
237     GNUNET_CONTAINER_bloomfilter_free (pr->bf);
238   pr->mingle =
239       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
240   pr->bf =
241       GNUNET_BLOCK_construct_bloomfilter (pr->mingle, pr->replies_seen,
242                                           pr->replies_seen_count);
243 }
244
245
246 /**
247  * Create a new pending request.
248  *
249  * @param options request options
250  * @param type type of the block that is being requested
251  * @param query key for the lookup
252  * @param namespace namespace to lookup, NULL for no namespace
253  * @param target preferred target for the request, NULL for none
254  * @param bf_data raw data for bloom filter for known replies, can be NULL
255  * @param bf_size number of bytes in bf_data
256  * @param mingle mingle value for bf
257  * @param anonymity_level desired anonymity level
258  * @param priority maximum outgoing cummulative request priority to use
259  * @param ttl current time-to-live for the request
260  * @param sender_pid peer ID to use for the sender when forwarding, 0 for none
261  * @param origin_pid peer ID of origin of query (do not loop back)
262  * @param replies_seen hash codes of known local replies
263  * @param replies_seen_count size of the 'replies_seen' array
264  * @param rh handle to call when we get a reply
265  * @param rh_cls closure for rh
266  * @return handle for the new pending request
267  */
268 struct GSF_PendingRequest *
269 GSF_pending_request_create_ (enum GSF_PendingRequestOptions options,
270                              enum GNUNET_BLOCK_Type type,
271                              const struct GNUNET_HashCode * query,
272                              const struct GNUNET_HashCode * namespace,
273                              const struct GNUNET_PeerIdentity *target,
274                              const char *bf_data, size_t bf_size,
275                              uint32_t mingle, uint32_t anonymity_level,
276                              uint32_t priority, int32_t ttl,
277                              GNUNET_PEER_Id sender_pid,
278                              GNUNET_PEER_Id origin_pid,
279                              const struct GNUNET_HashCode * replies_seen,
280                              unsigned int replies_seen_count,
281                              GSF_PendingRequestReplyHandler rh, void *rh_cls)
282 {
283   struct GSF_PendingRequest *pr;
284   struct GSF_PendingRequest *dpr;
285   size_t extra;
286   struct GNUNET_HashCode *eptr;
287
288   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
289               "Creating request handle for `%s' of type %d\n",
290               GNUNET_h2s (query), type);
291 #if INSANE_STATISTICS
292   GNUNET_STATISTICS_update (GSF_stats,
293                             gettext_noop ("# Pending requests created"), 1,
294                             GNUNET_NO);
295 #endif
296   extra = 0;
297   if (GNUNET_BLOCK_TYPE_FS_SBLOCK == type)
298     extra += sizeof (struct GNUNET_HashCode);
299   if (NULL != target)
300     extra += sizeof (struct GNUNET_PeerIdentity);
301   pr = GNUNET_malloc (sizeof (struct GSF_PendingRequest) + extra);
302   pr->local_result_offset =
303       GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
304   pr->public_data.query = *query;
305   eptr = (struct GNUNET_HashCode *) &pr[1];
306   if (GNUNET_BLOCK_TYPE_FS_SBLOCK == type)
307   {
308     GNUNET_assert (NULL != namespace);        
309     pr->public_data.namespace = eptr;
310     memcpy (eptr, namespace, sizeof (struct GNUNET_HashCode));
311     eptr++;
312   }
313   if (NULL != target)
314   {
315     pr->public_data.target = (struct GNUNET_PeerIdentity *) eptr;
316     memcpy (eptr, target, sizeof (struct GNUNET_PeerIdentity));
317   }
318   pr->public_data.anonymity_level = anonymity_level;
319   pr->public_data.priority = priority;
320   pr->public_data.original_priority = priority;
321   pr->public_data.options = options;
322   pr->public_data.type = type;
323   pr->public_data.start_time = GNUNET_TIME_absolute_get ();
324   pr->sender_pid = sender_pid;
325   pr->origin_pid = origin_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 (struct GNUNET_HashCode) * pr->replies_seen_size);
345     memcpy (pr->replies_seen, replies_seen,
346             replies_seen_count * sizeof (struct GNUNET_HashCode));
347     pr->replies_seen_count = replies_seen_count;
348   }
349   if (NULL != bf_data)
350   {
351     pr->bf =
352         GNUNET_CONTAINER_bloomfilter_init (bf_data, bf_size,
353                                            GNUNET_CONSTANTS_BLOOMFILTER_K);
354     pr->mingle = mingle;
355   }
356   else if ((replies_seen_count > 0) &&
357            (0 != (options & GSF_PRO_BLOOMFILTER_FULL_REFRESH)))
358   {
359     refresh_bloomfilter (pr);
360   }
361   GNUNET_CONTAINER_multihashmap_put (pr_map, 
362                                      &pr->public_data.query, pr,
363                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
364   if (0 == (options & GSF_PRO_REQUEST_NEVER_EXPIRES))
365   {
366     pr->hnode =
367         GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap, 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       if (NULL != dpr->rh)
378         dpr->rh (dpr->rh_cls, GNUNET_BLOCK_EVALUATION_REQUEST_VALID, dpr,
379                  UINT32_MAX, GNUNET_TIME_UNIT_FOREVER_ABS, GNUNET_TIME_UNIT_FOREVER_ABS,
380                  GNUNET_BLOCK_TYPE_ANY, NULL, 0);
381       GSF_pending_request_cancel_ (dpr, GNUNET_YES);
382     }
383   }
384   GNUNET_STATISTICS_update (GSF_stats,
385                             gettext_noop ("# Pending requests active"), 1,
386                             GNUNET_NO);
387   return pr;
388 }
389
390 /**
391  * Obtain the public data associated with a pending request
392  *
393  * @param pr pending request
394  * @return associated public data
395  */
396 struct GSF_PendingRequestData *
397 GSF_pending_request_get_data_ (struct GSF_PendingRequest *pr)
398 {
399   return &pr->public_data;
400 }
401
402
403 /**
404  * Test if two pending requests are compatible (would generate
405  * the same query modulo filters and should thus be processed
406  * jointly).
407  *
408  * @param pra a pending request
409  * @param prb another pending request
410  * @return GNUNET_OK if the requests are compatible
411  */
412 int
413 GSF_pending_request_is_compatible_ (struct GSF_PendingRequest *pra,
414                                     struct GSF_PendingRequest *prb)
415 {
416   if ((pra->public_data.type != prb->public_data.type) ||
417       (0 !=
418        memcmp (&pra->public_data.query, &prb->public_data.query,
419                sizeof (struct GNUNET_HashCode))) ||
420       ((pra->public_data.type == GNUNET_BLOCK_TYPE_FS_SBLOCK) &&
421        (0 !=
422         memcmp (pra->public_data.namespace, 
423                 prb->public_data.namespace,
424                 sizeof (struct 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 struct GNUNET_HashCode * replies_seen,
442                              unsigned int replies_seen_count)
443 {
444   unsigned int i;
445   struct 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, pr->replies_seen_size,
454                          replies_seen_count + pr->replies_seen_count);
455     memcpy (&pr->replies_seen[pr->replies_seen_count], replies_seen,
456             sizeof (struct GNUNET_HashCode) * replies_seen_count);
457     pr->replies_seen_count += replies_seen_count;
458     refresh_bloomfilter (pr);
459   }
460   else
461   {
462     if (NULL == pr->bf)
463     {
464       /* we're not the initiator, but the initiator did not give us
465        * any bloom-filter, so we need to create one on-the-fly */
466       pr->mingle =
467           GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
468       pr->bf =
469           GNUNET_BLOCK_construct_bloomfilter (pr->mingle, replies_seen,
470                                               replies_seen_count);
471     }
472     else
473     {
474       for (i = 0; i < pr->replies_seen_count; i++)
475       {
476         GNUNET_BLOCK_mingle_hash (&replies_seen[i], pr->mingle, &mhash);
477         GNUNET_CONTAINER_bloomfilter_add (pr->bf, &mhash);
478       }
479     }
480   }
481   if (NULL != pr->gh) 
482     GNUNET_DHT_get_filter_known_results (pr->gh,
483                                          replies_seen_count,
484                                          replies_seen);
485 }
486
487
488 /**
489  * Generate the message corresponding to the given pending request for
490  * transmission to other peers (or at least determine its size).
491  *
492  * @param pr request to generate the message for
493  * @param buf_size number of bytes available in buf
494  * @param buf where to copy the message (can be NULL)
495  * @return number of bytes needed (if > buf_size) or used
496  */
497 size_t
498 GSF_pending_request_get_message_ (struct GSF_PendingRequest *pr,
499                                   size_t buf_size, void *buf)
500 {
501   char lbuf[GNUNET_SERVER_MAX_MESSAGE_SIZE];
502   struct GetMessage *gm;
503   struct GNUNET_HashCode *ext;
504   size_t msize;
505   unsigned int k;
506   uint32_t bm;
507   uint32_t prio;
508   size_t bf_size;
509   struct GNUNET_TIME_Absolute now;
510   int64_t ttl;
511   int do_route;
512
513   if (buf_size > 0)
514     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
515                 "Building request message for `%s' of type %d\n",
516                 GNUNET_h2s (&pr->public_data.query), pr->public_data.type);
517   k = 0;
518   bm = 0;
519   do_route = (0 == (pr->public_data.options & GSF_PRO_FORWARD_ONLY));
520   if ((!do_route) && (pr->sender_pid == 0))
521   {
522     GNUNET_break (0);
523     do_route = GNUNET_YES;
524   }
525   if (!do_route)
526   {
527     bm |= GET_MESSAGE_BIT_RETURN_TO;
528     k++;
529   }
530   if (GNUNET_BLOCK_TYPE_FS_SBLOCK == pr->public_data.type)
531   {
532     bm |= GET_MESSAGE_BIT_SKS_NAMESPACE;
533     k++;
534   }
535   if (NULL != pr->public_data.target)
536   {
537     bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
538     k++;
539   }
540   bf_size = GNUNET_CONTAINER_bloomfilter_get_size (pr->bf);
541   msize = sizeof (struct GetMessage) + bf_size + k * sizeof (struct GNUNET_HashCode);
542   GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
543   if (buf_size < msize)
544     return msize;
545   gm = (struct GetMessage *) lbuf;
546   gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
547   gm->header.size = htons (msize);
548   gm->type = htonl (pr->public_data.type);
549   if (do_route)
550     prio =
551         GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
552                                   pr->public_data.priority + 1);
553   else
554     prio = 0;
555   pr->public_data.priority -= prio;
556   pr->public_data.num_transmissions++;
557   pr->public_data.respect_offered += prio;
558   gm->priority = htonl (prio);
559   now = GNUNET_TIME_absolute_get ();
560   ttl = (int64_t) (pr->public_data.ttl.abs_value - now.abs_value);
561   gm->ttl = htonl (ttl / 1000);
562   gm->filter_mutator = htonl (pr->mingle);
563   gm->hash_bitmap = htonl (bm);
564   gm->query = pr->public_data.query;
565   ext = (struct GNUNET_HashCode *) & gm[1];
566   k = 0;
567   if (!do_route)
568     GNUNET_PEER_resolve (pr->sender_pid,
569                          (struct GNUNET_PeerIdentity *) &ext[k++]);
570   if (GNUNET_BLOCK_TYPE_FS_SBLOCK == pr->public_data.type)
571     memcpy (&ext[k++], pr->public_data.namespace, sizeof (struct GNUNET_HashCode));
572   if (NULL != pr->public_data.target)
573     memcpy (&ext[k++],
574             pr->public_data.target,
575             sizeof (struct GNUNET_PeerIdentity));
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 struct GNUNET_HashCode * key, void *value)
596 {
597   struct GSF_PendingRequest *pr = value;
598   GSF_LocalLookupContinuation cont;
599
600   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
601               "Cleaning up pending request for `%s'.\n", GNUNET_h2s (key));
602   if (NULL != (cont = pr->llc_cont))
603   {
604     pr->llc_cont = NULL;
605     cont (pr->llc_cont_cls, pr, pr->local_result);
606   }
607   GSF_plan_notify_request_done_ (pr);
608   GNUNET_free_non_null (pr->replies_seen);
609   if (NULL != pr->bf)
610   {
611     GNUNET_CONTAINER_bloomfilter_free (pr->bf);
612     pr->bf = NULL;
613   }
614   GNUNET_PEER_change_rc (pr->sender_pid, -1);
615   pr->sender_pid = 0;
616   GNUNET_PEER_change_rc (pr->origin_pid, -1);
617   pr->origin_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"), -1,
644                             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, pr->public_data.start_time,
780                                 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 struct GNUNET_HashCode * key, void *value)
794 {
795   struct ProcessReplyClosure *prq = cls;
796   struct GSF_PendingRequest *pr = value;
797   struct GNUNET_HashCode chash;
798   struct GNUNET_TIME_Absolute last_transmission;
799
800   if (NULL == pr->rh)
801     return GNUNET_YES;
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   GNUNET_STATISTICS_update (GSF_stats,
806                             gettext_noop ("# replies received and matched"), 1,
807                             GNUNET_NO);
808   prq->eval =
809       GNUNET_BLOCK_evaluate (GSF_block_ctx, prq->type, key, &pr->bf, pr->mingle,
810                              pr->public_data.namespace,
811                              (prq->type ==
812                               GNUNET_BLOCK_TYPE_FS_SBLOCK) ?
813                              sizeof (struct GNUNET_HashCode) : 0, prq->data,
814                              prq->size);
815   switch (prq->eval)
816   {
817   case GNUNET_BLOCK_EVALUATION_OK_MORE:
818     update_request_performance_data (prq, pr);
819     break;
820   case GNUNET_BLOCK_EVALUATION_OK_LAST:
821     /* short cut: stop processing early, no BF-update, etc. */
822     update_request_performance_data (prq, pr);
823     GNUNET_LOAD_update (GSF_rt_entry_lifetime,
824                         GNUNET_TIME_absolute_get_duration (pr->
825                                                            public_data.start_time).rel_value);
826     if (GNUNET_YES !=
827         GSF_request_plan_reference_get_last_transmission_ (pr->public_data.pr_head, 
828                                                            prq->sender, 
829                                                            &last_transmission))
830       last_transmission.abs_value = GNUNET_TIME_UNIT_FOREVER_ABS.abs_value;
831     /* pass on to other peers / local clients */
832     pr->rh (pr->rh_cls, prq->eval, pr, prq->anonymity_level, prq->expiration,
833             last_transmission, prq->type, prq->data, prq->size);
834     return GNUNET_YES;
835   case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
836 #if INSANE_STATISTICS
837     GNUNET_STATISTICS_update (GSF_stats,
838                               gettext_noop
839                               ("# duplicate replies discarded (bloomfilter)"),
840                               1, GNUNET_NO);
841 #endif
842     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
843                 "Duplicate response, discarding.\n");
844     return GNUNET_YES;          /* duplicate */
845   case GNUNET_BLOCK_EVALUATION_RESULT_IRRELEVANT:
846     GNUNET_STATISTICS_update (GSF_stats,
847                               gettext_noop
848                               ("# irrelevant replies discarded"),
849                               1, GNUNET_NO);
850     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
851                 "Irrelevant response, ignoring.\n");
852     return GNUNET_YES;
853   case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
854     return GNUNET_YES;          /* wrong namespace */
855   case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
856     GNUNET_break (0);
857     return GNUNET_YES;
858   case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
859     GNUNET_break (0);
860     return GNUNET_YES;
861   case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
862     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Unsupported block type %u\n"),
863                 prq->type);
864     return GNUNET_NO;
865   }
866   /* update bloomfilter */
867   GNUNET_CRYPTO_hash (prq->data, prq->size, &chash);
868   GSF_pending_request_update_ (pr, &chash, 1);
869   if (NULL == prq->sender)
870   {
871     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
872                 "Found result for query `%s' in local datastore\n",
873                 GNUNET_h2s (key));
874     GNUNET_STATISTICS_update (GSF_stats,
875                               gettext_noop ("# results found locally"), 1,
876                               GNUNET_NO);
877   }
878   else
879   {
880     GSF_dht_lookup_ (pr);
881   }
882   prq->priority += pr->public_data.original_priority;
883   pr->public_data.priority = 0;
884   pr->public_data.original_priority = 0;
885   pr->public_data.results_found++;
886   prq->request_found = GNUNET_YES;
887   /* finally, pass on to other peer / local client */
888   if (! GSF_request_plan_reference_get_last_transmission_ (pr->public_data.pr_head,
889                                                            prq->sender, 
890                                                            &last_transmission))
891     last_transmission.abs_value = GNUNET_TIME_UNIT_FOREVER_ABS.abs_value;
892   pr->rh (pr->rh_cls, prq->eval, pr, 
893           prq->anonymity_level, prq->expiration,
894           last_transmission, prq->type, prq->data, prq->size);
895   return GNUNET_YES;
896 }
897
898
899 /**
900  * Context for the 'put_migration_continuation'.
901  */
902 struct PutMigrationContext
903 {
904
905   /**
906    * Start time for the operation.
907    */
908   struct GNUNET_TIME_Absolute start;
909
910   /**
911    * Request origin.
912    */
913   struct GNUNET_PeerIdentity origin;
914
915   /**
916    * GNUNET_YES if we had a matching request for this block,
917    * GNUNET_NO if not.
918    */
919   int requested;
920 };
921
922
923 /**
924  * Continuation called to notify client about result of the
925  * operation.
926  *
927  * @param cls closure
928  * @param success GNUNET_SYSERR on failure
929  * @param min_expiration minimum expiration time required for content to be stored
930  * @param msg NULL on success, otherwise an error message
931  */
932 static void
933 put_migration_continuation (void *cls, int success, 
934                             struct GNUNET_TIME_Absolute min_expiration,
935                             const char *msg)
936 {
937   struct PutMigrationContext *pmc = cls;
938   struct GSF_ConnectedPeer *cp;
939   struct GNUNET_TIME_Relative mig_pause;
940   struct GSF_PeerPerformanceData *ppd;
941
942   if (NULL != datastore_put_load)
943   {
944     if (GNUNET_SYSERR != success)
945     {
946       GNUNET_LOAD_update (datastore_put_load, 
947                           GNUNET_TIME_absolute_get_duration (pmc->start).rel_value);
948     }
949     else
950     {
951       /* on queue failure / timeout, increase the put load dramatically */
952       GNUNET_LOAD_update (datastore_put_load, 
953                           GNUNET_TIME_UNIT_MINUTES.rel_value);
954     }
955   }
956   cp = GSF_peer_get_ (&pmc->origin);
957   if (GNUNET_OK == success)
958   {
959     if (NULL != cp)
960     {
961       ppd = GSF_get_peer_performance_data_ (cp);
962       ppd->migration_delay.rel_value /= 2;
963     }
964     GNUNET_free (pmc);
965     return;
966   }
967   if ( (GNUNET_NO == success) && 
968        (GNUNET_NO == pmc->requested) && 
969        (NULL != cp) )
970   {
971     ppd = GSF_get_peer_performance_data_ (cp);
972     if (min_expiration.abs_value > 0)
973     {
974       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
975                   "Asking to stop migration for %s because datastore is full\n",
976                   GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (min_expiration), GNUNET_YES));
977       GSF_block_peer_migration_ (cp, min_expiration);      
978     }
979     else
980     {
981       ppd->migration_delay = GNUNET_TIME_relative_max (GNUNET_TIME_UNIT_SECONDS,
982                                                        ppd->migration_delay);
983       ppd->migration_delay = GNUNET_TIME_relative_min (GNUNET_TIME_UNIT_HOURS,
984                                                        ppd->migration_delay);
985       mig_pause.rel_value = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
986                                                       ppd->migration_delay.rel_value);
987       ppd->migration_delay = GNUNET_TIME_relative_multiply (ppd->migration_delay, 2);
988       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
989                   "Replicated content already exists locally, asking to stop migration for %s\n",
990                   GNUNET_STRINGS_relative_time_to_string (mig_pause, GNUNET_YES));
991       GSF_block_peer_migration_ (cp, GNUNET_TIME_relative_to_absolute (mig_pause));
992     }
993   }
994   GNUNET_free (pmc);
995   GNUNET_STATISTICS_update (GSF_stats,
996                             gettext_noop ("# Datastore `PUT' failures"), 1,
997                             GNUNET_NO);
998 }
999
1000
1001 /**
1002  * Test if the DATABASE (PUT) load on this peer is too high
1003  * to even consider processing the query at
1004  * all.
1005  *
1006  * @return GNUNET_YES if the load is too high to do anything (load high)
1007  *         GNUNET_NO to process normally (load normal or low)
1008  */
1009 static int
1010 test_put_load_too_high (uint32_t priority)
1011 {
1012   double ld;
1013
1014   if (NULL == datastore_put_load)
1015     return GNUNET_NO;
1016   if (GNUNET_LOAD_get_average (datastore_put_load) < 50)
1017     return GNUNET_NO;           /* very fast */
1018   ld = GNUNET_LOAD_get_load (datastore_put_load);
1019   if (ld < 2.0 * (1 + priority))
1020     return GNUNET_NO;
1021   GNUNET_STATISTICS_update (GSF_stats,
1022                             gettext_noop
1023                             ("# storage requests dropped due to high load"), 1,
1024                             GNUNET_NO);
1025   return GNUNET_YES;
1026 }
1027
1028
1029 /**
1030  * Iterator called on each result obtained for a DHT
1031  * operation that expects a reply
1032  *
1033  * @param cls closure
1034  * @param exp when will this value expire
1035  * @param key key of the result
1036  * @param get_path peers on reply path (or NULL if not recorded)
1037  * @param get_path_length number of entries in get_path
1038  * @param put_path peers on the PUT path (or NULL if not recorded)
1039  * @param put_path_length number of entries in get_path
1040  * @param type type of the result
1041  * @param size number of bytes in data
1042  * @param data pointer to the result data
1043  */
1044 static void
1045 handle_dht_reply (void *cls, struct GNUNET_TIME_Absolute exp,
1046                   const struct GNUNET_HashCode * key,
1047                   const struct GNUNET_PeerIdentity *get_path,
1048                   unsigned int get_path_length,
1049                   const struct GNUNET_PeerIdentity *put_path,
1050                   unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
1051                   size_t size, const void *data)
1052 {
1053   struct GSF_PendingRequest *pr = cls;
1054   struct ProcessReplyClosure prq;
1055   struct PutMigrationContext *pmc;
1056
1057   GNUNET_STATISTICS_update (GSF_stats,
1058                             gettext_noop ("# Replies received from DHT"), 1,
1059                             GNUNET_NO);
1060   memset (&prq, 0, sizeof (prq));
1061   prq.data = data;
1062   prq.expiration = exp;
1063   /* do not allow migrated content to live longer than 1 year */
1064   prq.expiration = GNUNET_TIME_absolute_min (GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_YEARS),
1065                                              prq.expiration);
1066   prq.size = size;
1067   prq.type = type;
1068   process_reply (&prq, key, pr);
1069   if ((GNUNET_YES == active_to_migration) &&
1070       (GNUNET_NO == test_put_load_too_high (prq.priority)))
1071   {
1072     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1073                 "Replicating result for query `%s' with priority %u\n",
1074                 GNUNET_h2s (key), prq.priority);
1075     pmc = GNUNET_malloc (sizeof (struct PutMigrationContext));
1076     pmc->start = GNUNET_TIME_absolute_get ();
1077     pmc->requested = GNUNET_YES;
1078     if (NULL ==
1079         GNUNET_DATASTORE_put (GSF_dsh, 0, key, size, data, type, prq.priority,
1080                               1 /* anonymity */ ,
1081                               0 /* replication */ ,
1082                               exp, 1 + prq.priority, MAX_DATASTORE_QUEUE,
1083                               GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1084                               &put_migration_continuation, pmc))
1085     {
1086       put_migration_continuation (pmc, GNUNET_SYSERR, GNUNET_TIME_UNIT_ZERO_ABS, NULL);
1087     }
1088   }
1089 }
1090
1091
1092 /**
1093  * Consider looking up the data in the DHT (anonymity-level permitting).
1094  *
1095  * @param pr the pending request to process
1096  */
1097 void
1098 GSF_dht_lookup_ (struct GSF_PendingRequest *pr)
1099 {
1100   const void *xquery;
1101   size_t xquery_size;
1102   struct GNUNET_PeerIdentity pi;
1103   char buf[sizeof (struct GNUNET_HashCode) * 2] GNUNET_ALIGN;
1104
1105   if (0 != pr->public_data.anonymity_level)
1106     return;
1107   if (NULL != pr->gh)
1108   {
1109     GNUNET_DHT_get_stop (pr->gh);
1110     pr->gh = NULL;
1111   }
1112   xquery = NULL;
1113   xquery_size = 0;
1114   if (GNUNET_BLOCK_TYPE_FS_SBLOCK == pr->public_data.type)
1115   {
1116     xquery = buf;
1117     memcpy (buf, pr->public_data.namespace, sizeof (struct GNUNET_HashCode));
1118     xquery_size = sizeof (struct GNUNET_HashCode);
1119   }
1120   if (0 != (pr->public_data.options & GSF_PRO_FORWARD_ONLY))
1121   {
1122     GNUNET_assert (0 != pr->sender_pid);
1123     GNUNET_PEER_resolve (pr->sender_pid, &pi);
1124     memcpy (&buf[xquery_size], &pi, sizeof (struct GNUNET_PeerIdentity));
1125     xquery_size += sizeof (struct GNUNET_PeerIdentity);
1126   }
1127   pr->gh =
1128       GNUNET_DHT_get_start (GSF_dht, 
1129                             pr->public_data.type, &pr->public_data.query,
1130                             5 /* DEFAULT_GET_REPLICATION */ ,
1131                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
1132                             xquery, xquery_size, &handle_dht_reply, pr);
1133   if ( (NULL != pr->gh) && 
1134        (0 != pr->replies_seen_count) )
1135     GNUNET_DHT_get_filter_known_results (pr->gh,
1136                                          pr->replies_seen_count,
1137                                          pr->replies_seen);
1138 }
1139
1140
1141 /**
1142  * Task that issues a warning if the datastore lookup takes too long.
1143  *
1144  * @param cls the 'struct GSF_PendingRequest'
1145  * @param tc task context
1146  */
1147 static void
1148 warn_delay_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1149 {
1150   struct GSF_PendingRequest *pr = cls;
1151
1152   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1153               _("Datastore lookup already took %s!\n"),
1154               GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (pr->qe_start), GNUNET_YES));
1155   pr->warn_task =
1156       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, &warn_delay_task,
1157                                     pr);
1158 }
1159
1160
1161 /**
1162  * Task that issues a warning if the datastore lookup takes too long.
1163  *
1164  * @param cls the 'struct GSF_PendingRequest'
1165  * @param tc task context
1166  */
1167 static void
1168 odc_warn_delay_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1169 {
1170   struct GSF_PendingRequest *pr = cls;
1171
1172   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1173               _("On-demand lookup already took %s!\n"),
1174               GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (pr->qe_start), GNUNET_YES));
1175   pr->warn_task =
1176       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1177                                     &odc_warn_delay_task, pr);
1178 }
1179
1180
1181 /**
1182  * We're processing (local) results for a search request
1183  * from another peer.  Pass applicable results to the
1184  * peer and if we are done either clean up (operation
1185  * complete) or forward to other peers (more results possible).
1186  *
1187  * @param cls our closure (struct PendingRequest)
1188  * @param key key for the content
1189  * @param size number of bytes in data
1190  * @param data content stored
1191  * @param type type of the content
1192  * @param priority priority of the content
1193  * @param anonymity anonymity-level for the content
1194  * @param expiration expiration time for the content
1195  * @param uid unique identifier for the datum;
1196  *        maybe 0 if no unique identifier is available
1197  */
1198 static void
1199 process_local_reply (void *cls, const struct GNUNET_HashCode * key, size_t size,
1200                      const void *data, enum GNUNET_BLOCK_Type type,
1201                      uint32_t priority, uint32_t anonymity,
1202                      struct GNUNET_TIME_Absolute expiration, uint64_t uid)
1203 {
1204   struct GSF_PendingRequest *pr = cls;
1205   GSF_LocalLookupContinuation cont;
1206   struct ProcessReplyClosure prq;
1207   struct GNUNET_HashCode query;
1208   unsigned int old_rf;
1209
1210   GNUNET_SCHEDULER_cancel (pr->warn_task);
1211   pr->warn_task = GNUNET_SCHEDULER_NO_TASK;
1212   if (NULL != pr->qe)
1213   {
1214     pr->qe = NULL;
1215     if (NULL == key)
1216     {
1217 #if INSANE_STATISTICS
1218       GNUNET_STATISTICS_update (GSF_stats,
1219                                 gettext_noop
1220                                 ("# Datastore lookups concluded (no results)"),
1221                                 1, GNUNET_NO);
1222 #endif
1223     }
1224     if (GNUNET_NO == pr->have_first_uid)
1225     {
1226       pr->first_uid = uid;
1227       pr->have_first_uid = 1;
1228     }
1229     else
1230     {
1231       if ((uid == pr->first_uid) && (key != NULL))
1232       {
1233         GNUNET_STATISTICS_update (GSF_stats,
1234                                   gettext_noop
1235                                   ("# Datastore lookups concluded (seen all)"),
1236                                   1, GNUNET_NO);
1237         key = NULL;             /* all replies seen! */
1238       }
1239       pr->have_first_uid++;
1240       if ((pr->have_first_uid > MAX_RESULTS) && (key != NULL))
1241       {
1242         GNUNET_STATISTICS_update (GSF_stats,
1243                                   gettext_noop
1244                                   ("# Datastore lookups aborted (more than MAX_RESULTS)"),
1245                                   1, GNUNET_NO);
1246         key = NULL;             /* all replies seen! */
1247       }
1248     }
1249   }
1250   if (NULL == key)
1251   {
1252     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1253                 "No further local responses available.\n");
1254 #if INSANE_STATISTICS
1255     if ((pr->public_data.type == GNUNET_BLOCK_TYPE_FS_DBLOCK) ||
1256         (pr->public_data.type == GNUNET_BLOCK_TYPE_FS_IBLOCK))
1257       GNUNET_STATISTICS_update (GSF_stats,
1258                                 gettext_noop
1259                                 ("# requested DBLOCK or IBLOCK not found"), 1,
1260                                 GNUNET_NO);
1261 #endif
1262     goto check_error_and_continue;
1263   }
1264   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1265               "Received reply for `%s' of type %d with UID %llu from datastore.\n",
1266               GNUNET_h2s (key), type, (unsigned long long) uid);
1267   if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
1268   {
1269     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1270                 "Found ONDEMAND block, performing on-demand encoding\n");
1271     GNUNET_STATISTICS_update (GSF_stats,
1272                               gettext_noop
1273                               ("# on-demand blocks matched requests"), 1,
1274                               GNUNET_NO);
1275     pr->qe_start = GNUNET_TIME_absolute_get ();
1276     pr->warn_task =
1277         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1278                                       &odc_warn_delay_task, pr);
1279     if (GNUNET_OK ==
1280         GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
1281                                           anonymity, expiration, uid,
1282                                           &process_local_reply, pr))
1283     {
1284       GNUNET_STATISTICS_update (GSF_stats,
1285                                 gettext_noop
1286                                 ("# on-demand lookups performed successfully"),
1287                                 1, GNUNET_NO);
1288       return;                   /* we're done */
1289     }
1290     GNUNET_STATISTICS_update (GSF_stats,
1291                               gettext_noop ("# on-demand lookups failed"), 1,
1292                               GNUNET_NO);
1293     GNUNET_SCHEDULER_cancel (pr->warn_task);
1294     pr->warn_task =
1295         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1296                                       &warn_delay_task, pr);
1297     pr->qe =
1298         GNUNET_DATASTORE_get_key (GSF_dsh, pr->local_result_offset - 1,
1299                                   &pr->public_data.query,
1300                                   pr->public_data.type ==
1301                                   GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1302                                   GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1303                                   (0 !=
1304                                    (GSF_PRO_PRIORITY_UNLIMITED &
1305                                     pr->public_data.options)) ? UINT_MAX : 1
1306                                   /* queue priority */ ,
1307                                   (0 !=
1308                                    (GSF_PRO_PRIORITY_UNLIMITED &
1309                                     pr->public_data.options)) ? UINT_MAX :
1310                                   datastore_queue_size
1311                                   /* max queue size */ ,
1312                                   GNUNET_TIME_UNIT_FOREVER_REL,
1313                                   &process_local_reply, pr);
1314     if (NULL != pr->qe)
1315       return;                   /* we're done */
1316     GNUNET_STATISTICS_update (GSF_stats,
1317                               gettext_noop
1318                               ("# Datastore lookups concluded (error queueing)"),
1319                               1, GNUNET_NO);
1320     goto check_error_and_continue;
1321   }
1322   old_rf = pr->public_data.results_found;
1323   memset (&prq, 0, sizeof (prq));
1324   prq.data = data;
1325   prq.expiration = expiration;
1326   prq.size = size;
1327   if (GNUNET_OK !=
1328       GNUNET_BLOCK_get_key (GSF_block_ctx, type, data, size, &query))
1329   {
1330     GNUNET_break (0);
1331     GNUNET_DATASTORE_remove (GSF_dsh, key, size, data, -1, -1,
1332                              GNUNET_TIME_UNIT_FOREVER_REL, NULL, NULL);
1333     pr->qe_start = GNUNET_TIME_absolute_get ();
1334     pr->warn_task =
1335         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1336                                       &warn_delay_task, pr);
1337     pr->qe =
1338         GNUNET_DATASTORE_get_key (GSF_dsh, pr->local_result_offset - 1,
1339                                   &pr->public_data.query,
1340                                   pr->public_data.type ==
1341                                   GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1342                                   GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1343                                   (0 !=
1344                                    (GSF_PRO_PRIORITY_UNLIMITED &
1345                                     pr->public_data.options)) ? UINT_MAX : 1
1346                                   /* queue priority */ ,
1347                                   (0 !=
1348                                    (GSF_PRO_PRIORITY_UNLIMITED &
1349                                     pr->public_data.options)) ? UINT_MAX :
1350                                   datastore_queue_size
1351                                   /* max queue size */ ,
1352                                   GNUNET_TIME_UNIT_FOREVER_REL,
1353                                   &process_local_reply, pr);
1354     if (pr->qe == NULL)
1355     {
1356       GNUNET_STATISTICS_update (GSF_stats,
1357                                 gettext_noop
1358                                 ("# Datastore lookups concluded (error queueing)"),
1359                                 1, GNUNET_NO);
1360       goto check_error_and_continue;
1361     }
1362     return;
1363   }
1364   prq.type = type;
1365   prq.priority = priority;
1366   prq.request_found = GNUNET_NO;
1367   prq.anonymity_level = anonymity;
1368   if ((old_rf == 0) && (pr->public_data.results_found == 0))
1369     GSF_update_datastore_delay_ (pr->public_data.start_time);
1370   process_reply (&prq, key, pr);
1371   pr->local_result = prq.eval;
1372   if (prq.eval == GNUNET_BLOCK_EVALUATION_OK_LAST)
1373   {
1374     GNUNET_STATISTICS_update (GSF_stats,
1375                               gettext_noop
1376                               ("# Datastore lookups concluded (found last result)"),
1377                               1, GNUNET_NO);
1378     goto check_error_and_continue;
1379   }
1380   if ((0 == (GSF_PRO_PRIORITY_UNLIMITED & pr->public_data.options)) &&
1381       ((GNUNET_YES == GSF_test_get_load_too_high_ (0)) ||
1382        (pr->public_data.results_found > 5 + 2 * pr->public_data.priority)))
1383   {
1384     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Load too high, done with request\n");
1385     GNUNET_STATISTICS_update (GSF_stats,
1386                               gettext_noop
1387                               ("# Datastore lookups concluded (load too high)"),
1388                               1, GNUNET_NO);
1389     goto check_error_and_continue;
1390   }
1391   pr->qe_start = GNUNET_TIME_absolute_get ();
1392   pr->warn_task =
1393       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, &warn_delay_task,
1394                                     pr);
1395   pr->qe =
1396       GNUNET_DATASTORE_get_key (GSF_dsh, pr->local_result_offset++,
1397                                 &pr->public_data.query,
1398                                 pr->public_data.type ==
1399                                 GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1400                                 GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1401                                 (0 !=
1402                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1403                                   public_data.options)) ? UINT_MAX : 1
1404                                 /* queue priority */ ,
1405                                 (0 !=
1406                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1407                                   public_data.options)) ? UINT_MAX :
1408                                 datastore_queue_size
1409                                 /* max queue size */ ,
1410                                 GNUNET_TIME_UNIT_FOREVER_REL,
1411                                 &process_local_reply, pr);
1412   /* check if we successfully queued another datastore request;
1413    * if so, return, otherwise call our continuation (if we have
1414    * any) */
1415 check_error_and_continue:
1416   if (NULL != pr->qe)
1417     return;
1418   if (GNUNET_SCHEDULER_NO_TASK != pr->warn_task)
1419   {
1420     GNUNET_SCHEDULER_cancel (pr->warn_task);
1421     pr->warn_task = GNUNET_SCHEDULER_NO_TASK;
1422   }
1423   if (NULL == (cont = pr->llc_cont))
1424     return;                     /* no continuation */
1425   pr->llc_cont = NULL;
1426   cont (pr->llc_cont_cls, pr, pr->local_result);
1427 }
1428
1429
1430 /**
1431  * Is the given target a legitimate peer for forwarding the given request?
1432  *
1433  * @param pr request
1434  * @param target
1435  * @return GNUNET_YES if this request could be forwarded to the given peer
1436  */
1437 int
1438 GSF_pending_request_test_target_ (struct GSF_PendingRequest *pr,
1439                                   const struct GNUNET_PeerIdentity *target)
1440 {
1441   struct GNUNET_PeerIdentity pi;
1442
1443   if (0 == pr->origin_pid)
1444     return GNUNET_YES;
1445   GNUNET_PEER_resolve (pr->origin_pid, &pi);
1446   return (0 ==
1447           memcmp (&pi, target,
1448                   sizeof (struct GNUNET_PeerIdentity))) ? GNUNET_NO :
1449       GNUNET_YES;
1450 }
1451
1452
1453 /**
1454  * Look up the request in the local datastore.
1455  *
1456  * @param pr the pending request to process
1457  * @param cont function to call at the end
1458  * @param cont_cls closure for cont
1459  */
1460 void
1461 GSF_local_lookup_ (struct GSF_PendingRequest *pr,
1462                    GSF_LocalLookupContinuation cont, void *cont_cls)
1463 {
1464   GNUNET_assert (NULL == pr->gh);
1465   GNUNET_assert (NULL == pr->llc_cont);
1466   pr->llc_cont = cont;
1467   pr->llc_cont_cls = cont_cls;
1468   pr->qe_start = GNUNET_TIME_absolute_get ();
1469   pr->warn_task =
1470       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, &warn_delay_task,
1471                                     pr);
1472 #if INSANE_STATISTICS
1473   GNUNET_STATISTICS_update (GSF_stats,
1474                             gettext_noop ("# Datastore lookups initiated"), 1,
1475                             GNUNET_NO);
1476 #endif
1477   pr->qe =
1478       GNUNET_DATASTORE_get_key (GSF_dsh, pr->local_result_offset++,
1479                                 &pr->public_data.query,
1480                                 pr->public_data.type ==
1481                                 GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1482                                 GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1483                                 (0 !=
1484                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1485                                   public_data.options)) ? UINT_MAX : 1
1486                                 /* queue priority */ ,
1487                                 (0 !=
1488                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1489                                   public_data.options)) ? UINT_MAX :
1490                                 datastore_queue_size
1491                                 /* max queue size */ ,
1492                                 GNUNET_TIME_UNIT_FOREVER_REL,
1493                                 &process_local_reply, pr);
1494   if (NULL != pr->qe)
1495     return;
1496   GNUNET_STATISTICS_update (GSF_stats,
1497                             gettext_noop
1498                             ("# Datastore lookups concluded (error queueing)"),
1499                             1, GNUNET_NO);
1500   GNUNET_SCHEDULER_cancel (pr->warn_task);
1501   pr->warn_task = GNUNET_SCHEDULER_NO_TASK;
1502   pr->llc_cont = NULL;
1503   if (NULL != cont)
1504     cont (cont_cls, pr, pr->local_result);
1505 }
1506
1507
1508
1509 /**
1510  * Handle P2P "CONTENT" message.  Checks that the message is
1511  * well-formed and then checks if there are any pending requests for
1512  * this content and possibly passes it on (to local clients or other
1513  * peers).  Does NOT perform migration (content caching at this peer).
1514  *
1515  * @param cp the other peer involved (sender or receiver, NULL
1516  *        for loopback messages where we are both sender and receiver)
1517  * @param message the actual message
1518  * @return GNUNET_OK if the message was well-formed,
1519  *         GNUNET_SYSERR if the message was malformed (close connection,
1520  *         do not cache under any circumstances)
1521  */
1522 int
1523 GSF_handle_p2p_content_ (struct GSF_ConnectedPeer *cp,
1524                          const struct GNUNET_MessageHeader *message)
1525 {
1526   const struct PutMessage *put;
1527   uint16_t msize;
1528   size_t dsize;
1529   enum GNUNET_BLOCK_Type type;
1530   struct GNUNET_TIME_Absolute expiration;
1531   struct GNUNET_HashCode query;
1532   struct ProcessReplyClosure prq;
1533   struct GNUNET_TIME_Relative block_time;
1534   double putl;
1535   struct PutMigrationContext *pmc;
1536
1537   msize = ntohs (message->size);
1538   if (msize < sizeof (struct PutMessage))
1539   {
1540     GNUNET_break_op (0);
1541     return GNUNET_SYSERR;
1542   }
1543   put = (const struct PutMessage *) message;
1544   dsize = msize - sizeof (struct PutMessage);
1545   type = ntohl (put->type);
1546   expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
1547   /* do not allow migrated content to live longer than 1 year */
1548   expiration = GNUNET_TIME_absolute_min (GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_YEARS),
1549                                          expiration);
1550   if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
1551     return GNUNET_SYSERR;
1552   if (GNUNET_OK !=
1553       GNUNET_BLOCK_get_key (GSF_block_ctx, type, &put[1], dsize, &query))
1554   {
1555     GNUNET_break_op (0);
1556     return GNUNET_SYSERR;
1557   }
1558   GNUNET_STATISTICS_update (GSF_stats,
1559                             gettext_noop ("# GAP PUT messages received"), 1,
1560                             GNUNET_NO);
1561   /* now, lookup 'query' */
1562   prq.data = (const void *) &put[1];
1563   prq.sender = cp;
1564   prq.size = dsize;
1565   prq.type = type;
1566   prq.expiration = expiration;
1567   prq.priority = 0;
1568   prq.anonymity_level = UINT32_MAX;
1569   prq.request_found = GNUNET_NO;
1570   GNUNET_CONTAINER_multihashmap_get_multiple (pr_map, &query, &process_reply,
1571                                               &prq);
1572   if (NULL != cp)
1573   {
1574     GSF_connected_peer_change_preference_ (cp,
1575                                            CONTENT_BANDWIDTH_VALUE +
1576                                            1000 * prq.priority);
1577     GSF_get_peer_performance_data_ (cp)->respect += prq.priority;
1578   }
1579   if ((GNUNET_YES == active_to_migration) &&
1580       (NULL != cp) &&
1581       (GNUNET_NO == test_put_load_too_high (prq.priority)))
1582   {
1583     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1584                 "Replicating result for query `%s' with priority %u\n",
1585                 GNUNET_h2s (&query), prq.priority);
1586     pmc = GNUNET_malloc (sizeof (struct PutMigrationContext));
1587     pmc->start = GNUNET_TIME_absolute_get ();
1588     pmc->requested = prq.request_found;
1589     GNUNET_assert (0 != GSF_get_peer_performance_data_ (cp)->pid);
1590     GNUNET_PEER_resolve (GSF_get_peer_performance_data_ (cp)->pid,
1591                          &pmc->origin);
1592     if (NULL ==
1593         GNUNET_DATASTORE_put (GSF_dsh, 0, &query, dsize, &put[1], type,
1594                               prq.priority, 1 /* anonymity */ ,
1595                               0 /* replication */ ,
1596                               expiration, 1 + prq.priority, MAX_DATASTORE_QUEUE,
1597                               GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1598                               &put_migration_continuation, pmc))
1599     {
1600       put_migration_continuation (pmc, GNUNET_SYSERR, GNUNET_TIME_UNIT_ZERO_ABS, NULL);
1601     }
1602   }
1603   else if (NULL != cp)
1604   {
1605     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1606                 "Choosing not to keep content `%s' (%d/%d)\n",
1607                 GNUNET_h2s (&query), active_to_migration,
1608                 test_put_load_too_high (prq.priority));
1609   }
1610   putl = GNUNET_LOAD_get_load (datastore_put_load);
1611   if ( (NULL != cp) && 
1612        (GNUNET_NO == prq.request_found) &&
1613        ( (GNUNET_YES != active_to_migration) ||
1614          (putl > 2.5 * (1 + prq.priority)) ) )
1615   {
1616     if (GNUNET_YES != active_to_migration)
1617       putl = 1.0 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 5);
1618     block_time =
1619         GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1620                                        5000 +
1621                                        GNUNET_CRYPTO_random_u32
1622                                        (GNUNET_CRYPTO_QUALITY_WEAK,
1623                                         (unsigned int) (60000 * putl * putl)));
1624     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
1625                 "Asking to stop migration for %llu ms because of load %f and events %d/%d\n",
1626                 (unsigned long long) block_time.rel_value,
1627                 putl,
1628                 active_to_migration,
1629                 (GNUNET_NO == prq.request_found));
1630     GSF_block_peer_migration_ (cp, GNUNET_TIME_relative_to_absolute (block_time));
1631   }
1632   return GNUNET_OK;
1633 }
1634
1635
1636 /**
1637  * Setup the subsystem.
1638  */
1639 void
1640 GSF_pending_request_init_ ()
1641 {
1642   unsigned long long dqs;
1643
1644   if (GNUNET_OK !=
1645       GNUNET_CONFIGURATION_get_value_number (GSF_cfg, "fs",
1646                                              "MAX_PENDING_REQUESTS",
1647                                              &max_pending_requests))
1648   {
1649     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_INFO,
1650                                "fs", "MAX_PENDING_REQUESTS");
1651   }
1652   if (GNUNET_OK !=
1653       GNUNET_CONFIGURATION_get_value_size (GSF_cfg, "fs", "DATASTORE_QUEUE_SIZE",
1654                                            &dqs))
1655   {
1656     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_INFO,
1657                                "fs", "DATASTORE_QUEUE_SIZE");
1658     dqs = 1024;
1659   }
1660   datastore_queue_size = (unsigned int) dqs;
1661
1662   active_to_migration =
1663       GNUNET_CONFIGURATION_get_value_yesno (GSF_cfg, "FS", "CONTENT_CACHING");
1664   datastore_put_load = GNUNET_LOAD_value_init (DATASTORE_LOAD_AUTODECLINE);
1665   pr_map = GNUNET_CONTAINER_multihashmap_create (32 * 1024, GNUNET_YES);
1666   requests_by_expiration_heap =
1667       GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1668 }
1669
1670
1671 /**
1672  * Shutdown the subsystem.
1673  */
1674 void
1675 GSF_pending_request_done_ ()
1676 {
1677   GNUNET_CONTAINER_multihashmap_iterate (pr_map, &clean_request, NULL);
1678   GNUNET_CONTAINER_multihashmap_destroy (pr_map);
1679   pr_map = NULL;
1680   GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
1681   requests_by_expiration_heap = NULL;
1682   GNUNET_LOAD_value_free (datastore_put_load);
1683   datastore_put_load = NULL;
1684 }
1685
1686
1687 /* end of gnunet-service-fs_pr.c */