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