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