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