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