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