rps tests: cosmetics
[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    * Do we have a first UID yet?
164    */
165   bool have_first_uid;
166
167   /**
168    * Have we seen a NULL result yet?
169    */
170   bool seen_null;
171
172   /**
173    * Unique ID of the first result from the local datastore;
174    * used to terminate the loop.
175    */
176   uint64_t first_uid;
177
178   /**
179    * Result count.
180    */
181   size_t result_count;
182
183   /**
184    * How often have we retried this request via 'cadet'?
185    * (used to bound overall retries).
186    */
187   unsigned int cadet_retry_count;
188
189   /**
190    * Number of valid entries in the 'replies_seen' array.
191    */
192   unsigned int replies_seen_count;
193
194   /**
195    * Length of the 'replies_seen' array.
196    */
197   unsigned int replies_seen_size;
198
199 };
200
201
202 /**
203  * All pending requests, ordered by the query.  Entries
204  * are of type 'struct GSF_PendingRequest*'.
205  */
206 static struct GNUNET_CONTAINER_MultiHashMap *pr_map;
207
208
209 /**
210  * Datastore 'PUT' load tracking.
211  */
212 static struct GNUNET_LOAD_Value *datastore_put_load;
213
214
215 /**
216  * Are we allowed to migrate content to this peer.
217  */
218 static int active_to_migration;
219
220
221 /**
222  * Heap with the request that will expire next at the top.  Contains
223  * pointers of type "struct PendingRequest*"; these will *also* be
224  * aliased from the "requests_by_peer" data structures and the
225  * "requests_by_query" table.  Note that requests from our clients
226  * don't expire and are thus NOT in the "requests_by_expiration"
227  * (or the "requests_by_peer" tables).
228  */
229 static struct GNUNET_CONTAINER_Heap *requests_by_expiration_heap;
230
231
232 /**
233  * Maximum number of requests (from other peers, overall) that we're
234  * willing to have pending at any given point in time.  Can be changed
235  * via the configuration file (32k is just the default).
236  */
237 static unsigned long long max_pending_requests = (32 * 1024);
238
239
240
241 /**
242  * Recalculate our bloom filter for filtering replies.  This function
243  * will create a new bloom filter from scratch, so it should only be
244  * called if we have no bloomfilter at all (and hence can create a
245  * fresh one of minimal size without problems) OR if our peer is the
246  * initiator (in which case we may resize to larger than mimimum size).
247  *
248  * @param type type of the request
249  * @param pr request for which the BF is to be recomputed
250  */
251 static void
252 refresh_bloomfilter (enum GNUNET_BLOCK_Type type,
253                      struct GSF_PendingRequest *pr)
254 {
255   if (NULL != pr->bg)
256   {
257     GNUNET_BLOCK_group_destroy (pr->bg);
258     pr->bg = NULL;
259   }
260   if (GNUNET_BLOCK_TYPE_FS_UBLOCK != type)
261     return; /* no need */
262   pr->bg
263     = GNUNET_BLOCK_group_create (GSF_block_ctx,
264                                  type,
265                                  GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
266                                                            UINT32_MAX),
267                                  NULL,
268                                  0,
269                                  "seen-set-size",
270                                  pr->replies_seen_count,
271                                  NULL);
272   if (NULL == pr->bg)
273     return;
274   GNUNET_break (GNUNET_OK ==
275                 GNUNET_BLOCK_group_set_seen (pr->bg,
276                                              pr->replies_seen,
277                                              pr->replies_seen_count));
278 }
279
280
281 /**
282  * Create a new pending request.
283  *
284  * @param options request options
285  * @param type type of the block that is being requested
286  * @param query key for the lookup
287  * @param target preferred target for the request, NULL for none
288  * @param bf_data raw data for bloom filter for known replies, can be NULL
289  * @param bf_size number of bytes in @a bf_data
290  * @param mingle mingle value for bf
291  * @param anonymity_level desired anonymity level
292  * @param priority maximum outgoing cummulative request priority to use
293  * @param ttl current time-to-live for the request
294  * @param sender_pid peer ID to use for the sender when forwarding, 0 for none
295  * @param origin_pid peer ID of origin of query (do not loop back)
296  * @param replies_seen hash codes of known local replies
297  * @param replies_seen_count size of the @a replies_seen array
298  * @param rh handle to call when we get a reply
299  * @param rh_cls closure for @a rh
300  * @return handle for the new pending request
301  */
302 struct GSF_PendingRequest *
303 GSF_pending_request_create_ (enum GSF_PendingRequestOptions options,
304                              enum GNUNET_BLOCK_Type type,
305                              const struct GNUNET_HashCode *query,
306                              const struct GNUNET_PeerIdentity *target,
307                              const char *bf_data,
308                              size_t bf_size,
309                              uint32_t mingle,
310                              uint32_t anonymity_level,
311                              uint32_t priority,
312                              int32_t ttl,
313                              GNUNET_PEER_Id sender_pid,
314                              GNUNET_PEER_Id origin_pid,
315                              const struct GNUNET_HashCode *replies_seen,
316                              unsigned int replies_seen_count,
317                              GSF_PendingRequestReplyHandler rh,
318                              void *rh_cls)
319 {
320   struct GSF_PendingRequest *pr;
321   struct GSF_PendingRequest *dpr;
322   size_t extra;
323   struct GNUNET_HashCode *eptr;
324
325   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
326               "Creating request handle for `%s' of type %d\n",
327               GNUNET_h2s (query), type);
328 #if INSANE_STATISTICS
329   GNUNET_STATISTICS_update (GSF_stats,
330                             gettext_noop ("# Pending requests created"), 1,
331                             GNUNET_NO);
332 #endif
333   extra = 0;
334   if (NULL != target)
335     extra += sizeof (struct GNUNET_PeerIdentity);
336   pr = GNUNET_malloc (sizeof (struct GSF_PendingRequest) + extra);
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 /* Call our continuation (if we have any) */
1344 static void
1345 call_continuation (struct GSF_PendingRequest *pr)
1346 {
1347   GSF_LocalLookupContinuation cont = pr->llc_cont;
1348
1349   GNUNET_assert (NULL == pr->qe);
1350   if (NULL != pr->warn_task)
1351   {
1352     GNUNET_SCHEDULER_cancel (pr->warn_task);
1353     pr->warn_task = NULL;
1354   }
1355   if (NULL == cont)
1356     return;                     /* no continuation */
1357   pr->llc_cont = NULL;
1358   if (0 != (GSF_PRO_LOCAL_ONLY & pr->public_data.options))
1359   {
1360     if (GNUNET_BLOCK_EVALUATION_OK_LAST != pr->local_result)
1361     {
1362       /* Signal that we are done and that there won't be any
1363          additional results to allow client to clean up state. */
1364       pr->rh (pr->rh_cls,
1365                GNUNET_BLOCK_EVALUATION_OK_LAST,
1366                pr,
1367                UINT32_MAX,
1368                GNUNET_TIME_UNIT_ZERO_ABS,
1369                GNUNET_TIME_UNIT_FOREVER_ABS,
1370                GNUNET_BLOCK_TYPE_ANY,
1371                NULL,
1372                0);
1373     }
1374     /* Finally, call our continuation to signal that we are
1375        done with local processing of this request; i.e. to
1376        start reading again from the client. */
1377     cont (pr->llc_cont_cls, NULL, GNUNET_BLOCK_EVALUATION_OK_LAST);
1378     return;
1379   }
1380
1381   cont (pr->llc_cont_cls, pr, pr->local_result);
1382 }
1383
1384
1385 /* Update stats and call continuation */
1386 static void
1387 no_more_local_results (struct GSF_PendingRequest *pr)
1388 {
1389   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1390               "No further local responses available.\n");
1391 #if INSANE_STATISTICS
1392   if ( (GNUNET_BLOCK_TYPE_FS_DBLOCK == pr->public_data.type) ||
1393        (GNUNET_BLOCK_TYPE_FS_IBLOCK == pr->public_data.type) )
1394     GNUNET_STATISTICS_update (GSF_stats,
1395                               gettext_noop ("# requested DBLOCK or IBLOCK not found"),
1396                               1,
1397                               GNUNET_NO);
1398 #endif
1399   call_continuation (pr);
1400 }
1401
1402
1403 /* forward declaration */
1404 static void
1405 process_local_reply (void *cls,
1406                      const struct GNUNET_HashCode *key,
1407                      size_t size,
1408                      const void *data,
1409                      enum GNUNET_BLOCK_Type type,
1410                      uint32_t priority,
1411                      uint32_t anonymity,
1412                      uint32_t replication,
1413                      struct GNUNET_TIME_Absolute expiration,
1414                      uint64_t uid);
1415
1416
1417 /* Start a local query */
1418 static void
1419 start_local_query (struct GSF_PendingRequest *pr,
1420                    uint64_t next_uid,
1421                    bool random)
1422 {
1423   pr->qe_start = GNUNET_TIME_absolute_get ();
1424   pr->warn_task =
1425       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1426                                     &warn_delay_task,
1427                                     pr);
1428   pr->qe =
1429       GNUNET_DATASTORE_get_key (GSF_dsh,
1430                                 next_uid,
1431                                 random,
1432                                 &pr->public_data.query,
1433                                 pr->public_data.type ==
1434                                 GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1435                                 GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1436                                 (0 !=
1437                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1438                                   public_data.options)) ? UINT_MAX : 1
1439                                 /* queue priority */ ,
1440                                 (0 !=
1441                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1442                                   public_data.options)) ? UINT_MAX :
1443                                 GSF_datastore_queue_size
1444                                 /* max queue size */ ,
1445                                 &process_local_reply, pr);
1446   if (NULL != pr->qe)
1447     return;
1448   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1449               "ERROR Requesting `%s' of type %d with next_uid %llu from datastore.\n",
1450               GNUNET_h2s (&pr->public_data.query),
1451               pr->public_data.type,
1452               (unsigned long long) next_uid);
1453   GNUNET_STATISTICS_update (GSF_stats,
1454                             gettext_noop ("# Datastore lookups concluded (error queueing)"),
1455                             1,
1456                             GNUNET_NO);
1457   call_continuation (pr);
1458 }
1459
1460
1461 /**
1462  * We're processing (local) results for a search request
1463  * from another peer.  Pass applicable results to the
1464  * peer and if we are done either clean up (operation
1465  * complete) or forward to other peers (more results possible).
1466  *
1467  * @param cls our closure (`struct GSF_PendingRequest *`)
1468  * @param key key for the content
1469  * @param size number of bytes in @a data
1470  * @param data content stored
1471  * @param type type of the content
1472  * @param priority priority of the content
1473  * @param anonymity anonymity-level for the content
1474  * @param replication replication-level for the content
1475  * @param expiration expiration time for the content
1476  * @param uid unique identifier for the datum;
1477  *        maybe 0 if no unique identifier is available
1478  */
1479 static void
1480 process_local_reply (void *cls,
1481                      const struct GNUNET_HashCode *key,
1482                      size_t size,
1483                      const void *data,
1484                      enum GNUNET_BLOCK_Type type,
1485                      uint32_t priority,
1486                      uint32_t anonymity,
1487                      uint32_t replication,
1488                      struct GNUNET_TIME_Absolute expiration,
1489                      uint64_t uid)
1490 {
1491   struct GSF_PendingRequest *pr = cls;
1492   struct ProcessReplyClosure prq;
1493   struct GNUNET_HashCode query;
1494   unsigned int old_rf;
1495
1496   GNUNET_SCHEDULER_cancel (pr->warn_task);
1497   pr->warn_task = NULL;
1498   if (NULL == pr->qe)
1499     goto called_from_on_demand;
1500   pr->qe = NULL;
1501   if ( (NULL == key) &&
1502        pr->seen_null &&
1503        !pr->have_first_uid) /* We have hit the end for the 2nd time with no results */
1504   {
1505     /* No results */
1506 #if INSANE_STATISTICS
1507     GNUNET_STATISTICS_update (GSF_stats,
1508                               gettext_noop
1509                               ("# Datastore lookups concluded (no results)"),
1510                               1, GNUNET_NO);
1511 #endif
1512     no_more_local_results (pr);
1513     return;
1514   }
1515   if ( ( (NULL == key) &&
1516          pr->seen_null ) || /* We have hit the end for the 2nd time OR */
1517        ( pr->seen_null &&
1518          pr->have_first_uid &&
1519          (uid >= pr->first_uid) ) ) /* We have hit the end and past first UID */
1520   {
1521     /* Seen all results */
1522     GNUNET_STATISTICS_update (GSF_stats,
1523                               gettext_noop
1524                               ("# Datastore lookups concluded (seen all)"),
1525                               1, GNUNET_NO);
1526     no_more_local_results (pr);
1527     return;
1528   }
1529   if (NULL == key)
1530   {
1531     GNUNET_assert (!pr->seen_null);
1532     pr->seen_null = true;
1533     start_local_query (pr,
1534                        0 /* next_uid */,
1535                        false /* random */);
1536     return;
1537   }
1538   if (!pr->have_first_uid)
1539   {
1540     pr->first_uid = uid;
1541     pr->have_first_uid = true;
1542   }
1543   pr->result_count++;
1544   if (pr->result_count > MAX_RESULTS)
1545   {
1546     GNUNET_STATISTICS_update (GSF_stats,
1547                               gettext_noop
1548                               ("# Datastore lookups aborted (more than MAX_RESULTS)"),
1549                               1, GNUNET_NO);
1550     no_more_local_results (pr);
1551     return;
1552   }
1553   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1554               "Received reply for `%s' of type %d with UID %llu from datastore.\n",
1555               GNUNET_h2s (key), type, (unsigned long long) uid);
1556   if (GNUNET_BLOCK_TYPE_FS_ONDEMAND == type)
1557   {
1558     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1559                 "Found ONDEMAND block, performing on-demand encoding\n");
1560     GNUNET_STATISTICS_update (GSF_stats,
1561                               gettext_noop
1562                               ("# on-demand blocks matched requests"), 1,
1563                               GNUNET_NO);
1564     pr->qe_start = GNUNET_TIME_absolute_get ();
1565     pr->warn_task =
1566         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1567                                       &odc_warn_delay_task, pr);
1568     if (GNUNET_OK ==
1569         GNUNET_FS_handle_on_demand_block (key,
1570                                           size,
1571                                           data,
1572                                           type,
1573                                           priority,
1574                                           anonymity,
1575                                           replication,
1576                                           expiration,
1577                                           uid,
1578                                           &process_local_reply,
1579                                           pr))
1580     {
1581       GNUNET_STATISTICS_update (GSF_stats,
1582                                 gettext_noop
1583                                 ("# on-demand lookups performed successfully"),
1584                                 1, GNUNET_NO);
1585       return;                   /* we're done */
1586     }
1587     GNUNET_STATISTICS_update (GSF_stats,
1588                               gettext_noop ("# on-demand lookups failed"), 1,
1589                               GNUNET_NO);
1590     GNUNET_SCHEDULER_cancel (pr->warn_task);
1591     start_local_query (pr,
1592                        uid + 1 /* next_uid */,
1593                        false /* random */);
1594     return;
1595   }
1596 called_from_on_demand:
1597   old_rf = pr->public_data.results_found;
1598   memset (&prq, 0, sizeof (prq));
1599   prq.data = data;
1600   prq.expiration = expiration;
1601   prq.size = size;
1602   if (GNUNET_OK !=
1603       GNUNET_BLOCK_get_key (GSF_block_ctx, type, data, size, &query))
1604   {
1605     GNUNET_break (0);
1606     GNUNET_DATASTORE_remove (GSF_dsh, key, size, data, -1, -1,
1607                              NULL, NULL);
1608     start_local_query (pr,
1609                        uid + 1 /* next_uid */,
1610                        false /* random */);
1611     return;
1612   }
1613   prq.type = type;
1614   prq.priority = priority;
1615   prq.request_found = GNUNET_NO;
1616   prq.anonymity_level = anonymity;
1617   if ((0 == old_rf) && (0 == pr->public_data.results_found))
1618     GSF_update_datastore_delay_ (pr->public_data.start_time);
1619   prq.eo = GNUNET_BLOCK_EO_LOCAL_SKIP_CRYPTO;
1620   process_reply (&prq, key, pr);
1621   pr->local_result = prq.eval;
1622   if (GNUNET_BLOCK_EVALUATION_OK_LAST == prq.eval)
1623   {
1624     GNUNET_STATISTICS_update (GSF_stats,
1625                               gettext_noop
1626                               ("# Datastore lookups concluded (found last result)"),
1627                               1,
1628                               GNUNET_NO);
1629     call_continuation (pr);
1630     return;
1631   }
1632   if ((0 == (GSF_PRO_PRIORITY_UNLIMITED & pr->public_data.options)) &&
1633       ((GNUNET_YES == GSF_test_get_load_too_high_ (0)) ||
1634        (pr->public_data.results_found > 5 + 2 * pr->public_data.priority)))
1635   {
1636     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1637                 "Load too high, done with request\n");
1638     GNUNET_STATISTICS_update (GSF_stats,
1639                               gettext_noop ("# Datastore lookups concluded (load too high)"),
1640                               1,
1641                               GNUNET_NO);
1642     call_continuation (pr);
1643     return;
1644   }
1645   start_local_query (pr,
1646                      uid + 1 /* next_uid */,
1647                      false /* random */);
1648 }
1649
1650
1651 /**
1652  * Is the given target a legitimate peer for forwarding the given request?
1653  *
1654  * @param pr request
1655  * @param target
1656  * @return #GNUNET_YES if this request could be forwarded to the given peer
1657  */
1658 int
1659 GSF_pending_request_test_target_ (struct GSF_PendingRequest *pr,
1660                                   const struct GNUNET_PeerIdentity *target)
1661 {
1662   struct GNUNET_PeerIdentity pi;
1663
1664   if (0 == pr->origin_pid)
1665     return GNUNET_YES;
1666   GNUNET_PEER_resolve (pr->origin_pid, &pi);
1667   return (0 ==
1668           memcmp (&pi, target,
1669                   sizeof (struct GNUNET_PeerIdentity))) ? GNUNET_NO :
1670       GNUNET_YES;
1671 }
1672
1673
1674 /**
1675  * Look up the request in the local datastore.
1676  *
1677  * @param pr the pending request to process
1678  * @param cont function to call at the end
1679  * @param cont_cls closure for @a cont
1680  */
1681 void
1682 GSF_local_lookup_ (struct GSF_PendingRequest *pr,
1683                    GSF_LocalLookupContinuation cont,
1684                    void *cont_cls)
1685 {
1686   GNUNET_assert (NULL == pr->gh);
1687   GNUNET_assert (NULL == pr->cadet_request);
1688   GNUNET_assert (NULL == pr->llc_cont);
1689   pr->llc_cont = cont;
1690   pr->llc_cont_cls = cont_cls;
1691 #if INSANE_STATISTICS
1692   GNUNET_STATISTICS_update (GSF_stats,
1693                             gettext_noop ("# Datastore lookups initiated"), 1,
1694                             GNUNET_NO);
1695 #endif
1696   start_local_query(pr,
1697                     0 /* next_uid */,
1698                     true /* random */);
1699 }
1700
1701
1702
1703 /**
1704  * Handle P2P "CONTENT" message.  Checks that the message is
1705  * well-formed and then checks if there are any pending requests for
1706  * this content and possibly passes it on (to local clients or other
1707  * peers).  Does NOT perform migration (content caching at this peer).
1708  *
1709  * @param cls the other peer involved
1710  * @param put the actual message
1711  */
1712 void
1713 handle_p2p_put (void *cls,
1714                 const struct PutMessage *put)
1715 {
1716   struct GSF_ConnectedPeer *cp = cls;
1717   uint16_t msize;
1718   size_t dsize;
1719   enum GNUNET_BLOCK_Type type;
1720   struct GNUNET_TIME_Absolute expiration;
1721   struct GNUNET_HashCode query;
1722   struct ProcessReplyClosure prq;
1723   struct GNUNET_TIME_Relative block_time;
1724   double putl;
1725   struct PutMigrationContext *pmc;
1726
1727   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1728               "Received P2P PUT from %s\n",
1729               GNUNET_i2s (GSF_get_peer_performance_data_ (cp)->peer));
1730   GSF_cover_content_count++;
1731   msize = ntohs (put->header.size);
1732   dsize = msize - sizeof (struct PutMessage);
1733   type = ntohl (put->type);
1734   expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
1735   /* do not allow migrated content to live longer than 1 year */
1736   expiration = GNUNET_TIME_absolute_min (GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_YEARS),
1737                                          expiration);
1738   if (GNUNET_OK !=
1739       GNUNET_BLOCK_get_key (GSF_block_ctx,
1740                             type,
1741                             &put[1],
1742                             dsize,
1743                             &query))
1744   {
1745     GNUNET_break_op (0);
1746     return;
1747   }
1748   GNUNET_STATISTICS_update (GSF_stats,
1749                             gettext_noop ("# GAP PUT messages received"),
1750                             1,
1751                             GNUNET_NO);
1752   /* now, lookup 'query' */
1753   prq.data = (const void *) &put[1];
1754   prq.sender = cp;
1755   prq.size = dsize;
1756   prq.type = type;
1757   prq.expiration = expiration;
1758   prq.priority = 0;
1759   prq.anonymity_level = UINT32_MAX;
1760   prq.request_found = GNUNET_NO;
1761   prq.eo = GNUNET_BLOCK_EO_NONE;
1762   GNUNET_CONTAINER_multihashmap_get_multiple (pr_map,
1763                                               &query,
1764                                               &process_reply,
1765                                               &prq);
1766   if (NULL != cp)
1767   {
1768     GSF_connected_peer_change_preference_ (cp,
1769                                            CONTENT_BANDWIDTH_VALUE +
1770                                            1000 * prq.priority);
1771     GSF_get_peer_performance_data_ (cp)->respect += prq.priority;
1772   }
1773   if ((GNUNET_YES == active_to_migration) &&
1774       (NULL != cp) &&
1775       (GNUNET_NO == test_put_load_too_high (prq.priority)))
1776   {
1777     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1778                 "Replicating result for query `%s' with priority %u\n",
1779                 GNUNET_h2s (&query),
1780                 prq.priority);
1781     pmc = GNUNET_new (struct PutMigrationContext);
1782     pmc->start = GNUNET_TIME_absolute_get ();
1783     pmc->requested = prq.request_found;
1784     GNUNET_assert (0 != GSF_get_peer_performance_data_ (cp)->pid);
1785     GNUNET_PEER_resolve (GSF_get_peer_performance_data_ (cp)->pid,
1786                          &pmc->origin);
1787     if (NULL ==
1788         GNUNET_DATASTORE_put (GSF_dsh,
1789                               0,
1790                               &query,
1791                               dsize,
1792                               &put[1],
1793                               type,
1794                               prq.priority,
1795                               1 /* anonymity */ ,
1796                               0 /* replication */ ,
1797                               expiration, 1 + prq.priority,
1798                               MAX_DATASTORE_QUEUE,
1799                               &put_migration_continuation,
1800                               pmc))
1801     {
1802       put_migration_continuation (pmc,
1803                                   GNUNET_SYSERR,
1804                                   GNUNET_TIME_UNIT_ZERO_ABS,
1805                                   NULL);
1806     }
1807   }
1808   else if (NULL != cp)
1809   {
1810     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1811                 "Choosing not to keep content `%s' (%d/%d)\n",
1812                 GNUNET_h2s (&query),
1813                 active_to_migration,
1814                 test_put_load_too_high (prq.priority));
1815   }
1816   putl = GNUNET_LOAD_get_load (datastore_put_load);
1817   if ( (NULL != cp) &&
1818        (GNUNET_NO == prq.request_found) &&
1819        ( (GNUNET_YES != active_to_migration) ||
1820          (putl > 2.5 * (1 + prq.priority)) ) )
1821   {
1822     if (GNUNET_YES != active_to_migration)
1823       putl = 1.0 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 5);
1824     block_time =
1825         GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1826                                        5000 +
1827                                        GNUNET_CRYPTO_random_u32
1828                                        (GNUNET_CRYPTO_QUALITY_WEAK,
1829                                         (unsigned int) (60000 * putl * putl)));
1830     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1831                 "Asking to stop migration for %s because of load %f and events %d/%d\n",
1832                 GNUNET_STRINGS_relative_time_to_string (block_time,
1833                                                         GNUNET_YES),
1834                 putl,
1835                 active_to_migration,
1836                 (GNUNET_NO == prq.request_found));
1837     GSF_block_peer_migration_ (cp,
1838                                GNUNET_TIME_relative_to_absolute (block_time));
1839   }
1840 }
1841
1842
1843 /**
1844  * Check if the given request is still active.
1845  *
1846  * @param pr pending request
1847  * @return #GNUNET_YES if the request is still active
1848  */
1849 int
1850 GSF_pending_request_test_active_ (struct GSF_PendingRequest *pr)
1851 {
1852   return (NULL != pr->rh) ? GNUNET_YES : GNUNET_NO;
1853 }
1854
1855
1856 /**
1857  * Setup the subsystem.
1858  */
1859 void
1860 GSF_pending_request_init_ ()
1861 {
1862   if (GNUNET_OK !=
1863       GNUNET_CONFIGURATION_get_value_number (GSF_cfg, "fs",
1864                                              "MAX_PENDING_REQUESTS",
1865                                              &max_pending_requests))
1866   {
1867     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_INFO,
1868                                "fs", "MAX_PENDING_REQUESTS");
1869   }
1870   active_to_migration =
1871       GNUNET_CONFIGURATION_get_value_yesno (GSF_cfg, "FS", "CONTENT_CACHING");
1872   datastore_put_load = GNUNET_LOAD_value_init (DATASTORE_LOAD_AUTODECLINE);
1873   pr_map = GNUNET_CONTAINER_multihashmap_create (32 * 1024, GNUNET_YES);
1874   requests_by_expiration_heap =
1875       GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1876 }
1877
1878
1879 /**
1880  * Shutdown the subsystem.
1881  */
1882 void
1883 GSF_pending_request_done_ ()
1884 {
1885   GNUNET_CONTAINER_multihashmap_iterate (pr_map,
1886                                          &clean_request,
1887                                          NULL);
1888   GNUNET_CONTAINER_multihashmap_destroy (pr_map);
1889   pr_map = NULL;
1890   GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
1891   requests_by_expiration_heap = NULL;
1892   GNUNET_LOAD_value_free (datastore_put_load);
1893   datastore_put_load = NULL;
1894 }
1895
1896
1897 /* end of gnunet-service-fs_pr.c */