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