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