- refactor to check messages from both enc systems
[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 | GNUNET_ERROR_TYPE_BULK,
1279               _("Datastore lookup already took %s!\n"),
1280               GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (pr->qe_start),
1281                                                       GNUNET_YES));
1282   pr->warn_task =
1283       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1284                                     &warn_delay_task,
1285                                     pr);
1286 }
1287
1288
1289 /**
1290  * Task that issues a warning if the datastore lookup takes too long.
1291  *
1292  * @param cls the 'struct GSF_PendingRequest'
1293  * @param tc task context
1294  */
1295 static void
1296 odc_warn_delay_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1297 {
1298   struct GSF_PendingRequest *pr = cls;
1299
1300   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1301               _("On-demand lookup already took %s!\n"),
1302               GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (pr->qe_start), GNUNET_YES));
1303   pr->warn_task =
1304       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1305                                     &odc_warn_delay_task, pr);
1306 }
1307
1308
1309 /**
1310  * We're processing (local) results for a search request
1311  * from another peer.  Pass applicable results to the
1312  * peer and if we are done either clean up (operation
1313  * complete) or forward to other peers (more results possible).
1314  *
1315  * @param cls our closure (`struct GSF_PendingRequest *`)
1316  * @param key key for the content
1317  * @param size number of bytes in @a data
1318  * @param data content stored
1319  * @param type type of the content
1320  * @param priority priority of the content
1321  * @param anonymity anonymity-level for the content
1322  * @param expiration expiration time for the content
1323  * @param uid unique identifier for the datum;
1324  *        maybe 0 if no unique identifier is available
1325  */
1326 static void
1327 process_local_reply (void *cls,
1328                      const struct GNUNET_HashCode *key,
1329                      size_t size,
1330                      const void *data,
1331                      enum GNUNET_BLOCK_Type type,
1332                      uint32_t priority,
1333                      uint32_t anonymity,
1334                      struct GNUNET_TIME_Absolute expiration,
1335                      uint64_t uid)
1336 {
1337   struct GSF_PendingRequest *pr = cls;
1338   GSF_LocalLookupContinuation cont;
1339   struct ProcessReplyClosure prq;
1340   struct GNUNET_HashCode query;
1341   unsigned int old_rf;
1342
1343   GNUNET_SCHEDULER_cancel (pr->warn_task);
1344   pr->warn_task = NULL;
1345   if (NULL != pr->qe)
1346   {
1347     pr->qe = NULL;
1348     if (NULL == key)
1349     {
1350 #if INSANE_STATISTICS
1351       GNUNET_STATISTICS_update (GSF_stats,
1352                                 gettext_noop
1353                                 ("# Datastore lookups concluded (no results)"),
1354                                 1, GNUNET_NO);
1355 #endif
1356     }
1357     if (GNUNET_NO == pr->have_first_uid)
1358     {
1359       pr->first_uid = uid;
1360       pr->have_first_uid = 1;
1361     }
1362     else
1363     {
1364       if ((uid == pr->first_uid) && (key != NULL))
1365       {
1366         GNUNET_STATISTICS_update (GSF_stats,
1367                                   gettext_noop
1368                                   ("# Datastore lookups concluded (seen all)"),
1369                                   1, GNUNET_NO);
1370         key = NULL;             /* all replies seen! */
1371       }
1372       pr->have_first_uid++;
1373       if ((pr->have_first_uid > MAX_RESULTS) && (key != NULL))
1374       {
1375         GNUNET_STATISTICS_update (GSF_stats,
1376                                   gettext_noop
1377                                   ("# Datastore lookups aborted (more than MAX_RESULTS)"),
1378                                   1, GNUNET_NO);
1379         key = NULL;             /* all replies seen! */
1380       }
1381     }
1382   }
1383   if (NULL == key)
1384   {
1385     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1386                 "No further local responses available.\n");
1387 #if INSANE_STATISTICS
1388     if ((pr->public_data.type == GNUNET_BLOCK_TYPE_FS_DBLOCK) ||
1389         (pr->public_data.type == GNUNET_BLOCK_TYPE_FS_IBLOCK))
1390       GNUNET_STATISTICS_update (GSF_stats,
1391                                 gettext_noop
1392                                 ("# requested DBLOCK or IBLOCK not found"), 1,
1393                                 GNUNET_NO);
1394 #endif
1395     goto check_error_and_continue;
1396   }
1397   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1398               "Received reply for `%s' of type %d with UID %llu from datastore.\n",
1399               GNUNET_h2s (key), type, (unsigned long long) uid);
1400   if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
1401   {
1402     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1403                 "Found ONDEMAND block, performing on-demand encoding\n");
1404     GNUNET_STATISTICS_update (GSF_stats,
1405                               gettext_noop
1406                               ("# on-demand blocks matched requests"), 1,
1407                               GNUNET_NO);
1408     pr->qe_start = GNUNET_TIME_absolute_get ();
1409     pr->warn_task =
1410         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1411                                       &odc_warn_delay_task, pr);
1412     if (GNUNET_OK ==
1413         GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
1414                                           anonymity, expiration, uid,
1415                                           &process_local_reply, pr))
1416     {
1417       GNUNET_STATISTICS_update (GSF_stats,
1418                                 gettext_noop
1419                                 ("# on-demand lookups performed successfully"),
1420                                 1, GNUNET_NO);
1421       return;                   /* we're done */
1422     }
1423     GNUNET_STATISTICS_update (GSF_stats,
1424                               gettext_noop ("# on-demand lookups failed"), 1,
1425                               GNUNET_NO);
1426     GNUNET_SCHEDULER_cancel (pr->warn_task);
1427     pr->warn_task =
1428         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1429                                       &warn_delay_task, pr);
1430     pr->qe =
1431         GNUNET_DATASTORE_get_key (GSF_dsh, pr->local_result_offset - 1,
1432                                   &pr->public_data.query,
1433                                   pr->public_data.type ==
1434                                   GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1435                                   GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1436                                   (0 !=
1437                                    (GSF_PRO_PRIORITY_UNLIMITED &
1438                                     pr->public_data.options)) ? UINT_MAX : 1
1439                                   /* queue priority */ ,
1440                                   (0 !=
1441                                    (GSF_PRO_PRIORITY_UNLIMITED &
1442                                     pr->public_data.options)) ? UINT_MAX :
1443                                   GSF_datastore_queue_size
1444                                   /* max queue size */ ,
1445                                   GNUNET_TIME_UNIT_FOREVER_REL,
1446                                   &process_local_reply, pr);
1447     if (NULL != pr->qe)
1448       return;                   /* we're done */
1449     GNUNET_STATISTICS_update (GSF_stats,
1450                               gettext_noop
1451                               ("# Datastore lookups concluded (error queueing)"),
1452                               1, GNUNET_NO);
1453     goto check_error_and_continue;
1454   }
1455   old_rf = pr->public_data.results_found;
1456   memset (&prq, 0, sizeof (prq));
1457   prq.data = data;
1458   prq.expiration = expiration;
1459   prq.size = size;
1460   if (GNUNET_OK !=
1461       GNUNET_BLOCK_get_key (GSF_block_ctx, type, data, size, &query))
1462   {
1463     GNUNET_break (0);
1464     GNUNET_DATASTORE_remove (GSF_dsh, key, size, data, -1, -1,
1465                              GNUNET_TIME_UNIT_FOREVER_REL, NULL, NULL);
1466     pr->qe_start = GNUNET_TIME_absolute_get ();
1467     pr->warn_task =
1468         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1469                                       &warn_delay_task, pr);
1470     pr->qe =
1471         GNUNET_DATASTORE_get_key (GSF_dsh, pr->local_result_offset - 1,
1472                                   &pr->public_data.query,
1473                                   pr->public_data.type ==
1474                                   GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1475                                   GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1476                                   (0 !=
1477                                    (GSF_PRO_PRIORITY_UNLIMITED &
1478                                     pr->public_data.options)) ? UINT_MAX : 1
1479                                   /* queue priority */ ,
1480                                   (0 !=
1481                                    (GSF_PRO_PRIORITY_UNLIMITED &
1482                                     pr->public_data.options)) ? UINT_MAX :
1483                                   GSF_datastore_queue_size
1484                                   /* max queue size */ ,
1485                                   GNUNET_TIME_UNIT_FOREVER_REL,
1486                                   &process_local_reply, pr);
1487     if (pr->qe == NULL)
1488     {
1489       GNUNET_STATISTICS_update (GSF_stats,
1490                                 gettext_noop
1491                                 ("# Datastore lookups concluded (error queueing)"),
1492                                 1, GNUNET_NO);
1493       goto check_error_and_continue;
1494     }
1495     return;
1496   }
1497   prq.type = type;
1498   prq.priority = priority;
1499   prq.request_found = GNUNET_NO;
1500   prq.anonymity_level = anonymity;
1501   if ((0 == old_rf) && (0 == pr->public_data.results_found))
1502     GSF_update_datastore_delay_ (pr->public_data.start_time);
1503   prq.eo = GNUNET_BLOCK_EO_LOCAL_SKIP_CRYPTO;
1504   process_reply (&prq, key, pr);
1505   pr->local_result = prq.eval;
1506   if (prq.eval == GNUNET_BLOCK_EVALUATION_OK_LAST)
1507   {
1508     GNUNET_STATISTICS_update (GSF_stats,
1509                               gettext_noop
1510                               ("# Datastore lookups concluded (found last result)"),
1511                               1,
1512                               GNUNET_NO);
1513     goto check_error_and_continue;
1514   }
1515   if ((0 == (GSF_PRO_PRIORITY_UNLIMITED & pr->public_data.options)) &&
1516       ((GNUNET_YES == GSF_test_get_load_too_high_ (0)) ||
1517        (pr->public_data.results_found > 5 + 2 * pr->public_data.priority)))
1518   {
1519     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1520                 "Load too high, done with request\n");
1521     GNUNET_STATISTICS_update (GSF_stats,
1522                               gettext_noop ("# Datastore lookups concluded (load too high)"),
1523                               1,
1524                               GNUNET_NO);
1525     goto check_error_and_continue;
1526   }
1527   pr->qe_start = GNUNET_TIME_absolute_get ();
1528   pr->warn_task =
1529       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1530                                     &warn_delay_task,
1531                                     pr);
1532   pr->qe =
1533       GNUNET_DATASTORE_get_key (GSF_dsh, pr->local_result_offset++,
1534                                 &pr->public_data.query,
1535                                 pr->public_data.type ==
1536                                 GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1537                                 GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1538                                 (0 !=
1539                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1540                                   public_data.options)) ? UINT_MAX : 1
1541                                 /* queue priority */ ,
1542                                 (0 !=
1543                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1544                                   public_data.options)) ? UINT_MAX :
1545                                 GSF_datastore_queue_size
1546                                 /* max queue size */ ,
1547                                 GNUNET_TIME_UNIT_FOREVER_REL,
1548                                 &process_local_reply, pr);
1549   /* check if we successfully queued another datastore request;
1550    * if so, return, otherwise call our continuation (if we have
1551    * any) */
1552 check_error_and_continue:
1553   if (NULL != pr->qe)
1554     return;
1555   if (NULL != pr->warn_task)
1556   {
1557     GNUNET_SCHEDULER_cancel (pr->warn_task);
1558     pr->warn_task = NULL;
1559   }
1560   if (NULL == (cont = pr->llc_cont))
1561     return;                     /* no continuation */
1562   pr->llc_cont = NULL;
1563   if (0 != (GSF_PRO_LOCAL_ONLY & pr->public_data.options))
1564   {
1565     if (GNUNET_BLOCK_EVALUATION_OK_LAST != pr->local_result)
1566     {
1567       /* Signal that we are done and that there won't be any
1568          additional results to allow client to clean up state. */
1569       pr->rh (pr->rh_cls,
1570                GNUNET_BLOCK_EVALUATION_OK_LAST,
1571                pr,
1572                UINT32_MAX,
1573                GNUNET_TIME_UNIT_ZERO_ABS,
1574                GNUNET_TIME_UNIT_FOREVER_ABS,
1575                GNUNET_BLOCK_TYPE_ANY,
1576                NULL, 0);
1577     }
1578     /* Finally, call our continuation to signal that we are
1579        done with local processing of this request; i.e. to
1580        start reading again from the client. */
1581     cont (pr->llc_cont_cls, NULL, GNUNET_BLOCK_EVALUATION_OK_LAST);
1582     return;
1583   }
1584
1585   cont (pr->llc_cont_cls, pr, pr->local_result);
1586 }
1587
1588
1589 /**
1590  * Is the given target a legitimate peer for forwarding the given request?
1591  *
1592  * @param pr request
1593  * @param target
1594  * @return #GNUNET_YES if this request could be forwarded to the given peer
1595  */
1596 int
1597 GSF_pending_request_test_target_ (struct GSF_PendingRequest *pr,
1598                                   const struct GNUNET_PeerIdentity *target)
1599 {
1600   struct GNUNET_PeerIdentity pi;
1601
1602   if (0 == pr->origin_pid)
1603     return GNUNET_YES;
1604   GNUNET_PEER_resolve (pr->origin_pid, &pi);
1605   return (0 ==
1606           memcmp (&pi, target,
1607                   sizeof (struct GNUNET_PeerIdentity))) ? GNUNET_NO :
1608       GNUNET_YES;
1609 }
1610
1611
1612 /**
1613  * Look up the request in the local datastore.
1614  *
1615  * @param pr the pending request to process
1616  * @param cont function to call at the end
1617  * @param cont_cls closure for @a cont
1618  */
1619 void
1620 GSF_local_lookup_ (struct GSF_PendingRequest *pr,
1621                    GSF_LocalLookupContinuation cont,
1622                    void *cont_cls)
1623 {
1624   GNUNET_assert (NULL == pr->gh);
1625   GNUNET_assert (NULL == pr->cadet_request);
1626   GNUNET_assert (NULL == pr->llc_cont);
1627   pr->llc_cont = cont;
1628   pr->llc_cont_cls = cont_cls;
1629   pr->qe_start = GNUNET_TIME_absolute_get ();
1630   pr->warn_task =
1631       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1632                                     &warn_delay_task,
1633                                     pr);
1634 #if INSANE_STATISTICS
1635   GNUNET_STATISTICS_update (GSF_stats,
1636                             gettext_noop ("# Datastore lookups initiated"), 1,
1637                             GNUNET_NO);
1638 #endif
1639   pr->qe =
1640       GNUNET_DATASTORE_get_key (GSF_dsh, pr->local_result_offset++,
1641                                 &pr->public_data.query,
1642                                 pr->public_data.type ==
1643                                 GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1644                                 GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1645                                 (0 !=
1646                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1647                                   public_data.options)) ? UINT_MAX : 1
1648                                 /* queue priority */ ,
1649                                 (0 !=
1650                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1651                                   public_data.options)) ? UINT_MAX :
1652                                 GSF_datastore_queue_size
1653                                 /* max queue size */ ,
1654                                 GNUNET_TIME_UNIT_FOREVER_REL,
1655                                 &process_local_reply, pr);
1656   if (NULL != pr->qe)
1657     return;
1658   GNUNET_STATISTICS_update (GSF_stats,
1659                             gettext_noop
1660                             ("# Datastore lookups concluded (error queueing)"),
1661                             1, GNUNET_NO);
1662   GNUNET_SCHEDULER_cancel (pr->warn_task);
1663   pr->warn_task = NULL;
1664   pr->llc_cont = NULL;
1665   if (NULL != cont)
1666     cont (cont_cls, pr, pr->local_result);
1667 }
1668
1669
1670
1671 /**
1672  * Handle P2P "CONTENT" message.  Checks that the message is
1673  * well-formed and then checks if there are any pending requests for
1674  * this content and possibly passes it on (to local clients or other
1675  * peers).  Does NOT perform migration (content caching at this peer).
1676  *
1677  * @param cp the other peer involved (sender or receiver, NULL
1678  *        for loopback messages where we are both sender and receiver)
1679  * @param message the actual message
1680  * @return #GNUNET_OK if the message was well-formed,
1681  *         #GNUNET_SYSERR if the message was malformed (close connection,
1682  *         do not cache under any circumstances)
1683  */
1684 int
1685 GSF_handle_p2p_content_ (struct GSF_ConnectedPeer *cp,
1686                          const struct GNUNET_MessageHeader *message)
1687 {
1688   const struct PutMessage *put;
1689   uint16_t msize;
1690   size_t dsize;
1691   enum GNUNET_BLOCK_Type type;
1692   struct GNUNET_TIME_Absolute expiration;
1693   struct GNUNET_HashCode query;
1694   struct ProcessReplyClosure prq;
1695   struct GNUNET_TIME_Relative block_time;
1696   double putl;
1697   struct PutMigrationContext *pmc;
1698
1699   msize = ntohs (message->size);
1700   if (msize < sizeof (struct PutMessage))
1701   {
1702     GNUNET_break_op (0);
1703     return GNUNET_SYSERR;
1704   }
1705   put = (const struct PutMessage *) message;
1706   dsize = msize - sizeof (struct PutMessage);
1707   type = ntohl (put->type);
1708   expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
1709   /* do not allow migrated content to live longer than 1 year */
1710   expiration = GNUNET_TIME_absolute_min (GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_YEARS),
1711                                          expiration);
1712   if (GNUNET_BLOCK_TYPE_FS_ONDEMAND == type)
1713     return GNUNET_SYSERR;
1714   if (GNUNET_OK !=
1715       GNUNET_BLOCK_get_key (GSF_block_ctx,
1716                             type,
1717                             &put[1],
1718                             dsize,
1719                             &query))
1720   {
1721     GNUNET_break_op (0);
1722     return GNUNET_SYSERR;
1723   }
1724   GNUNET_STATISTICS_update (GSF_stats,
1725                             gettext_noop ("# GAP PUT messages received"),
1726                             1,
1727                             GNUNET_NO);
1728   /* now, lookup 'query' */
1729   prq.data = (const void *) &put[1];
1730   prq.sender = cp;
1731   prq.size = dsize;
1732   prq.type = type;
1733   prq.expiration = expiration;
1734   prq.priority = 0;
1735   prq.anonymity_level = UINT32_MAX;
1736   prq.request_found = GNUNET_NO;
1737   prq.eo = GNUNET_BLOCK_EO_NONE;
1738   GNUNET_CONTAINER_multihashmap_get_multiple (pr_map,
1739                                               &query,
1740                                               &process_reply,
1741                                               &prq);
1742   if (NULL != cp)
1743   {
1744     GSF_connected_peer_change_preference_ (cp,
1745                                            CONTENT_BANDWIDTH_VALUE +
1746                                            1000 * prq.priority);
1747     GSF_get_peer_performance_data_ (cp)->respect += prq.priority;
1748   }
1749   if ((GNUNET_YES == active_to_migration) &&
1750       (NULL != cp) &&
1751       (GNUNET_NO == test_put_load_too_high (prq.priority)))
1752   {
1753     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1754                 "Replicating result for query `%s' with priority %u\n",
1755                 GNUNET_h2s (&query),
1756                 prq.priority);
1757     pmc = GNUNET_new (struct PutMigrationContext);
1758     pmc->start = GNUNET_TIME_absolute_get ();
1759     pmc->requested = prq.request_found;
1760     GNUNET_assert (0 != GSF_get_peer_performance_data_ (cp)->pid);
1761     GNUNET_PEER_resolve (GSF_get_peer_performance_data_ (cp)->pid,
1762                          &pmc->origin);
1763     if (NULL ==
1764         GNUNET_DATASTORE_put (GSF_dsh, 0, &query, dsize, &put[1], type,
1765                               prq.priority, 1 /* anonymity */ ,
1766                               0 /* replication */ ,
1767                               expiration, 1 + prq.priority, MAX_DATASTORE_QUEUE,
1768                               GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1769                               &put_migration_continuation, pmc))
1770     {
1771       put_migration_continuation (pmc,
1772                                   GNUNET_SYSERR,
1773                                   GNUNET_TIME_UNIT_ZERO_ABS,
1774                                   NULL);
1775     }
1776   }
1777   else if (NULL != cp)
1778   {
1779     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1780                 "Choosing not to keep content `%s' (%d/%d)\n",
1781                 GNUNET_h2s (&query), active_to_migration,
1782                 test_put_load_too_high (prq.priority));
1783   }
1784   putl = GNUNET_LOAD_get_load (datastore_put_load);
1785   if ( (NULL != cp) &&
1786        (GNUNET_NO == prq.request_found) &&
1787        ( (GNUNET_YES != active_to_migration) ||
1788          (putl > 2.5 * (1 + prq.priority)) ) )
1789   {
1790     if (GNUNET_YES != active_to_migration)
1791       putl = 1.0 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 5);
1792     block_time =
1793         GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1794                                        5000 +
1795                                        GNUNET_CRYPTO_random_u32
1796                                        (GNUNET_CRYPTO_QUALITY_WEAK,
1797                                         (unsigned int) (60000 * putl * putl)));
1798     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1799                 "Asking to stop migration for %s because of load %f and events %d/%d\n",
1800                 GNUNET_STRINGS_relative_time_to_string (block_time,
1801                                                         GNUNET_YES),
1802                 putl,
1803                 active_to_migration,
1804                 (GNUNET_NO == prq.request_found));
1805     GSF_block_peer_migration_ (cp, GNUNET_TIME_relative_to_absolute (block_time));
1806   }
1807   return GNUNET_OK;
1808 }
1809
1810
1811 /**
1812  * Setup the subsystem.
1813  */
1814 void
1815 GSF_pending_request_init_ ()
1816 {
1817   if (GNUNET_OK !=
1818       GNUNET_CONFIGURATION_get_value_number (GSF_cfg, "fs",
1819                                              "MAX_PENDING_REQUESTS",
1820                                              &max_pending_requests))
1821   {
1822     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_INFO,
1823                                "fs", "MAX_PENDING_REQUESTS");
1824   }
1825   active_to_migration =
1826       GNUNET_CONFIGURATION_get_value_yesno (GSF_cfg, "FS", "CONTENT_CACHING");
1827   datastore_put_load = GNUNET_LOAD_value_init (DATASTORE_LOAD_AUTODECLINE);
1828   pr_map = GNUNET_CONTAINER_multihashmap_create (32 * 1024, GNUNET_YES);
1829   requests_by_expiration_heap =
1830       GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1831 }
1832
1833
1834 /**
1835  * Shutdown the subsystem.
1836  */
1837 void
1838 GSF_pending_request_done_ ()
1839 {
1840   GNUNET_CONTAINER_multihashmap_iterate (pr_map, &clean_request, NULL);
1841   GNUNET_CONTAINER_multihashmap_destroy (pr_map);
1842   pr_map = NULL;
1843   GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
1844   requests_by_expiration_heap = NULL;
1845   GNUNET_LOAD_value_free (datastore_put_load);
1846   datastore_put_load = NULL;
1847 }
1848
1849
1850 /* end of gnunet-service-fs_pr.c */