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