glitch in the license text detected by hyazinthe, thank you!
[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 it
6      under the terms of the GNU Affero General Public License as published
7      by the Free Software Foundation, either version 3 of the License,
8      or (at your 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      Affero General Public License for more details.
14 */
15
16 /**
17  * @file fs/gnunet-service-fs_pr.c
18  * @brief API to handle pending requests
19  * @author Christian Grothoff
20  */
21 #include "platform.h"
22 #include "gnunet_util_lib.h"
23 #include "gnunet_load_lib.h"
24 #include "gnunet-service-fs.h"
25 #include "gnunet-service-fs_cp.h"
26 #include "gnunet-service-fs_indexing.h"
27 #include "gnunet-service-fs_pe.h"
28 #include "gnunet-service-fs_pr.h"
29 #include "gnunet-service-fs_cadet.h"
30
31
32 /**
33  * Desired replication level for GETs.
34  */
35 #define DHT_GET_REPLICATION 5
36
37 /**
38  * Maximum size of the datastore queue for P2P operations.  Needs to
39  * be large enough to queue #MAX_QUEUE_PER_PEER operations for roughly
40  * the number of active (connected) peers.
41  */
42 #define MAX_DATASTORE_QUEUE (16 * MAX_QUEUE_PER_PEER)
43
44 /**
45  * Bandwidth value of a 0-priority content (must be fairly high
46  * compared to query since content is typically significantly larger
47  * -- and more valueable since it can take many queries to get one
48  * piece of content).
49  */
50 #define CONTENT_BANDWIDTH_VALUE 800
51
52 /**
53  * Hard limit on the number of results we may get from the datastore per query.
54  */
55 #define MAX_RESULTS (100 * 1024)
56
57 /**
58  * Collect an instane number of statistics?  May cause excessive IPC.
59  */
60 #define INSANE_STATISTICS GNUNET_NO
61
62 /**
63  * If obtaining a block via cadet fails, how often do we retry it before
64  * giving up for good (and sticking to non-anonymous transfer)?
65  */
66 #define CADET_RETRY_MAX 3
67
68
69 /**
70  * An active request.
71  */
72 struct GSF_PendingRequest
73 {
74   /**
75    * Public data for the request.
76    */
77   struct GSF_PendingRequestData public_data;
78
79   /**
80    * Function to call if we encounter a reply.
81    */
82   GSF_PendingRequestReplyHandler rh;
83
84   /**
85    * Closure for @e rh
86    */
87   void *rh_cls;
88
89   /**
90    * Array of hash codes of replies we've already seen.
91    */
92   struct GNUNET_HashCode *replies_seen;
93
94   /**
95    * Block group for filtering replies we've already seen.
96    */
97   struct GNUNET_BLOCK_Group *bg;
98
99   /**
100    * Entry for this pending request in the expiration heap, or NULL.
101    */
102   struct GNUNET_CONTAINER_HeapNode *hnode;
103
104   /**
105    * Datastore queue entry for this request (or NULL for none).
106    */
107   struct GNUNET_DATASTORE_QueueEntry *qe;
108
109   /**
110    * DHT request handle for this request (or NULL for none).
111    */
112   struct GNUNET_DHT_GetHandle *gh;
113
114   /**
115    * Cadet request handle for this request (or NULL for none).
116    */
117   struct GSF_CadetRequest *cadet_request;
118
119   /**
120    * Function to call upon completion of the local get
121    * request, or NULL for none.
122    */
123   GSF_LocalLookupContinuation llc_cont;
124
125   /**
126    * Closure for @e llc_cont.
127    */
128   void *llc_cont_cls;
129
130   /**
131    * Last result from the local datastore lookup evaluation.
132    */
133   enum GNUNET_BLOCK_EvaluationResult local_result;
134
135   /**
136    * Identity of the peer that we should use for the 'sender'
137    * (recipient of the response) when forwarding (0 for none).
138    */
139   GNUNET_PEER_Id sender_pid;
140
141   /**
142    * Identity of the peer that we should never forward this query
143    * to since it originated this query (0 for none).
144    */
145   GNUNET_PEER_Id origin_pid;
146
147   /**
148    * Time we started the last datastore lookup.
149    */
150   struct GNUNET_TIME_Absolute qe_start;
151
152   /**
153    * Task that warns us if the local datastore lookup takes too long.
154    */
155   struct GNUNET_SCHEDULER_Task * warn_task;
156
157   /**
158    * Do we have a first UID yet?
159    */
160   bool have_first_uid;
161
162   /**
163    * Have we seen a NULL result yet?
164    */
165   bool seen_null;
166
167   /**
168    * Unique ID of the first result from the local datastore;
169    * used to terminate the loop.
170    */
171   uint64_t first_uid;
172
173   /**
174    * Result count.
175    */
176   size_t result_count;
177
178   /**
179    * How often have we retried this request via 'cadet'?
180    * (used to bound overall retries).
181    */
182   unsigned int cadet_retry_count;
183
184   /**
185    * Number of valid entries in the 'replies_seen' array.
186    */
187   unsigned int replies_seen_count;
188
189   /**
190    * Length of the 'replies_seen' array.
191    */
192   unsigned int replies_seen_size;
193
194 };
195
196
197 /**
198  * All pending requests, ordered by the query.  Entries
199  * are of type 'struct GSF_PendingRequest*'.
200  */
201 static struct GNUNET_CONTAINER_MultiHashMap *pr_map;
202
203
204 /**
205  * Datastore 'PUT' load tracking.
206  */
207 static struct GNUNET_LOAD_Value *datastore_put_load;
208
209
210 /**
211  * Are we allowed to migrate content to this peer.
212  */
213 static int active_to_migration;
214
215
216 /**
217  * Heap with the request that will expire next at the top.  Contains
218  * pointers of type "struct PendingRequest*"; these will *also* be
219  * aliased from the "requests_by_peer" data structures and the
220  * "requests_by_query" table.  Note that requests from our clients
221  * don't expire and are thus NOT in the "requests_by_expiration"
222  * (or the "requests_by_peer" tables).
223  */
224 static struct GNUNET_CONTAINER_Heap *requests_by_expiration_heap;
225
226
227 /**
228  * Maximum number of requests (from other peers, overall) that we're
229  * willing to have pending at any given point in time.  Can be changed
230  * via the configuration file (32k is just the default).
231  */
232 static unsigned long long max_pending_requests = (32 * 1024);
233
234
235
236 /**
237  * Recalculate our bloom filter for filtering replies.  This function
238  * will create a new bloom filter from scratch, so it should only be
239  * called if we have no bloomfilter at all (and hence can create a
240  * fresh one of minimal size without problems) OR if our peer is the
241  * initiator (in which case we may resize to larger than mimimum size).
242  *
243  * @param type type of the request
244  * @param pr request for which the BF is to be recomputed
245  */
246 static void
247 refresh_bloomfilter (enum GNUNET_BLOCK_Type type,
248                      struct GSF_PendingRequest *pr)
249 {
250   if (NULL != pr->bg)
251   {
252     GNUNET_BLOCK_group_destroy (pr->bg);
253     pr->bg = NULL;
254   }
255   if (GNUNET_BLOCK_TYPE_FS_UBLOCK != type)
256     return; /* no need */
257   pr->bg
258     = GNUNET_BLOCK_group_create (GSF_block_ctx,
259                                  type,
260                                  GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
261                                                            UINT32_MAX),
262                                  NULL,
263                                  0,
264                                  "seen-set-size",
265                                  pr->replies_seen_count,
266                                  NULL);
267   if (NULL == pr->bg)
268     return;
269   GNUNET_break (GNUNET_OK ==
270                 GNUNET_BLOCK_group_set_seen (pr->bg,
271                                              pr->replies_seen,
272                                              pr->replies_seen_count));
273 }
274
275
276 /**
277  * Create a new pending request.
278  *
279  * @param options request options
280  * @param type type of the block that is being requested
281  * @param query key for the lookup
282  * @param target preferred target for the request, NULL for none
283  * @param bf_data raw data for bloom filter for known replies, can be NULL
284  * @param bf_size number of bytes in @a bf_data
285  * @param mingle mingle value for bf
286  * @param anonymity_level desired anonymity level
287  * @param priority maximum outgoing cummulative request priority to use
288  * @param ttl current time-to-live for the request
289  * @param sender_pid peer ID to use for the sender when forwarding, 0 for none
290  * @param origin_pid peer ID of origin of query (do not loop back)
291  * @param replies_seen hash codes of known local replies
292  * @param replies_seen_count size of the @a replies_seen array
293  * @param rh handle to call when we get a reply
294  * @param rh_cls closure for @a rh
295  * @return handle for the new pending request
296  */
297 struct GSF_PendingRequest *
298 GSF_pending_request_create_ (enum GSF_PendingRequestOptions options,
299                              enum GNUNET_BLOCK_Type type,
300                              const struct GNUNET_HashCode *query,
301                              const struct GNUNET_PeerIdentity *target,
302                              const char *bf_data,
303                              size_t bf_size,
304                              uint32_t mingle,
305                              uint32_t anonymity_level,
306                              uint32_t priority,
307                              int32_t ttl,
308                              GNUNET_PEER_Id sender_pid,
309                              GNUNET_PEER_Id origin_pid,
310                              const struct GNUNET_HashCode *replies_seen,
311                              unsigned int replies_seen_count,
312                              GSF_PendingRequestReplyHandler rh,
313                              void *rh_cls)
314 {
315   struct GSF_PendingRequest *pr;
316   struct GSF_PendingRequest *dpr;
317   size_t extra;
318   struct GNUNET_HashCode *eptr;
319
320   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
321               "Creating request handle for `%s' of type %d\n",
322               GNUNET_h2s (query), type);
323 #if INSANE_STATISTICS
324   GNUNET_STATISTICS_update (GSF_stats,
325                             gettext_noop ("# Pending requests created"), 1,
326                             GNUNET_NO);
327 #endif
328   extra = 0;
329   if (NULL != target)
330     extra += sizeof (struct GNUNET_PeerIdentity);
331   pr = GNUNET_malloc (sizeof (struct GSF_PendingRequest) + extra);
332   pr->public_data.query = *query;
333   eptr = (struct GNUNET_HashCode *) &pr[1];
334   if (NULL != target)
335   {
336     pr->public_data.target = (struct GNUNET_PeerIdentity *) eptr;
337     GNUNET_memcpy (eptr,
338             target,
339             sizeof (struct GNUNET_PeerIdentity));
340   }
341   pr->public_data.anonymity_level = anonymity_level;
342   pr->public_data.priority = priority;
343   pr->public_data.original_priority = priority;
344   pr->public_data.options = options;
345   pr->public_data.type = type;
346   pr->public_data.start_time = GNUNET_TIME_absolute_get ();
347   pr->sender_pid = sender_pid;
348   pr->origin_pid = origin_pid;
349   pr->rh = rh;
350   pr->rh_cls = rh_cls;
351   GNUNET_assert ((sender_pid != 0) || (0 == (options & GSF_PRO_FORWARD_ONLY)));
352   if (ttl >= 0)
353     pr->public_data.ttl =
354         GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_multiply
355                                           (GNUNET_TIME_UNIT_SECONDS,
356                                            (uint32_t) ttl));
357   else
358     pr->public_data.ttl =
359         GNUNET_TIME_absolute_subtract (pr->public_data.start_time,
360                                        GNUNET_TIME_relative_multiply
361                                        (GNUNET_TIME_UNIT_SECONDS,
362                                         (uint32_t) (-ttl)));
363   if (replies_seen_count > 0)
364   {
365     pr->replies_seen_size = replies_seen_count;
366     pr->replies_seen = GNUNET_new_array (pr->replies_seen_size,
367                                          struct GNUNET_HashCode);
368     GNUNET_memcpy (pr->replies_seen,
369                    replies_seen,
370                    replies_seen_count * sizeof (struct GNUNET_HashCode));
371     pr->replies_seen_count = replies_seen_count;
372   }
373   if ( (NULL != bf_data) &&
374        (GNUNET_BLOCK_TYPE_FS_UBLOCK == pr->public_data.type) )
375   {
376     pr->bg
377       =  GNUNET_BLOCK_group_create (GSF_block_ctx,
378                                     pr->public_data.type,
379                                     mingle,
380                                     bf_data,
381                                     bf_size,
382                                     "seen-set-size",
383                                     0,
384                                     NULL);
385   }
386   else if ((replies_seen_count > 0) &&
387            (0 != (options & GSF_PRO_BLOOMFILTER_FULL_REFRESH)))
388   {
389     refresh_bloomfilter (pr->public_data.type,
390                          pr);
391   }
392   GNUNET_CONTAINER_multihashmap_put (pr_map,
393                                      &pr->public_data.query,
394                                      pr,
395                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
396   if (0 == (options & GSF_PRO_REQUEST_NEVER_EXPIRES))
397   {
398     pr->hnode =
399         GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
400                                       pr,
401                                       pr->public_data.ttl.abs_value_us);
402     /* make sure we don't track too many requests */
403     while (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) >
404            max_pending_requests)
405     {
406       dpr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
407       GNUNET_assert (NULL != dpr);
408       if (pr == dpr)
409         break;                  /* let the request live briefly... */
410       if (NULL != dpr->rh)
411         dpr->rh (dpr->rh_cls,
412                  GNUNET_BLOCK_EVALUATION_REQUEST_VALID,
413                  dpr,
414                  UINT32_MAX,
415                  GNUNET_TIME_UNIT_FOREVER_ABS,
416                  GNUNET_TIME_UNIT_FOREVER_ABS,
417                  GNUNET_BLOCK_TYPE_ANY,
418                  NULL,
419                  0);
420       GSF_pending_request_cancel_ (dpr,
421                                    GNUNET_YES);
422     }
423   }
424   GNUNET_STATISTICS_update (GSF_stats,
425                             gettext_noop ("# Pending requests active"), 1,
426                             GNUNET_NO);
427   return pr;
428 }
429
430 /**
431  * Obtain the public data associated with a pending request
432  *
433  * @param pr pending request
434  * @return associated public data
435  */
436 struct GSF_PendingRequestData *
437 GSF_pending_request_get_data_ (struct GSF_PendingRequest *pr)
438 {
439   return &pr->public_data;
440 }
441
442
443 /**
444  * Test if two pending requests are compatible (would generate
445  * the same query modulo filters and should thus be processed
446  * jointly).
447  *
448  * @param pra a pending request
449  * @param prb another pending request
450  * @return #GNUNET_OK if the requests are compatible
451  */
452 int
453 GSF_pending_request_is_compatible_ (struct GSF_PendingRequest *pra,
454                                     struct GSF_PendingRequest *prb)
455 {
456   if ( (pra->public_data.type != prb->public_data.type) ||
457        (0 != memcmp (&pra->public_data.query,
458                      &prb->public_data.query,
459                      sizeof (struct GNUNET_HashCode))))
460     return GNUNET_NO;
461   return GNUNET_OK;
462 }
463
464
465 /**
466  * Update a given pending request with additional replies
467  * that have been seen.
468  *
469  * @param pr request to update
470  * @param replies_seen hash codes of replies that we've seen
471  * @param replies_seen_count size of the replies_seen array
472  */
473 void
474 GSF_pending_request_update_ (struct GSF_PendingRequest *pr,
475                              const struct GNUNET_HashCode * replies_seen,
476                              unsigned int replies_seen_count)
477 {
478   if (replies_seen_count + pr->replies_seen_count < pr->replies_seen_count)
479     return;                     /* integer overflow */
480   if (0 != (pr->public_data.options & GSF_PRO_BLOOMFILTER_FULL_REFRESH))
481   {
482     /* we're responsible for the BF, full refresh */
483     if (replies_seen_count + pr->replies_seen_count > pr->replies_seen_size)
484       GNUNET_array_grow (pr->replies_seen,
485                          pr->replies_seen_size,
486                          replies_seen_count + pr->replies_seen_count);
487     GNUNET_memcpy (&pr->replies_seen[pr->replies_seen_count],
488                    replies_seen,
489                    sizeof (struct GNUNET_HashCode) * replies_seen_count);
490     pr->replies_seen_count += replies_seen_count;
491     refresh_bloomfilter (pr->public_data.type,
492                          pr);
493   }
494   else
495   {
496     if (NULL == pr->bg)
497     {
498       /* we're not the initiator, but the initiator did not give us
499        * any bloom-filter, so we need to create one on-the-fly */
500       refresh_bloomfilter (pr->public_data.type,
501                            pr);
502     }
503     else
504     {
505       GNUNET_break (GNUNET_OK ==
506                     GNUNET_BLOCK_group_set_seen (pr->bg,
507                                                  replies_seen,
508                                                  pr->replies_seen_count));
509     }
510   }
511   if (NULL != pr->gh)
512     GNUNET_DHT_get_filter_known_results (pr->gh,
513                                          replies_seen_count,
514                                          replies_seen);
515 }
516
517
518 /**
519  * Generate the message corresponding to the given pending request for
520  * transmission to other peers.
521  *
522  * @param pr request to generate the message for
523  * @return envelope with the request message
524  */
525 struct GNUNET_MQ_Envelope *
526 GSF_pending_request_get_message_ (struct GSF_PendingRequest *pr)
527 {
528   struct GNUNET_MQ_Envelope *env;
529   struct GetMessage *gm;
530   struct GNUNET_PeerIdentity *ext;
531   unsigned int k;
532   uint32_t bm;
533   uint32_t prio;
534   size_t bf_size;
535   struct GNUNET_TIME_Absolute now;
536   int64_t ttl;
537   int do_route;
538   void *bf_data;
539   uint32_t bf_nonce;
540
541   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
542               "Building request message for `%s' of type %d\n",
543               GNUNET_h2s (&pr->public_data.query),
544               pr->public_data.type);
545   k = 0;
546   bm = 0;
547   do_route = (0 == (pr->public_data.options & GSF_PRO_FORWARD_ONLY));
548   if ((!do_route) && (pr->sender_pid == 0))
549   {
550     GNUNET_break (0);
551     do_route = GNUNET_YES;
552   }
553   if (!do_route)
554   {
555     bm |= GET_MESSAGE_BIT_RETURN_TO;
556     k++;
557   }
558   if (NULL != pr->public_data.target)
559   {
560     bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
561     k++;
562   }
563   if (GNUNET_OK !=
564       GNUNET_BLOCK_group_serialize (pr->bg,
565                                     &bf_nonce,
566                                     &bf_data,
567                                     &bf_size))
568   {
569     bf_size = 0;
570     bf_data = NULL;
571   }
572   env = GNUNET_MQ_msg_extra (gm,
573                              bf_size + k * sizeof (struct GNUNET_PeerIdentity),
574                              GNUNET_MESSAGE_TYPE_FS_GET);
575   gm->type = htonl (pr->public_data.type);
576   if (do_route)
577     prio =
578         GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
579                                   pr->public_data.priority + 1);
580   else
581     prio = 0;
582   pr->public_data.priority -= prio;
583   pr->public_data.num_transmissions++;
584   pr->public_data.respect_offered += prio;
585   gm->priority = htonl (prio);
586   now = GNUNET_TIME_absolute_get ();
587   ttl = (int64_t) (pr->public_data.ttl.abs_value_us - now.abs_value_us);
588   gm->ttl = htonl (ttl / 1000LL / 1000LL);
589   gm->filter_mutator = htonl (bf_nonce);
590   gm->hash_bitmap = htonl (bm);
591   gm->query = pr->public_data.query;
592   ext = (struct GNUNET_PeerIdentity *) &gm[1];
593   k = 0;
594   if (! do_route)
595     GNUNET_PEER_resolve (pr->sender_pid,
596                          &ext[k++]);
597   if (NULL != pr->public_data.target)
598     ext[k++] = *pr->public_data.target;
599   GNUNET_memcpy (&ext[k],
600                  bf_data,
601                  bf_size);
602   GNUNET_free_non_null (bf_data);
603   return env;
604 }
605
606
607 /**
608  * Iterator to free pending requests.
609  *
610  * @param cls closure, unused
611  * @param key current key code
612  * @param value value in the hash map (pending request)
613  * @return #GNUNET_YES (we should continue to iterate)
614  */
615 static int
616 clean_request (void *cls,
617                const struct GNUNET_HashCode *key,
618                void *value)
619 {
620   struct GSF_PendingRequest *pr = value;
621   GSF_LocalLookupContinuation cont;
622
623   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
624               "Cleaning up pending request for `%s'.\n",
625               GNUNET_h2s (key));
626   if (NULL != pr->cadet_request)
627   {
628     pr->cadet_retry_count = CADET_RETRY_MAX;
629     GSF_cadet_query_cancel (pr->cadet_request);
630     pr->cadet_request = NULL;
631   }
632   if (NULL != (cont = pr->llc_cont))
633   {
634     pr->llc_cont = NULL;
635     cont (pr->llc_cont_cls,
636           pr,
637           pr->local_result);
638   }
639   GSF_plan_notify_request_done_ (pr);
640   GNUNET_free_non_null (pr->replies_seen);
641   GNUNET_BLOCK_group_destroy (pr->bg);
642   pr->bg = NULL;
643   GNUNET_PEER_change_rc (pr->sender_pid, -1);
644   pr->sender_pid = 0;
645   GNUNET_PEER_change_rc (pr->origin_pid, -1);
646   pr->origin_pid = 0;
647   if (NULL != pr->hnode)
648   {
649     GNUNET_CONTAINER_heap_remove_node (pr->hnode);
650     pr->hnode = NULL;
651   }
652   if (NULL != pr->qe)
653   {
654     GNUNET_DATASTORE_cancel (pr->qe);
655     pr->qe = NULL;
656   }
657   if (NULL != pr->gh)
658   {
659     GNUNET_DHT_get_stop (pr->gh);
660     pr->gh = NULL;
661   }
662   if (NULL != pr->warn_task)
663   {
664     GNUNET_SCHEDULER_cancel (pr->warn_task);
665     pr->warn_task = NULL;
666   }
667   GNUNET_assert (GNUNET_OK ==
668                  GNUNET_CONTAINER_multihashmap_remove (pr_map,
669                                                        &pr->public_data.query,
670                                                        pr));
671   GNUNET_STATISTICS_update (GSF_stats,
672                             gettext_noop ("# Pending requests active"),
673                             -1,
674                             GNUNET_NO);
675   GNUNET_free (pr);
676   return GNUNET_YES;
677 }
678
679
680 /**
681  * Explicitly cancel a pending request.
682  *
683  * @param pr request to cancel
684  * @param full_cleanup fully purge the request
685  */
686 void
687 GSF_pending_request_cancel_ (struct GSF_PendingRequest *pr,
688                              int full_cleanup)
689 {
690   GSF_LocalLookupContinuation cont;
691
692   if (NULL == pr_map)
693     return;                     /* already cleaned up! */
694   if (GNUNET_NO == full_cleanup)
695   {
696     /* make request inactive (we're no longer interested in more results),
697      * but do NOT remove from our data-structures, we still need it there
698      * to prevent the request from looping */
699     pr->rh = NULL;
700     if (NULL != pr->cadet_request)
701     {
702       pr->cadet_retry_count = CADET_RETRY_MAX;
703       GSF_cadet_query_cancel (pr->cadet_request);
704       pr->cadet_request = NULL;
705     }
706     if (NULL != (cont = pr->llc_cont))
707     {
708       pr->llc_cont = NULL;
709       cont (pr->llc_cont_cls,
710             pr,
711             pr->local_result);
712     }
713     GSF_plan_notify_request_done_ (pr);
714     if (NULL != pr->qe)
715     {
716       GNUNET_DATASTORE_cancel (pr->qe);
717       pr->qe = NULL;
718     }
719     if (NULL != pr->gh)
720     {
721       GNUNET_DHT_get_stop (pr->gh);
722       pr->gh = NULL;
723     }
724     if (NULL != pr->warn_task)
725     {
726       GNUNET_SCHEDULER_cancel (pr->warn_task);
727       pr->warn_task = NULL;
728     }
729     return;
730   }
731   GNUNET_assert (GNUNET_YES ==
732                  clean_request (NULL,
733                                 &pr->public_data.query,
734                                 pr));
735 }
736
737
738 /**
739  * Iterate over all pending requests.
740  *
741  * @param it function to call for each request
742  * @param cls closure for @a it
743  */
744 void
745 GSF_iterate_pending_requests_ (GSF_PendingRequestIterator it, void *cls)
746 {
747   GNUNET_CONTAINER_multihashmap_iterate (pr_map,
748                                          (GNUNET_CONTAINER_HashMapIterator) it,
749                                          cls);
750 }
751
752
753 /**
754  * Closure for process_reply() function.
755  */
756 struct ProcessReplyClosure
757 {
758   /**
759    * The data for the reply.
760    */
761   const void *data;
762
763   /**
764    * Who gave us this reply? NULL for local host (or DHT)
765    */
766   struct GSF_ConnectedPeer *sender;
767
768   /**
769    * When the reply expires.
770    */
771   struct GNUNET_TIME_Absolute expiration;
772
773   /**
774    * Size of data.
775    */
776   size_t size;
777
778   /**
779    * Type of the block.
780    */
781   enum GNUNET_BLOCK_Type type;
782
783   /**
784    * Control flags for evaluation.
785    */
786   enum GNUNET_BLOCK_EvaluationOptions eo;
787
788   /**
789    * How much was this reply worth to us?
790    */
791   uint32_t priority;
792
793   /**
794    * Anonymity requirements for this reply.
795    */
796   uint32_t anonymity_level;
797
798   /**
799    * Evaluation result (returned).
800    */
801   enum GNUNET_BLOCK_EvaluationResult eval;
802
803   /**
804    * Did we find a matching request?
805    */
806   int request_found;
807 };
808
809
810 /**
811  * Update the performance data for the sender (if any) since
812  * the sender successfully answered one of our queries.
813  *
814  * @param prq information about the sender
815  * @param pr request that was satisfied
816  */
817 static void
818 update_request_performance_data (struct ProcessReplyClosure *prq,
819                                  struct GSF_PendingRequest *pr)
820 {
821   if (prq->sender == NULL)
822     return;
823   GSF_peer_update_performance_ (prq->sender, pr->public_data.start_time,
824                                 prq->priority);
825 }
826
827
828 /**
829  * We have received a reply; handle it!
830  *
831  * @param cls response (a `struct ProcessReplyClosure`)
832  * @param key our query
833  * @param value value in the hash map (info about the query)
834  * @return #GNUNET_YES (we should continue to iterate)
835  */
836 static int
837 process_reply (void *cls,
838                const struct GNUNET_HashCode *key,
839                void *value)
840 {
841   struct ProcessReplyClosure *prq = cls;
842   struct GSF_PendingRequest *pr = value;
843   struct GNUNET_HashCode chash;
844   struct GNUNET_TIME_Absolute last_transmission;
845
846   if (NULL == pr->rh)
847     return GNUNET_YES;
848   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
849               "Matched result (type %u) for query `%s' with pending request\n",
850               (unsigned int) prq->type,
851               GNUNET_h2s (key));
852   GNUNET_STATISTICS_update (GSF_stats,
853                             gettext_noop ("# replies received and matched"), 1,
854                             GNUNET_NO);
855   prq->eval =
856       GNUNET_BLOCK_evaluate (GSF_block_ctx,
857                              prq->type,
858                              pr->bg,
859                              prq->eo,
860                              key,
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_saturating_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     GNUNET_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 /* Call our continuation (if we have any) */
1339 static void
1340 call_continuation (struct GSF_PendingRequest *pr)
1341 {
1342   GSF_LocalLookupContinuation cont = pr->llc_cont;
1343
1344   GNUNET_assert (NULL == pr->qe);
1345   if (NULL != pr->warn_task)
1346   {
1347     GNUNET_SCHEDULER_cancel (pr->warn_task);
1348     pr->warn_task = NULL;
1349   }
1350   if (NULL == cont)
1351     return;                     /* no continuation */
1352   pr->llc_cont = NULL;
1353   if (0 != (GSF_PRO_LOCAL_ONLY & pr->public_data.options))
1354   {
1355     if (GNUNET_BLOCK_EVALUATION_OK_LAST != pr->local_result)
1356     {
1357       /* Signal that we are done and that there won't be any
1358          additional results to allow client to clean up state. */
1359       pr->rh (pr->rh_cls,
1360                GNUNET_BLOCK_EVALUATION_OK_LAST,
1361                pr,
1362                UINT32_MAX,
1363                GNUNET_TIME_UNIT_ZERO_ABS,
1364                GNUNET_TIME_UNIT_FOREVER_ABS,
1365                GNUNET_BLOCK_TYPE_ANY,
1366                NULL,
1367                0);
1368     }
1369     /* Finally, call our continuation to signal that we are
1370        done with local processing of this request; i.e. to
1371        start reading again from the client. */
1372     cont (pr->llc_cont_cls, NULL, GNUNET_BLOCK_EVALUATION_OK_LAST);
1373     return;
1374   }
1375
1376   cont (pr->llc_cont_cls, pr, pr->local_result);
1377 }
1378
1379
1380 /* Update stats and call continuation */
1381 static void
1382 no_more_local_results (struct GSF_PendingRequest *pr)
1383 {
1384   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1385               "No further local responses available.\n");
1386 #if INSANE_STATISTICS
1387   if ( (GNUNET_BLOCK_TYPE_FS_DBLOCK == pr->public_data.type) ||
1388        (GNUNET_BLOCK_TYPE_FS_IBLOCK == pr->public_data.type) )
1389     GNUNET_STATISTICS_update (GSF_stats,
1390                               gettext_noop ("# requested DBLOCK or IBLOCK not found"),
1391                               1,
1392                               GNUNET_NO);
1393 #endif
1394   call_continuation (pr);
1395 }
1396
1397
1398 /* forward declaration */
1399 static void
1400 process_local_reply (void *cls,
1401                      const struct GNUNET_HashCode *key,
1402                      size_t size,
1403                      const void *data,
1404                      enum GNUNET_BLOCK_Type type,
1405                      uint32_t priority,
1406                      uint32_t anonymity,
1407                      uint32_t replication,
1408                      struct GNUNET_TIME_Absolute expiration,
1409                      uint64_t uid);
1410
1411
1412 /* Start a local query */
1413 static void
1414 start_local_query (struct GSF_PendingRequest *pr,
1415                    uint64_t next_uid,
1416                    bool random)
1417 {
1418   pr->qe_start = GNUNET_TIME_absolute_get ();
1419   pr->warn_task =
1420       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1421                                     &warn_delay_task,
1422                                     pr);
1423   pr->qe =
1424       GNUNET_DATASTORE_get_key (GSF_dsh,
1425                                 next_uid,
1426                                 random,
1427                                 &pr->public_data.query,
1428                                 pr->public_data.type ==
1429                                 GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1430                                 GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1431                                 (0 !=
1432                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1433                                   public_data.options)) ? UINT_MAX : 1
1434                                 /* queue priority */ ,
1435                                 (0 !=
1436                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1437                                   public_data.options)) ? UINT_MAX :
1438                                 GSF_datastore_queue_size
1439                                 /* max queue size */ ,
1440                                 &process_local_reply, pr);
1441   if (NULL != pr->qe)
1442     return;
1443   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1444               "ERROR Requesting `%s' of type %d with next_uid %llu from datastore.\n",
1445               GNUNET_h2s (&pr->public_data.query),
1446               pr->public_data.type,
1447               (unsigned long long) next_uid);
1448   GNUNET_STATISTICS_update (GSF_stats,
1449                             gettext_noop ("# Datastore lookups concluded (error queueing)"),
1450                             1,
1451                             GNUNET_NO);
1452   call_continuation (pr);
1453 }
1454
1455
1456 /**
1457  * We're processing (local) results for a search request
1458  * from another peer.  Pass applicable results to the
1459  * peer and if we are done either clean up (operation
1460  * complete) or forward to other peers (more results possible).
1461  *
1462  * @param cls our closure (`struct GSF_PendingRequest *`)
1463  * @param key key for the content
1464  * @param size number of bytes in @a data
1465  * @param data content stored
1466  * @param type type of the content
1467  * @param priority priority of the content
1468  * @param anonymity anonymity-level for the content
1469  * @param replication replication-level for the content
1470  * @param expiration expiration time for the content
1471  * @param uid unique identifier for the datum;
1472  *        maybe 0 if no unique identifier is available
1473  */
1474 static void
1475 process_local_reply (void *cls,
1476                      const struct GNUNET_HashCode *key,
1477                      size_t size,
1478                      const void *data,
1479                      enum GNUNET_BLOCK_Type type,
1480                      uint32_t priority,
1481                      uint32_t anonymity,
1482                      uint32_t replication,
1483                      struct GNUNET_TIME_Absolute expiration,
1484                      uint64_t uid)
1485 {
1486   struct GSF_PendingRequest *pr = cls;
1487   struct ProcessReplyClosure prq;
1488   struct GNUNET_HashCode query;
1489   unsigned int old_rf;
1490
1491   GNUNET_SCHEDULER_cancel (pr->warn_task);
1492   pr->warn_task = NULL;
1493   if (NULL == pr->qe)
1494     goto called_from_on_demand;
1495   pr->qe = NULL;
1496   if ( (NULL == key) &&
1497        pr->seen_null &&
1498        !pr->have_first_uid) /* We have hit the end for the 2nd time with no results */
1499   {
1500     /* No results */
1501 #if INSANE_STATISTICS
1502     GNUNET_STATISTICS_update (GSF_stats,
1503                               gettext_noop
1504                               ("# Datastore lookups concluded (no results)"),
1505                               1, GNUNET_NO);
1506 #endif
1507     no_more_local_results (pr);
1508     return;
1509   }
1510   if ( ( (NULL == key) &&
1511          pr->seen_null ) || /* We have hit the end for the 2nd time OR */
1512        ( pr->seen_null &&
1513          pr->have_first_uid &&
1514          (uid >= pr->first_uid) ) ) /* We have hit the end and past first UID */
1515   {
1516     /* Seen all results */
1517     GNUNET_STATISTICS_update (GSF_stats,
1518                               gettext_noop
1519                               ("# Datastore lookups concluded (seen all)"),
1520                               1, GNUNET_NO);
1521     no_more_local_results (pr);
1522     return;
1523   }
1524   if (NULL == key)
1525   {
1526     GNUNET_assert (!pr->seen_null);
1527     pr->seen_null = true;
1528     start_local_query (pr,
1529                        0 /* next_uid */,
1530                        false /* random */);
1531     return;
1532   }
1533   if (!pr->have_first_uid)
1534   {
1535     pr->first_uid = uid;
1536     pr->have_first_uid = true;
1537   }
1538   pr->result_count++;
1539   if (pr->result_count > MAX_RESULTS)
1540   {
1541     GNUNET_STATISTICS_update (GSF_stats,
1542                               gettext_noop
1543                               ("# Datastore lookups aborted (more than MAX_RESULTS)"),
1544                               1, GNUNET_NO);
1545     no_more_local_results (pr);
1546     return;
1547   }
1548   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1549               "Received reply for `%s' of type %d with UID %llu from datastore.\n",
1550               GNUNET_h2s (key), type, (unsigned long long) uid);
1551   if (GNUNET_BLOCK_TYPE_FS_ONDEMAND == type)
1552   {
1553     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1554                 "Found ONDEMAND block, performing on-demand encoding\n");
1555     GNUNET_STATISTICS_update (GSF_stats,
1556                               gettext_noop
1557                               ("# on-demand blocks matched requests"), 1,
1558                               GNUNET_NO);
1559     pr->qe_start = GNUNET_TIME_absolute_get ();
1560     pr->warn_task =
1561         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1562                                       &odc_warn_delay_task, pr);
1563     if (GNUNET_OK ==
1564         GNUNET_FS_handle_on_demand_block (key,
1565                                           size,
1566                                           data,
1567                                           type,
1568                                           priority,
1569                                           anonymity,
1570                                           replication,
1571                                           expiration,
1572                                           uid,
1573                                           &process_local_reply,
1574                                           pr))
1575     {
1576       GNUNET_STATISTICS_update (GSF_stats,
1577                                 gettext_noop
1578                                 ("# on-demand lookups performed successfully"),
1579                                 1, GNUNET_NO);
1580       return;                   /* we're done */
1581     }
1582     GNUNET_STATISTICS_update (GSF_stats,
1583                               gettext_noop ("# on-demand lookups failed"), 1,
1584                               GNUNET_NO);
1585     GNUNET_SCHEDULER_cancel (pr->warn_task);
1586     start_local_query (pr,
1587                        uid + 1 /* next_uid */,
1588                        false /* random */);
1589     return;
1590   }
1591 called_from_on_demand:
1592   old_rf = pr->public_data.results_found;
1593   memset (&prq, 0, sizeof (prq));
1594   prq.data = data;
1595   prq.expiration = expiration;
1596   prq.size = size;
1597   if (GNUNET_OK !=
1598       GNUNET_BLOCK_get_key (GSF_block_ctx, type, data, size, &query))
1599   {
1600     GNUNET_break (0);
1601     GNUNET_DATASTORE_remove (GSF_dsh, key, size, data, -1, -1,
1602                              NULL, NULL);
1603     start_local_query (pr,
1604                        uid + 1 /* next_uid */,
1605                        false /* random */);
1606     return;
1607   }
1608   prq.type = type;
1609   prq.priority = priority;
1610   prq.request_found = GNUNET_NO;
1611   prq.anonymity_level = anonymity;
1612   if ((0 == old_rf) && (0 == pr->public_data.results_found))
1613     GSF_update_datastore_delay_ (pr->public_data.start_time);
1614   prq.eo = GNUNET_BLOCK_EO_LOCAL_SKIP_CRYPTO;
1615   process_reply (&prq, key, pr);
1616   pr->local_result = prq.eval;
1617   if (GNUNET_BLOCK_EVALUATION_OK_LAST == prq.eval)
1618   {
1619     GNUNET_STATISTICS_update (GSF_stats,
1620                               gettext_noop
1621                               ("# Datastore lookups concluded (found last result)"),
1622                               1,
1623                               GNUNET_NO);
1624     call_continuation (pr);
1625     return;
1626   }
1627   if ((0 == (GSF_PRO_PRIORITY_UNLIMITED & pr->public_data.options)) &&
1628       ((GNUNET_YES == GSF_test_get_load_too_high_ (0)) ||
1629        (pr->public_data.results_found > 5 + 2 * pr->public_data.priority)))
1630   {
1631     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1632                 "Load too high, done with request\n");
1633     GNUNET_STATISTICS_update (GSF_stats,
1634                               gettext_noop ("# Datastore lookups concluded (load too high)"),
1635                               1,
1636                               GNUNET_NO);
1637     call_continuation (pr);
1638     return;
1639   }
1640   start_local_query (pr,
1641                      uid + 1 /* next_uid */,
1642                      false /* random */);
1643 }
1644
1645
1646 /**
1647  * Is the given target a legitimate peer for forwarding the given request?
1648  *
1649  * @param pr request
1650  * @param target
1651  * @return #GNUNET_YES if this request could be forwarded to the given peer
1652  */
1653 int
1654 GSF_pending_request_test_target_ (struct GSF_PendingRequest *pr,
1655                                   const struct GNUNET_PeerIdentity *target)
1656 {
1657   struct GNUNET_PeerIdentity pi;
1658
1659   if (0 == pr->origin_pid)
1660     return GNUNET_YES;
1661   GNUNET_PEER_resolve (pr->origin_pid, &pi);
1662   return (0 ==
1663           memcmp (&pi, target,
1664                   sizeof (struct GNUNET_PeerIdentity))) ? GNUNET_NO :
1665       GNUNET_YES;
1666 }
1667
1668
1669 /**
1670  * Look up the request in the local datastore.
1671  *
1672  * @param pr the pending request to process
1673  * @param cont function to call at the end
1674  * @param cont_cls closure for @a cont
1675  */
1676 void
1677 GSF_local_lookup_ (struct GSF_PendingRequest *pr,
1678                    GSF_LocalLookupContinuation cont,
1679                    void *cont_cls)
1680 {
1681   GNUNET_assert (NULL == pr->gh);
1682   GNUNET_assert (NULL == pr->cadet_request);
1683   GNUNET_assert (NULL == pr->llc_cont);
1684   pr->llc_cont = cont;
1685   pr->llc_cont_cls = cont_cls;
1686 #if INSANE_STATISTICS
1687   GNUNET_STATISTICS_update (GSF_stats,
1688                             gettext_noop ("# Datastore lookups initiated"), 1,
1689                             GNUNET_NO);
1690 #endif
1691   start_local_query(pr,
1692                     0 /* next_uid */,
1693                     true /* random */);
1694 }
1695
1696
1697
1698 /**
1699  * Handle P2P "CONTENT" message.  Checks that the message is
1700  * well-formed and then checks if there are any pending requests for
1701  * this content and possibly passes it on (to local clients or other
1702  * peers).  Does NOT perform migration (content caching at this peer).
1703  *
1704  * @param cls the other peer involved
1705  * @param put the actual message
1706  */
1707 void
1708 handle_p2p_put (void *cls,
1709                 const struct PutMessage *put)
1710 {
1711   struct GSF_ConnectedPeer *cp = cls;
1712   uint16_t msize;
1713   size_t dsize;
1714   enum GNUNET_BLOCK_Type type;
1715   struct GNUNET_TIME_Absolute expiration;
1716   struct GNUNET_HashCode query;
1717   struct ProcessReplyClosure prq;
1718   struct GNUNET_TIME_Relative block_time;
1719   double putl;
1720   struct PutMigrationContext *pmc;
1721
1722   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1723               "Received P2P PUT from %s\n",
1724               GNUNET_i2s (GSF_get_peer_performance_data_ (cp)->peer));
1725   GSF_cover_content_count++;
1726   msize = ntohs (put->header.size);
1727   dsize = msize - sizeof (struct PutMessage);
1728   type = ntohl (put->type);
1729   expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
1730   /* do not allow migrated content to live longer than 1 year */
1731   expiration = GNUNET_TIME_absolute_min (GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_YEARS),
1732                                          expiration);
1733   if (GNUNET_OK !=
1734       GNUNET_BLOCK_get_key (GSF_block_ctx,
1735                             type,
1736                             &put[1],
1737                             dsize,
1738                             &query))
1739   {
1740     GNUNET_break_op (0);
1741     return;
1742   }
1743   GNUNET_STATISTICS_update (GSF_stats,
1744                             gettext_noop ("# GAP PUT messages received"),
1745                             1,
1746                             GNUNET_NO);
1747   /* now, lookup 'query' */
1748   prq.data = (const void *) &put[1];
1749   prq.sender = cp;
1750   prq.size = dsize;
1751   prq.type = type;
1752   prq.expiration = expiration;
1753   prq.priority = 0;
1754   prq.anonymity_level = UINT32_MAX;
1755   prq.request_found = GNUNET_NO;
1756   prq.eo = GNUNET_BLOCK_EO_NONE;
1757   GNUNET_CONTAINER_multihashmap_get_multiple (pr_map,
1758                                               &query,
1759                                               &process_reply,
1760                                               &prq);
1761   if (NULL != cp)
1762   {
1763     GSF_connected_peer_change_preference_ (cp,
1764                                            CONTENT_BANDWIDTH_VALUE +
1765                                            1000 * prq.priority);
1766     GSF_get_peer_performance_data_ (cp)->respect += prq.priority;
1767   }
1768   if ((GNUNET_YES == active_to_migration) &&
1769       (NULL != cp) &&
1770       (GNUNET_NO == test_put_load_too_high (prq.priority)))
1771   {
1772     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1773                 "Replicating result for query `%s' with priority %u\n",
1774                 GNUNET_h2s (&query),
1775                 prq.priority);
1776     pmc = GNUNET_new (struct PutMigrationContext);
1777     pmc->start = GNUNET_TIME_absolute_get ();
1778     pmc->requested = prq.request_found;
1779     GNUNET_assert (0 != GSF_get_peer_performance_data_ (cp)->pid);
1780     GNUNET_PEER_resolve (GSF_get_peer_performance_data_ (cp)->pid,
1781                          &pmc->origin);
1782     if (NULL ==
1783         GNUNET_DATASTORE_put (GSF_dsh,
1784                               0,
1785                               &query,
1786                               dsize,
1787                               &put[1],
1788                               type,
1789                               prq.priority,
1790                               1 /* anonymity */ ,
1791                               0 /* replication */ ,
1792                               expiration, 1 + prq.priority,
1793                               MAX_DATASTORE_QUEUE,
1794                               &put_migration_continuation,
1795                               pmc))
1796     {
1797       put_migration_continuation (pmc,
1798                                   GNUNET_SYSERR,
1799                                   GNUNET_TIME_UNIT_ZERO_ABS,
1800                                   NULL);
1801     }
1802   }
1803   else if (NULL != cp)
1804   {
1805     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1806                 "Choosing not to keep content `%s' (%d/%d)\n",
1807                 GNUNET_h2s (&query),
1808                 active_to_migration,
1809                 test_put_load_too_high (prq.priority));
1810   }
1811   putl = GNUNET_LOAD_get_load (datastore_put_load);
1812   if ( (NULL != cp) &&
1813        (GNUNET_NO == prq.request_found) &&
1814        ( (GNUNET_YES != active_to_migration) ||
1815          (putl > 2.5 * (1 + prq.priority)) ) )
1816   {
1817     if (GNUNET_YES != active_to_migration)
1818       putl = 1.0 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 5);
1819     block_time =
1820         GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1821                                        5000 +
1822                                        GNUNET_CRYPTO_random_u32
1823                                        (GNUNET_CRYPTO_QUALITY_WEAK,
1824                                         (unsigned int) (60000 * putl * putl)));
1825     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1826                 "Asking to stop migration for %s because of load %f and events %d/%d\n",
1827                 GNUNET_STRINGS_relative_time_to_string (block_time,
1828                                                         GNUNET_YES),
1829                 putl,
1830                 active_to_migration,
1831                 (GNUNET_NO == prq.request_found));
1832     GSF_block_peer_migration_ (cp,
1833                                GNUNET_TIME_relative_to_absolute (block_time));
1834   }
1835 }
1836
1837
1838 /**
1839  * Check if the given request is still active.
1840  *
1841  * @param pr pending request
1842  * @return #GNUNET_YES if the request is still active
1843  */
1844 int
1845 GSF_pending_request_test_active_ (struct GSF_PendingRequest *pr)
1846 {
1847   return (NULL != pr->rh) ? GNUNET_YES : GNUNET_NO;
1848 }
1849
1850
1851 /**
1852  * Setup the subsystem.
1853  */
1854 void
1855 GSF_pending_request_init_ ()
1856 {
1857   if (GNUNET_OK !=
1858       GNUNET_CONFIGURATION_get_value_number (GSF_cfg, "fs",
1859                                              "MAX_PENDING_REQUESTS",
1860                                              &max_pending_requests))
1861   {
1862     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_INFO,
1863                                "fs", "MAX_PENDING_REQUESTS");
1864   }
1865   active_to_migration =
1866       GNUNET_CONFIGURATION_get_value_yesno (GSF_cfg, "FS", "CONTENT_CACHING");
1867   datastore_put_load = GNUNET_LOAD_value_init (DATASTORE_LOAD_AUTODECLINE);
1868   pr_map = GNUNET_CONTAINER_multihashmap_create (32 * 1024, GNUNET_YES);
1869   requests_by_expiration_heap =
1870       GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1871 }
1872
1873
1874 /**
1875  * Shutdown the subsystem.
1876  */
1877 void
1878 GSF_pending_request_done_ ()
1879 {
1880   GNUNET_CONTAINER_multihashmap_iterate (pr_map,
1881                                          &clean_request,
1882                                          NULL);
1883   GNUNET_CONTAINER_multihashmap_destroy (pr_map);
1884   pr_map = NULL;
1885   GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
1886   requests_by_expiration_heap = NULL;
1887   GNUNET_LOAD_value_free (datastore_put_load);
1888   datastore_put_load = NULL;
1889 }
1890
1891
1892 /* end of gnunet-service-fs_pr.c */