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