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