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