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