fix #3704
[oweals/gnunet.git] / src / fs / gnunet-service-fs_pr.c
1 /*
2      This file is part of GNUnet.
3      Copyright (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   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, 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 (NULL != pr->warn_task)
636   {
637     GNUNET_SCHEDULER_cancel (pr->warn_task);
638     pr->warn_task = NULL;
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 (NULL != pr->warn_task)
694     {
695       GNUNET_SCHEDULER_cancel (pr->warn_task);
696       pr->warn_task = NULL;
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    * Control flags for evaluation.
752    */
753   enum GNUNET_BLOCK_EvaluationOptions eo;
754
755   /**
756    * How much was this reply worth to us?
757    */
758   uint32_t priority;
759
760   /**
761    * Anonymity requirements for this reply.
762    */
763   uint32_t anonymity_level;
764
765   /**
766    * Evaluation result (returned).
767    */
768   enum GNUNET_BLOCK_EvaluationResult eval;
769
770   /**
771    * Did we find a matching request?
772    */
773   int request_found;
774 };
775
776
777 /**
778  * Update the performance data for the sender (if any) since
779  * the sender successfully answered one of our queries.
780  *
781  * @param prq information about the sender
782  * @param pr request that was satisfied
783  */
784 static void
785 update_request_performance_data (struct ProcessReplyClosure *prq,
786                                  struct GSF_PendingRequest *pr)
787 {
788   if (prq->sender == NULL)
789     return;
790   GSF_peer_update_performance_ (prq->sender, pr->public_data.start_time,
791                                 prq->priority);
792 }
793
794
795 /**
796  * We have received a reply; handle it!
797  *
798  * @param cls response (a `struct ProcessReplyClosure`)
799  * @param key our query
800  * @param value value in the hash map (info about the query)
801  * @return #GNUNET_YES (we should continue to iterate)
802  */
803 static int
804 process_reply (void *cls,
805                const struct GNUNET_HashCode *key,
806                void *value)
807 {
808   struct ProcessReplyClosure *prq = cls;
809   struct GSF_PendingRequest *pr = value;
810   struct GNUNET_HashCode chash;
811   struct GNUNET_TIME_Absolute last_transmission;
812
813   if (NULL == pr->rh)
814     return GNUNET_YES;
815   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
816               "Matched result (type %u) for query `%s' with pending request\n",
817               (unsigned int) prq->type,
818               GNUNET_h2s (key));
819   GNUNET_STATISTICS_update (GSF_stats,
820                             gettext_noop ("# replies received and matched"), 1,
821                             GNUNET_NO);
822   prq->eval =
823       GNUNET_BLOCK_evaluate (GSF_block_ctx,
824                              prq->type,
825                              prq->eo,
826                              key,
827                              &pr->bf,
828                              pr->mingle,
829                              NULL,
830                              0,
831                              prq->data,
832                              prq->size);
833   switch (prq->eval)
834   {
835   case GNUNET_BLOCK_EVALUATION_OK_MORE:
836     update_request_performance_data (prq, pr);
837     break;
838   case GNUNET_BLOCK_EVALUATION_OK_LAST:
839     /* short cut: stop processing early, no BF-update, etc. */
840     update_request_performance_data (prq, pr);
841     GNUNET_LOAD_update (GSF_rt_entry_lifetime,
842                         GNUNET_TIME_absolute_get_duration (pr->
843                                                            public_data.start_time).rel_value_us);
844     if (GNUNET_YES !=
845         GSF_request_plan_reference_get_last_transmission_ (pr->public_data.pr_head,
846                                                            prq->sender,
847                                                            &last_transmission))
848       last_transmission.abs_value_us = GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us;
849     /* pass on to other peers / local clients */
850     pr->rh (pr->rh_cls, prq->eval, pr, prq->anonymity_level, prq->expiration,
851             last_transmission, prq->type, prq->data, prq->size);
852     return GNUNET_YES;
853   case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
854 #if INSANE_STATISTICS
855     GNUNET_STATISTICS_update (GSF_stats,
856                               gettext_noop
857                               ("# duplicate replies discarded (bloomfilter)"),
858                               1, GNUNET_NO);
859 #endif
860     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
861                 "Duplicate response, discarding.\n");
862     return GNUNET_YES;          /* duplicate */
863   case GNUNET_BLOCK_EVALUATION_RESULT_IRRELEVANT:
864     GNUNET_STATISTICS_update (GSF_stats,
865                               gettext_noop
866                               ("# irrelevant replies discarded"),
867                               1, GNUNET_NO);
868     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
869                 "Irrelevant response, ignoring.\n");
870     return GNUNET_YES;
871   case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
872     return GNUNET_YES;          /* wrong namespace */
873   case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
874     GNUNET_break (0);
875     return GNUNET_YES;
876   case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
877     GNUNET_break (0);
878     return GNUNET_YES;
879   case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
880     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
881                 _("Unsupported block type %u\n"),
882                 prq->type);
883     return GNUNET_NO;
884   }
885   /* update bloomfilter */
886   GNUNET_CRYPTO_hash (prq->data,
887                       prq->size,
888                       &chash);
889   GSF_pending_request_update_ (pr,
890                                &chash,
891                                1);
892   if (NULL == prq->sender)
893   {
894     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
895                 "Found result for query `%s' in local datastore\n",
896                 GNUNET_h2s (key));
897     GNUNET_STATISTICS_update (GSF_stats,
898                               gettext_noop ("# results found locally"),
899                               1,
900                               GNUNET_NO);
901   }
902   else
903   {
904     GSF_dht_lookup_ (pr);
905   }
906   prq->priority += pr->public_data.original_priority;
907   pr->public_data.priority = 0;
908   pr->public_data.original_priority = 0;
909   pr->public_data.results_found++;
910   prq->request_found = GNUNET_YES;
911   /* finally, pass on to other peer / local client */
912   if (! GSF_request_plan_reference_get_last_transmission_ (pr->public_data.pr_head,
913                                                            prq->sender,
914                                                            &last_transmission))
915     last_transmission.abs_value_us = GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us;
916   pr->rh (pr->rh_cls,
917           prq->eval,
918           pr,
919           prq->anonymity_level,
920           prq->expiration,
921           last_transmission,
922           prq->type,
923           prq->data,
924           prq->size);
925   return GNUNET_YES;
926 }
927
928
929 /**
930  * Context for put_migration_continuation().
931  */
932 struct PutMigrationContext
933 {
934
935   /**
936    * Start time for the operation.
937    */
938   struct GNUNET_TIME_Absolute start;
939
940   /**
941    * Request origin.
942    */
943   struct GNUNET_PeerIdentity origin;
944
945   /**
946    * #GNUNET_YES if we had a matching request for this block,
947    * #GNUNET_NO if not.
948    */
949   int requested;
950 };
951
952
953 /**
954  * Continuation called to notify client about result of the
955  * operation.
956  *
957  * @param cls closure
958  * @param success #GNUNET_SYSERR on failure
959  * @param min_expiration minimum expiration time required for content to be stored
960  * @param msg NULL on success, otherwise an error message
961  */
962 static void
963 put_migration_continuation (void *cls, int success,
964                             struct GNUNET_TIME_Absolute min_expiration,
965                             const char *msg)
966 {
967   struct PutMigrationContext *pmc = cls;
968   struct GSF_ConnectedPeer *cp;
969   struct GNUNET_TIME_Relative mig_pause;
970   struct GSF_PeerPerformanceData *ppd;
971
972   if (NULL != datastore_put_load)
973   {
974     if (GNUNET_SYSERR != success)
975     {
976       GNUNET_LOAD_update (datastore_put_load,
977                           GNUNET_TIME_absolute_get_duration (pmc->start).rel_value_us);
978     }
979     else
980     {
981       /* on queue failure / timeout, increase the put load dramatically */
982       GNUNET_LOAD_update (datastore_put_load,
983                           GNUNET_TIME_UNIT_MINUTES.rel_value_us);
984     }
985   }
986   cp = GSF_peer_get_ (&pmc->origin);
987   if (GNUNET_OK == success)
988   {
989     if (NULL != cp)
990     {
991       ppd = GSF_get_peer_performance_data_ (cp);
992       ppd->migration_delay.rel_value_us /= 2;
993     }
994     GNUNET_free (pmc);
995     return;
996   }
997   if ( (GNUNET_NO == success) &&
998        (GNUNET_NO == pmc->requested) &&
999        (NULL != cp) )
1000   {
1001     ppd = GSF_get_peer_performance_data_ (cp);
1002     if (min_expiration.abs_value_us > 0)
1003     {
1004       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1005                   "Asking to stop migration for %s because datastore is full\n",
1006                   GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (min_expiration), GNUNET_YES));
1007       GSF_block_peer_migration_ (cp, min_expiration);
1008     }
1009     else
1010     {
1011       ppd->migration_delay = GNUNET_TIME_relative_max (GNUNET_TIME_UNIT_SECONDS,
1012                                                        ppd->migration_delay);
1013       ppd->migration_delay = GNUNET_TIME_relative_min (GNUNET_TIME_UNIT_HOURS,
1014                                                        ppd->migration_delay);
1015       mig_pause.rel_value_us = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
1016                                                          ppd->migration_delay.rel_value_us);
1017       ppd->migration_delay = GNUNET_TIME_relative_multiply (ppd->migration_delay, 2);
1018       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1019                   "Replicated content already exists locally, asking to stop migration for %s\n",
1020                   GNUNET_STRINGS_relative_time_to_string (mig_pause,
1021                                                           GNUNET_YES));
1022       GSF_block_peer_migration_ (cp,
1023                                  GNUNET_TIME_relative_to_absolute (mig_pause));
1024     }
1025   }
1026   GNUNET_free (pmc);
1027   GNUNET_STATISTICS_update (GSF_stats,
1028                             gettext_noop ("# Datastore `PUT' failures"), 1,
1029                             GNUNET_NO);
1030 }
1031
1032
1033 /**
1034  * Test if the DATABASE (PUT) load on this peer is too high
1035  * to even consider processing the query at
1036  * all.
1037  *
1038  * @param priority the priority of the item
1039  * @return #GNUNET_YES if the load is too high to do anything (load high)
1040  *         #GNUNET_NO to process normally (load normal or low)
1041  */
1042 static int
1043 test_put_load_too_high (uint32_t priority)
1044 {
1045   double ld;
1046
1047   if (NULL == datastore_put_load)
1048     return GNUNET_NO;
1049   if (GNUNET_LOAD_get_average (datastore_put_load) < 50)
1050     return GNUNET_NO;           /* very fast */
1051   ld = GNUNET_LOAD_get_load (datastore_put_load);
1052   if (ld < 2.0 * (1 + priority))
1053     return GNUNET_NO;
1054   GNUNET_STATISTICS_update (GSF_stats,
1055                             gettext_noop
1056                             ("# storage requests dropped due to high load"), 1,
1057                             GNUNET_NO);
1058   return GNUNET_YES;
1059 }
1060
1061
1062 /**
1063  * Iterator called on each result obtained for a DHT
1064  * operation that expects a reply
1065  *
1066  * @param cls closure
1067  * @param exp when will this value expire
1068  * @param key key of the result
1069  * @param get_path peers on reply path (or NULL if not recorded)
1070  * @param get_path_length number of entries in @a get_path
1071  * @param put_path peers on the PUT path (or NULL if not recorded)
1072  * @param put_path_length number of entries in @a get_path
1073  * @param type type of the result
1074  * @param size number of bytes in @a data
1075  * @param data pointer to the result data
1076  */
1077 static void
1078 handle_dht_reply (void *cls,
1079                   struct GNUNET_TIME_Absolute exp,
1080                   const struct GNUNET_HashCode *key,
1081                   const struct GNUNET_PeerIdentity *get_path,
1082                   unsigned int get_path_length,
1083                   const struct GNUNET_PeerIdentity *put_path,
1084                   unsigned int put_path_length,
1085                   enum GNUNET_BLOCK_Type type,
1086                   size_t size,
1087                   const void *data)
1088 {
1089   struct GSF_PendingRequest *pr = cls;
1090   struct ProcessReplyClosure prq;
1091   struct PutMigrationContext *pmc;
1092
1093   GNUNET_STATISTICS_update (GSF_stats,
1094                             gettext_noop ("# Replies received from DHT"), 1,
1095                             GNUNET_NO);
1096   memset (&prq, 0, sizeof (prq));
1097   prq.data = data;
1098   prq.expiration = exp;
1099   /* do not allow migrated content to live longer than 1 year */
1100   prq.expiration = GNUNET_TIME_absolute_min (GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_YEARS),
1101                                              prq.expiration);
1102   prq.size = size;
1103   prq.type = type;
1104   prq.eo = GNUNET_BLOCK_EO_NONE;
1105   process_reply (&prq, key, pr);
1106   if ((GNUNET_YES == active_to_migration) &&
1107       (GNUNET_NO == test_put_load_too_high (prq.priority)))
1108   {
1109     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1110                 "Replicating result for query `%s' with priority %u\n",
1111                 GNUNET_h2s (key), prq.priority);
1112     pmc = GNUNET_new (struct PutMigrationContext);
1113     pmc->start = GNUNET_TIME_absolute_get ();
1114     pmc->requested = GNUNET_YES;
1115     if (NULL ==
1116         GNUNET_DATASTORE_put (GSF_dsh, 0, key, size, data, type, prq.priority,
1117                               1 /* anonymity */ ,
1118                               0 /* replication */ ,
1119                               exp, 1 + prq.priority, MAX_DATASTORE_QUEUE,
1120                               GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1121                               &put_migration_continuation, pmc))
1122     {
1123       put_migration_continuation (pmc,
1124                                   GNUNET_SYSERR,
1125                                   GNUNET_TIME_UNIT_ZERO_ABS,
1126                                   NULL);
1127     }
1128   }
1129 }
1130
1131
1132 /**
1133  * Consider looking up the data in the DHT (anonymity-level permitting).
1134  *
1135  * @param pr the pending request to process
1136  */
1137 void
1138 GSF_dht_lookup_ (struct GSF_PendingRequest *pr)
1139 {
1140   const void *xquery;
1141   size_t xquery_size;
1142   struct GNUNET_PeerIdentity pi;
1143   char buf[sizeof (struct GNUNET_HashCode) * 2] GNUNET_ALIGN;
1144
1145   if (0 != pr->public_data.anonymity_level)
1146     return;
1147   if (NULL != pr->gh)
1148   {
1149     GNUNET_DHT_get_stop (pr->gh);
1150     pr->gh = NULL;
1151   }
1152   xquery = NULL;
1153   xquery_size = 0;
1154   if (0 != (pr->public_data.options & GSF_PRO_FORWARD_ONLY))
1155   {
1156     GNUNET_assert (0 != pr->sender_pid);
1157     GNUNET_PEER_resolve (pr->sender_pid, &pi);
1158     memcpy (&buf[xquery_size], &pi, sizeof (struct GNUNET_PeerIdentity));
1159     xquery_size += sizeof (struct GNUNET_PeerIdentity);
1160   }
1161   pr->gh =
1162       GNUNET_DHT_get_start (GSF_dht,
1163                             pr->public_data.type, &pr->public_data.query,
1164                             DHT_GET_REPLICATION,
1165                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
1166                             xquery, xquery_size, &handle_dht_reply, pr);
1167   if ( (NULL != pr->gh) &&
1168        (0 != pr->replies_seen_count) )
1169     GNUNET_DHT_get_filter_known_results (pr->gh,
1170                                          pr->replies_seen_count,
1171                                          pr->replies_seen);
1172 }
1173
1174
1175 /**
1176  * Function called with a reply from the cadet.
1177  *
1178  * @param cls the pending request struct
1179  * @param type type of the block, ANY on error
1180  * @param expiration expiration time for the block
1181  * @param data_size number of bytes in @a data, 0 on error
1182  * @param data reply block data, NULL on error
1183  */
1184 static void
1185 cadet_reply_proc (void *cls,
1186                  enum GNUNET_BLOCK_Type type,
1187                  struct GNUNET_TIME_Absolute expiration,
1188                  size_t data_size,
1189                  const void *data)
1190 {
1191   struct GSF_PendingRequest *pr = cls;
1192   struct ProcessReplyClosure prq;
1193   struct GNUNET_HashCode query;
1194
1195   pr->cadet_request = NULL;
1196   if (GNUNET_BLOCK_TYPE_ANY == type)
1197   {
1198     GNUNET_break (NULL == data);
1199     GNUNET_break (0 == data_size);
1200     pr->cadet_retry_count++;
1201     if (pr->cadet_retry_count >= CADET_RETRY_MAX)
1202       return; /* give up on cadet */
1203     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1204                 "Error retrieiving block via cadet\n");
1205     /* retry -- without delay, as this is non-anonymous
1206        and cadet/cadet connect will take some time anyway */
1207     pr->cadet_request = GSF_cadet_query (pr->public_data.target,
1208                                        &pr->public_data.query,
1209                                        pr->public_data.type,
1210                                        &cadet_reply_proc,
1211                                        pr);
1212     return;
1213   }
1214   if (GNUNET_YES !=
1215       GNUNET_BLOCK_get_key (GSF_block_ctx,
1216                             type,
1217                             data, data_size, &query))
1218   {
1219     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1220                 "Failed to derive key for block of type %d\n",
1221                 (int) type);
1222     GNUNET_break_op (0);
1223     return;
1224   }
1225   GNUNET_STATISTICS_update (GSF_stats,
1226                             gettext_noop ("# Replies received from CADET"), 1,
1227                             GNUNET_NO);
1228   memset (&prq, 0, sizeof (prq));
1229   prq.data = data;
1230   prq.expiration = expiration;
1231   /* do not allow migrated content to live longer than 1 year */
1232   prq.expiration = GNUNET_TIME_absolute_min (GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_YEARS),
1233                                              prq.expiration);
1234   prq.size = data_size;
1235   prq.type = type;
1236   prq.eo = GNUNET_BLOCK_EO_NONE;
1237   process_reply (&prq, &query, pr);
1238 }
1239
1240
1241 /**
1242  * Consider downloading via cadet (if possible)
1243  *
1244  * @param pr the pending request to process
1245  */
1246 void
1247 GSF_cadet_lookup_ (struct GSF_PendingRequest *pr)
1248 {
1249   if (0 != pr->public_data.anonymity_level)
1250     return;
1251   if (0 == pr->public_data.target)
1252   {
1253     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1254                 "Cannot do cadet-based download, target peer not known\n");
1255     return;
1256   }
1257   if (NULL != pr->cadet_request)
1258     return;
1259   pr->cadet_request = GSF_cadet_query (pr->public_data.target,
1260                                      &pr->public_data.query,
1261                                      pr->public_data.type,
1262                                      &cadet_reply_proc,
1263                                      pr);
1264 }
1265
1266
1267 /**
1268  * Task that issues a warning if the datastore lookup takes too long.
1269  *
1270  * @param cls the 'struct GSF_PendingRequest'
1271  * @param tc task context
1272  */
1273 static void
1274 warn_delay_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1275 {
1276   struct GSF_PendingRequest *pr = cls;
1277
1278   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1279               _("Datastore lookup already took %s!\n"),
1280               GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (pr->qe_start), GNUNET_YES));
1281   pr->warn_task =
1282       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, &warn_delay_task,
1283                                     pr);
1284 }
1285
1286
1287 /**
1288  * Task that issues a warning if the datastore lookup takes too long.
1289  *
1290  * @param cls the 'struct GSF_PendingRequest'
1291  * @param tc task context
1292  */
1293 static void
1294 odc_warn_delay_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1295 {
1296   struct GSF_PendingRequest *pr = cls;
1297
1298   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1299               _("On-demand lookup already took %s!\n"),
1300               GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (pr->qe_start), GNUNET_YES));
1301   pr->warn_task =
1302       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1303                                     &odc_warn_delay_task, pr);
1304 }
1305
1306
1307 /**
1308  * We're processing (local) results for a search request
1309  * from another peer.  Pass applicable results to the
1310  * peer and if we are done either clean up (operation
1311  * complete) or forward to other peers (more results possible).
1312  *
1313  * @param cls our closure (`struct GSF_PendingRequest *`)
1314  * @param key key for the content
1315  * @param size number of bytes in @a data
1316  * @param data content stored
1317  * @param type type of the content
1318  * @param priority priority of the content
1319  * @param anonymity anonymity-level for the content
1320  * @param expiration expiration time for the content
1321  * @param uid unique identifier for the datum;
1322  *        maybe 0 if no unique identifier is available
1323  */
1324 static void
1325 process_local_reply (void *cls,
1326                      const struct GNUNET_HashCode *key,
1327                      size_t size,
1328                      const void *data,
1329                      enum GNUNET_BLOCK_Type type,
1330                      uint32_t priority,
1331                      uint32_t anonymity,
1332                      struct GNUNET_TIME_Absolute expiration,
1333                      uint64_t uid)
1334 {
1335   struct GSF_PendingRequest *pr = cls;
1336   GSF_LocalLookupContinuation cont;
1337   struct ProcessReplyClosure prq;
1338   struct GNUNET_HashCode query;
1339   unsigned int old_rf;
1340
1341   GNUNET_SCHEDULER_cancel (pr->warn_task);
1342   pr->warn_task = NULL;
1343   if (NULL != pr->qe)
1344   {
1345     pr->qe = NULL;
1346     if (NULL == key)
1347     {
1348 #if INSANE_STATISTICS
1349       GNUNET_STATISTICS_update (GSF_stats,
1350                                 gettext_noop
1351                                 ("# Datastore lookups concluded (no results)"),
1352                                 1, GNUNET_NO);
1353 #endif
1354     }
1355     if (GNUNET_NO == pr->have_first_uid)
1356     {
1357       pr->first_uid = uid;
1358       pr->have_first_uid = 1;
1359     }
1360     else
1361     {
1362       if ((uid == pr->first_uid) && (key != NULL))
1363       {
1364         GNUNET_STATISTICS_update (GSF_stats,
1365                                   gettext_noop
1366                                   ("# Datastore lookups concluded (seen all)"),
1367                                   1, GNUNET_NO);
1368         key = NULL;             /* all replies seen! */
1369       }
1370       pr->have_first_uid++;
1371       if ((pr->have_first_uid > MAX_RESULTS) && (key != NULL))
1372       {
1373         GNUNET_STATISTICS_update (GSF_stats,
1374                                   gettext_noop
1375                                   ("# Datastore lookups aborted (more than MAX_RESULTS)"),
1376                                   1, GNUNET_NO);
1377         key = NULL;             /* all replies seen! */
1378       }
1379     }
1380   }
1381   if (NULL == key)
1382   {
1383     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1384                 "No further local responses available.\n");
1385 #if INSANE_STATISTICS
1386     if ((pr->public_data.type == GNUNET_BLOCK_TYPE_FS_DBLOCK) ||
1387         (pr->public_data.type == GNUNET_BLOCK_TYPE_FS_IBLOCK))
1388       GNUNET_STATISTICS_update (GSF_stats,
1389                                 gettext_noop
1390                                 ("# requested DBLOCK or IBLOCK not found"), 1,
1391                                 GNUNET_NO);
1392 #endif
1393     goto check_error_and_continue;
1394   }
1395   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1396               "Received reply for `%s' of type %d with UID %llu from datastore.\n",
1397               GNUNET_h2s (key), type, (unsigned long long) uid);
1398   if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
1399   {
1400     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1401                 "Found ONDEMAND block, performing on-demand encoding\n");
1402     GNUNET_STATISTICS_update (GSF_stats,
1403                               gettext_noop
1404                               ("# on-demand blocks matched requests"), 1,
1405                               GNUNET_NO);
1406     pr->qe_start = GNUNET_TIME_absolute_get ();
1407     pr->warn_task =
1408         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1409                                       &odc_warn_delay_task, pr);
1410     if (GNUNET_OK ==
1411         GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
1412                                           anonymity, expiration, uid,
1413                                           &process_local_reply, pr))
1414     {
1415       GNUNET_STATISTICS_update (GSF_stats,
1416                                 gettext_noop
1417                                 ("# on-demand lookups performed successfully"),
1418                                 1, GNUNET_NO);
1419       return;                   /* we're done */
1420     }
1421     GNUNET_STATISTICS_update (GSF_stats,
1422                               gettext_noop ("# on-demand lookups failed"), 1,
1423                               GNUNET_NO);
1424     GNUNET_SCHEDULER_cancel (pr->warn_task);
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 (NULL != pr->qe)
1446       return;                   /* we're done */
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   old_rf = pr->public_data.results_found;
1454   memset (&prq, 0, sizeof (prq));
1455   prq.data = data;
1456   prq.expiration = expiration;
1457   prq.size = size;
1458   if (GNUNET_OK !=
1459       GNUNET_BLOCK_get_key (GSF_block_ctx, type, data, size, &query))
1460   {
1461     GNUNET_break (0);
1462     GNUNET_DATASTORE_remove (GSF_dsh, key, size, data, -1, -1,
1463                              GNUNET_TIME_UNIT_FOREVER_REL, NULL, NULL);
1464     pr->qe_start = GNUNET_TIME_absolute_get ();
1465     pr->warn_task =
1466         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1467                                       &warn_delay_task, pr);
1468     pr->qe =
1469         GNUNET_DATASTORE_get_key (GSF_dsh, pr->local_result_offset - 1,
1470                                   &pr->public_data.query,
1471                                   pr->public_data.type ==
1472                                   GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1473                                   GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1474                                   (0 !=
1475                                    (GSF_PRO_PRIORITY_UNLIMITED &
1476                                     pr->public_data.options)) ? UINT_MAX : 1
1477                                   /* queue priority */ ,
1478                                   (0 !=
1479                                    (GSF_PRO_PRIORITY_UNLIMITED &
1480                                     pr->public_data.options)) ? UINT_MAX :
1481                                   GSF_datastore_queue_size
1482                                   /* max queue size */ ,
1483                                   GNUNET_TIME_UNIT_FOREVER_REL,
1484                                   &process_local_reply, pr);
1485     if (pr->qe == NULL)
1486     {
1487       GNUNET_STATISTICS_update (GSF_stats,
1488                                 gettext_noop
1489                                 ("# Datastore lookups concluded (error queueing)"),
1490                                 1, GNUNET_NO);
1491       goto check_error_and_continue;
1492     }
1493     return;
1494   }
1495   prq.type = type;
1496   prq.priority = priority;
1497   prq.request_found = GNUNET_NO;
1498   prq.anonymity_level = anonymity;
1499   if ((0 == old_rf) && (0 == pr->public_data.results_found))
1500     GSF_update_datastore_delay_ (pr->public_data.start_time);
1501   prq.eo = GNUNET_BLOCK_EO_LOCAL_SKIP_CRYPTO;
1502   process_reply (&prq, key, pr);
1503   pr->local_result = prq.eval;
1504   if (prq.eval == GNUNET_BLOCK_EVALUATION_OK_LAST)
1505   {
1506     GNUNET_STATISTICS_update (GSF_stats,
1507                               gettext_noop
1508                               ("# Datastore lookups concluded (found last result)"),
1509                               1,
1510                               GNUNET_NO);
1511     goto check_error_and_continue;
1512   }
1513   if ((0 == (GSF_PRO_PRIORITY_UNLIMITED & pr->public_data.options)) &&
1514       ((GNUNET_YES == GSF_test_get_load_too_high_ (0)) ||
1515        (pr->public_data.results_found > 5 + 2 * pr->public_data.priority)))
1516   {
1517     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Load too high, done with request\n");
1518     GNUNET_STATISTICS_update (GSF_stats,
1519                               gettext_noop
1520                               ("# Datastore lookups concluded (load too high)"),
1521                               1,
1522                               GNUNET_NO);
1523     goto check_error_and_continue;
1524   }
1525   pr->qe_start = GNUNET_TIME_absolute_get ();
1526   pr->warn_task =
1527       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1528                                     &warn_delay_task,
1529                                     pr);
1530   pr->qe =
1531       GNUNET_DATASTORE_get_key (GSF_dsh, pr->local_result_offset++,
1532                                 &pr->public_data.query,
1533                                 pr->public_data.type ==
1534                                 GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1535                                 GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1536                                 (0 !=
1537                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1538                                   public_data.options)) ? UINT_MAX : 1
1539                                 /* queue priority */ ,
1540                                 (0 !=
1541                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1542                                   public_data.options)) ? UINT_MAX :
1543                                 GSF_datastore_queue_size
1544                                 /* max queue size */ ,
1545                                 GNUNET_TIME_UNIT_FOREVER_REL,
1546                                 &process_local_reply, pr);
1547   /* check if we successfully queued another datastore request;
1548    * if so, return, otherwise call our continuation (if we have
1549    * any) */
1550 check_error_and_continue:
1551   if (NULL != pr->qe)
1552     return;
1553   if (NULL != pr->warn_task)
1554   {
1555     GNUNET_SCHEDULER_cancel (pr->warn_task);
1556     pr->warn_task = NULL;
1557   }
1558   if (NULL == (cont = pr->llc_cont))
1559     return;                     /* no continuation */
1560   pr->llc_cont = NULL;
1561   if (0 != (GSF_PRO_LOCAL_ONLY & pr->public_data.options))
1562   {
1563     if (GNUNET_BLOCK_EVALUATION_OK_LAST != pr->local_result)
1564     {
1565       /* Signal that we are done and that there won't be any
1566          additional results to allow client to clean up state. */
1567       pr->rh (pr->rh_cls,
1568                GNUNET_BLOCK_EVALUATION_OK_LAST,
1569                pr,
1570                UINT32_MAX,
1571                GNUNET_TIME_UNIT_ZERO_ABS,
1572                GNUNET_TIME_UNIT_FOREVER_ABS,
1573                GNUNET_BLOCK_TYPE_ANY,
1574                NULL, 0);
1575     }
1576     /* Finally, call our continuation to signal that we are
1577        done with local processing of this request; i.e. to
1578        start reading again from the client. */
1579     cont (pr->llc_cont_cls, NULL, GNUNET_BLOCK_EVALUATION_OK_LAST);
1580     return;
1581   }
1582
1583   cont (pr->llc_cont_cls, pr, pr->local_result);
1584 }
1585
1586
1587 /**
1588  * Is the given target a legitimate peer for forwarding the given request?
1589  *
1590  * @param pr request
1591  * @param target
1592  * @return #GNUNET_YES if this request could be forwarded to the given peer
1593  */
1594 int
1595 GSF_pending_request_test_target_ (struct GSF_PendingRequest *pr,
1596                                   const struct GNUNET_PeerIdentity *target)
1597 {
1598   struct GNUNET_PeerIdentity pi;
1599
1600   if (0 == pr->origin_pid)
1601     return GNUNET_YES;
1602   GNUNET_PEER_resolve (pr->origin_pid, &pi);
1603   return (0 ==
1604           memcmp (&pi, target,
1605                   sizeof (struct GNUNET_PeerIdentity))) ? GNUNET_NO :
1606       GNUNET_YES;
1607 }
1608
1609
1610 /**
1611  * Look up the request in the local datastore.
1612  *
1613  * @param pr the pending request to process
1614  * @param cont function to call at the end
1615  * @param cont_cls closure for @a cont
1616  */
1617 void
1618 GSF_local_lookup_ (struct GSF_PendingRequest *pr,
1619                    GSF_LocalLookupContinuation cont,
1620                    void *cont_cls)
1621 {
1622   GNUNET_assert (NULL == pr->gh);
1623   GNUNET_assert (NULL == pr->cadet_request);
1624   GNUNET_assert (NULL == pr->llc_cont);
1625   pr->llc_cont = cont;
1626   pr->llc_cont_cls = cont_cls;
1627   pr->qe_start = GNUNET_TIME_absolute_get ();
1628   pr->warn_task =
1629       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, &warn_delay_task,
1630                                     pr);
1631 #if INSANE_STATISTICS
1632   GNUNET_STATISTICS_update (GSF_stats,
1633                             gettext_noop ("# Datastore lookups initiated"), 1,
1634                             GNUNET_NO);
1635 #endif
1636   pr->qe =
1637       GNUNET_DATASTORE_get_key (GSF_dsh, pr->local_result_offset++,
1638                                 &pr->public_data.query,
1639                                 pr->public_data.type ==
1640                                 GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1641                                 GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1642                                 (0 !=
1643                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1644                                   public_data.options)) ? UINT_MAX : 1
1645                                 /* queue priority */ ,
1646                                 (0 !=
1647                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1648                                   public_data.options)) ? UINT_MAX :
1649                                 GSF_datastore_queue_size
1650                                 /* max queue size */ ,
1651                                 GNUNET_TIME_UNIT_FOREVER_REL,
1652                                 &process_local_reply, pr);
1653   if (NULL != pr->qe)
1654     return;
1655   GNUNET_STATISTICS_update (GSF_stats,
1656                             gettext_noop
1657                             ("# Datastore lookups concluded (error queueing)"),
1658                             1, GNUNET_NO);
1659   GNUNET_SCHEDULER_cancel (pr->warn_task);
1660   pr->warn_task = NULL;
1661   pr->llc_cont = NULL;
1662   if (NULL != cont)
1663     cont (cont_cls, pr, pr->local_result);
1664 }
1665
1666
1667
1668 /**
1669  * Handle P2P "CONTENT" message.  Checks that the message is
1670  * well-formed and then checks if there are any pending requests for
1671  * this content and possibly passes it on (to local clients or other
1672  * peers).  Does NOT perform migration (content caching at this peer).
1673  *
1674  * @param cp the other peer involved (sender or receiver, NULL
1675  *        for loopback messages where we are both sender and receiver)
1676  * @param message the actual message
1677  * @return #GNUNET_OK if the message was well-formed,
1678  *         #GNUNET_SYSERR if the message was malformed (close connection,
1679  *         do not cache under any circumstances)
1680  */
1681 int
1682 GSF_handle_p2p_content_ (struct GSF_ConnectedPeer *cp,
1683                          const struct GNUNET_MessageHeader *message)
1684 {
1685   const struct PutMessage *put;
1686   uint16_t msize;
1687   size_t dsize;
1688   enum GNUNET_BLOCK_Type type;
1689   struct GNUNET_TIME_Absolute expiration;
1690   struct GNUNET_HashCode query;
1691   struct ProcessReplyClosure prq;
1692   struct GNUNET_TIME_Relative block_time;
1693   double putl;
1694   struct PutMigrationContext *pmc;
1695
1696   msize = ntohs (message->size);
1697   if (msize < sizeof (struct PutMessage))
1698   {
1699     GNUNET_break_op (0);
1700     return GNUNET_SYSERR;
1701   }
1702   put = (const struct PutMessage *) message;
1703   dsize = msize - sizeof (struct PutMessage);
1704   type = ntohl (put->type);
1705   expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
1706   /* do not allow migrated content to live longer than 1 year */
1707   expiration = GNUNET_TIME_absolute_min (GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_YEARS),
1708                                          expiration);
1709   if (GNUNET_BLOCK_TYPE_FS_ONDEMAND == type)
1710     return GNUNET_SYSERR;
1711   if (GNUNET_OK !=
1712       GNUNET_BLOCK_get_key (GSF_block_ctx,
1713                             type,
1714                             &put[1],
1715                             dsize,
1716                             &query))
1717   {
1718     GNUNET_break_op (0);
1719     return GNUNET_SYSERR;
1720   }
1721   GNUNET_STATISTICS_update (GSF_stats,
1722                             gettext_noop ("# GAP PUT messages received"),
1723                             1,
1724                             GNUNET_NO);
1725   /* now, lookup 'query' */
1726   prq.data = (const void *) &put[1];
1727   prq.sender = cp;
1728   prq.size = dsize;
1729   prq.type = type;
1730   prq.expiration = expiration;
1731   prq.priority = 0;
1732   prq.anonymity_level = UINT32_MAX;
1733   prq.request_found = GNUNET_NO;
1734   prq.eo = GNUNET_BLOCK_EO_NONE;
1735   GNUNET_CONTAINER_multihashmap_get_multiple (pr_map,
1736                                               &query,
1737                                               &process_reply,
1738                                               &prq);
1739   if (NULL != cp)
1740   {
1741     GSF_connected_peer_change_preference_ (cp,
1742                                            CONTENT_BANDWIDTH_VALUE +
1743                                            1000 * prq.priority);
1744     GSF_get_peer_performance_data_ (cp)->respect += prq.priority;
1745   }
1746   if ((GNUNET_YES == active_to_migration) &&
1747       (NULL != cp) &&
1748       (GNUNET_NO == test_put_load_too_high (prq.priority)))
1749   {
1750     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1751                 "Replicating result for query `%s' with priority %u\n",
1752                 GNUNET_h2s (&query),
1753                 prq.priority);
1754     pmc = GNUNET_new (struct PutMigrationContext);
1755     pmc->start = GNUNET_TIME_absolute_get ();
1756     pmc->requested = prq.request_found;
1757     GNUNET_assert (0 != GSF_get_peer_performance_data_ (cp)->pid);
1758     GNUNET_PEER_resolve (GSF_get_peer_performance_data_ (cp)->pid,
1759                          &pmc->origin);
1760     if (NULL ==
1761         GNUNET_DATASTORE_put (GSF_dsh, 0, &query, dsize, &put[1], type,
1762                               prq.priority, 1 /* anonymity */ ,
1763                               0 /* replication */ ,
1764                               expiration, 1 + prq.priority, MAX_DATASTORE_QUEUE,
1765                               GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1766                               &put_migration_continuation, pmc))
1767     {
1768       put_migration_continuation (pmc,
1769                                   GNUNET_SYSERR,
1770                                   GNUNET_TIME_UNIT_ZERO_ABS,
1771                                   NULL);
1772     }
1773   }
1774   else if (NULL != cp)
1775   {
1776     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1777                 "Choosing not to keep content `%s' (%d/%d)\n",
1778                 GNUNET_h2s (&query), active_to_migration,
1779                 test_put_load_too_high (prq.priority));
1780   }
1781   putl = GNUNET_LOAD_get_load (datastore_put_load);
1782   if ( (NULL != cp) &&
1783        (GNUNET_NO == prq.request_found) &&
1784        ( (GNUNET_YES != active_to_migration) ||
1785          (putl > 2.5 * (1 + prq.priority)) ) )
1786   {
1787     if (GNUNET_YES != active_to_migration)
1788       putl = 1.0 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 5);
1789     block_time =
1790         GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1791                                        5000 +
1792                                        GNUNET_CRYPTO_random_u32
1793                                        (GNUNET_CRYPTO_QUALITY_WEAK,
1794                                         (unsigned int) (60000 * putl * putl)));
1795     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1796                 "Asking to stop migration for %s because of load %f and events %d/%d\n",
1797                 GNUNET_STRINGS_relative_time_to_string (block_time,
1798                                                         GNUNET_YES),
1799                 putl,
1800                 active_to_migration,
1801                 (GNUNET_NO == prq.request_found));
1802     GSF_block_peer_migration_ (cp, GNUNET_TIME_relative_to_absolute (block_time));
1803   }
1804   return GNUNET_OK;
1805 }
1806
1807
1808 /**
1809  * Setup the subsystem.
1810  */
1811 void
1812 GSF_pending_request_init_ ()
1813 {
1814   if (GNUNET_OK !=
1815       GNUNET_CONFIGURATION_get_value_number (GSF_cfg, "fs",
1816                                              "MAX_PENDING_REQUESTS",
1817                                              &max_pending_requests))
1818   {
1819     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_INFO,
1820                                "fs", "MAX_PENDING_REQUESTS");
1821   }
1822   active_to_migration =
1823       GNUNET_CONFIGURATION_get_value_yesno (GSF_cfg, "FS", "CONTENT_CACHING");
1824   datastore_put_load = GNUNET_LOAD_value_init (DATASTORE_LOAD_AUTODECLINE);
1825   pr_map = GNUNET_CONTAINER_multihashmap_create (32 * 1024, GNUNET_YES);
1826   requests_by_expiration_heap =
1827       GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1828 }
1829
1830
1831 /**
1832  * Shutdown the subsystem.
1833  */
1834 void
1835 GSF_pending_request_done_ ()
1836 {
1837   GNUNET_CONTAINER_multihashmap_iterate (pr_map, &clean_request, NULL);
1838   GNUNET_CONTAINER_multihashmap_destroy (pr_map);
1839   pr_map = NULL;
1840   GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
1841   requests_by_expiration_heap = NULL;
1842   GNUNET_LOAD_value_free (datastore_put_load);
1843   datastore_put_load = NULL;
1844 }
1845
1846
1847 /* end of gnunet-service-fs_pr.c */