dead code elimination, splitting fs.h into fs.h and fs_api.h
[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_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       dpr->rh (dpr->rh_cls, GNUNET_BLOCK_EVALUATION_REQUEST_VALID, dpr,
362                UINT32_MAX, GNUNET_TIME_UNIT_FOREVER_ABS, GNUNET_BLOCK_TYPE_ANY,
363                NULL, 0);
364       GSF_pending_request_cancel_ (dpr, GNUNET_YES);
365     }
366   }
367   GNUNET_STATISTICS_update (GSF_stats,
368                             gettext_noop ("# Pending requests active"), 1,
369                             GNUNET_NO);
370   return pr;
371 }
372
373
374 /**
375  * Obtain the public data associated with a pending request
376  *
377  * @param pr pending request
378  * @return associated public data
379  */
380 struct GSF_PendingRequestData *
381 GSF_pending_request_get_data_ (struct GSF_PendingRequest *pr)
382 {
383   return &pr->public_data;
384 }
385
386
387 /**
388  * Test if two pending requests are compatible (would generate
389  * the same query modulo filters and should thus be processed
390  * jointly).
391  *
392  * @param pra a pending request
393  * @param prb another pending request
394  * @return GNUNET_OK if the requests are compatible
395  */
396 int
397 GSF_pending_request_is_compatible_ (struct GSF_PendingRequest *pra,
398                                     struct GSF_PendingRequest *prb)
399 {
400   if ((pra->public_data.type != prb->public_data.type) ||
401       (0 !=
402        memcmp (&pra->public_data.query, &prb->public_data.query,
403                sizeof (GNUNET_HashCode))) ||
404       ((pra->public_data.type == GNUNET_BLOCK_TYPE_FS_SBLOCK) &&
405        (0 !=
406         memcmp (&pra->public_data.namespace, &prb->public_data.namespace,
407                 sizeof (GNUNET_HashCode)))))
408     return GNUNET_NO;
409   return GNUNET_OK;
410 }
411
412
413
414 /**
415  * Update a given pending request with additional replies
416  * that have been seen.
417  *
418  * @param pr request to update
419  * @param replies_seen hash codes of replies that we've seen
420  * @param replies_seen_count size of the replies_seen array
421  */
422 void
423 GSF_pending_request_update_ (struct GSF_PendingRequest *pr,
424                              const GNUNET_HashCode * replies_seen,
425                              unsigned int replies_seen_count)
426 {
427   unsigned int i;
428   GNUNET_HashCode mhash;
429
430   if (replies_seen_count + pr->replies_seen_count < pr->replies_seen_count)
431     return;                     /* integer overflow */
432   if (0 != (pr->public_data.options & GSF_PRO_BLOOMFILTER_FULL_REFRESH))
433   {
434     /* we're responsible for the BF, full refresh */
435     if (replies_seen_count + pr->replies_seen_count > pr->replies_seen_size)
436       GNUNET_array_grow (pr->replies_seen, pr->replies_seen_size,
437                          replies_seen_count + pr->replies_seen_count);
438     memcpy (&pr->replies_seen[pr->replies_seen_count], replies_seen,
439             sizeof (GNUNET_HashCode) * replies_seen_count);
440     pr->replies_seen_count += replies_seen_count;
441     refresh_bloomfilter (pr);
442   }
443   else
444   {
445     if (NULL == pr->bf)
446     {
447       /* we're not the initiator, but the initiator did not give us
448        * any bloom-filter, so we need to create one on-the-fly */
449       pr->mingle =
450           GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
451       pr->bf =
452           GNUNET_BLOCK_construct_bloomfilter (pr->mingle, replies_seen,
453                                               replies_seen_count);
454     }
455     else
456     {
457       for (i = 0; i < pr->replies_seen_count; i++)
458       {
459         GNUNET_BLOCK_mingle_hash (&replies_seen[i], pr->mingle, &mhash);
460         GNUNET_CONTAINER_bloomfilter_add (pr->bf, &mhash);
461       }
462     }
463   }
464 }
465
466
467 /**
468  * Generate the message corresponding to the given pending request for
469  * transmission to other peers (or at least determine its size).
470  *
471  * @param pr request to generate the message for
472  * @param buf_size number of bytes available in buf
473  * @param buf where to copy the message (can be NULL)
474  * @return number of bytes needed (if > buf_size) or used
475  */
476 size_t
477 GSF_pending_request_get_message_ (struct GSF_PendingRequest *pr,
478                                   size_t buf_size, void *buf)
479 {
480   char lbuf[GNUNET_SERVER_MAX_MESSAGE_SIZE];
481   struct GetMessage *gm;
482   GNUNET_HashCode *ext;
483   size_t msize;
484   unsigned int k;
485   uint32_t bm;
486   uint32_t prio;
487   size_t bf_size;
488   struct GNUNET_TIME_Absolute now;
489   int64_t ttl;
490   int do_route;
491
492 #if DEBUG_FS
493   if (buf_size > 0)
494     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
495                 "Building request message for `%s' of type %d\n",
496                 GNUNET_h2s (&pr->public_data.query), pr->public_data.type);
497 #endif
498   k = 0;
499   bm = 0;
500   do_route = (0 == (pr->public_data.options & GSF_PRO_FORWARD_ONLY));
501   if ((!do_route) && (pr->sender_pid == 0))
502   {
503     GNUNET_break (0);
504     do_route = GNUNET_YES;
505   }
506   if (!do_route)
507   {
508     bm |= GET_MESSAGE_BIT_RETURN_TO;
509     k++;
510   }
511   if (GNUNET_BLOCK_TYPE_FS_SBLOCK == pr->public_data.type)
512   {
513     bm |= GET_MESSAGE_BIT_SKS_NAMESPACE;
514     k++;
515   }
516   if (GNUNET_YES == pr->public_data.has_target)
517   {
518     bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
519     k++;
520   }
521   bf_size = GNUNET_CONTAINER_bloomfilter_get_size (pr->bf);
522   msize = sizeof (struct GetMessage) + bf_size + k * sizeof (GNUNET_HashCode);
523   GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
524   if (buf_size < msize)
525     return msize;
526   gm = (struct GetMessage *) lbuf;
527   gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
528   gm->header.size = htons (msize);
529   gm->type = htonl (pr->public_data.type);
530   if (do_route)
531     prio =
532         GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
533                                   pr->public_data.priority + 1);
534   else
535     prio = 0;
536   pr->public_data.priority -= prio;
537   gm->priority = htonl (prio);
538   now = GNUNET_TIME_absolute_get ();
539   ttl = (int64_t) (pr->public_data.ttl.abs_value - now.abs_value);
540   gm->ttl = htonl (ttl / 1000);
541   gm->filter_mutator = htonl (pr->mingle);
542   gm->hash_bitmap = htonl (bm);
543   gm->query = pr->public_data.query;
544   ext = (GNUNET_HashCode *) & gm[1];
545   k = 0;
546   if (!do_route)
547     GNUNET_PEER_resolve (pr->sender_pid,
548                          (struct GNUNET_PeerIdentity *) &ext[k++]);
549   if (GNUNET_BLOCK_TYPE_FS_SBLOCK == pr->public_data.type)
550     memcpy (&ext[k++], &pr->public_data.namespace, sizeof (GNUNET_HashCode));
551   if (GNUNET_YES == pr->public_data.has_target)
552     ext[k++] = pr->public_data.target.hashPubKey;
553   if (pr->bf != NULL)
554     GNUNET_assert (GNUNET_SYSERR !=
555                    GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
556                                                               (char *) &ext[k],
557                                                               bf_size));
558   memcpy (buf, gm, msize);
559   return msize;
560 }
561
562
563 /**
564  * Iterator to free pending requests.
565  *
566  * @param cls closure, unused
567  * @param key current key code
568  * @param value value in the hash map (pending request)
569  * @return GNUNET_YES (we should continue to iterate)
570  */
571 static int
572 clean_request (void *cls, const GNUNET_HashCode * key, void *value)
573 {
574   struct GSF_PendingRequest *pr = value;
575   GSF_LocalLookupContinuation cont;
576
577 #if DEBUG_FS
578   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
579               "Cleaning up pending request for `%s'.\n", GNUNET_h2s (key));
580 #endif
581   if (NULL != (cont = pr->llc_cont))
582   {
583     pr->llc_cont = NULL;
584     cont (pr->llc_cont_cls, pr, pr->local_result);
585   }
586   GSF_plan_notify_request_done_ (pr);
587   GNUNET_free_non_null (pr->replies_seen);
588   if (NULL != pr->bf)
589   {
590     GNUNET_CONTAINER_bloomfilter_free (pr->bf);
591     pr->bf = NULL;
592   }
593   GNUNET_PEER_change_rc (pr->sender_pid, -1);
594   pr->sender_pid = 0;
595   GNUNET_PEER_change_rc (pr->origin_pid, -1);
596   pr->origin_pid = 0;
597   if (NULL != pr->hnode)
598   {
599     GNUNET_CONTAINER_heap_remove_node (pr->hnode);
600     pr->hnode = NULL;
601   }
602   if (NULL != pr->qe)
603   {
604     GNUNET_DATASTORE_cancel (pr->qe);
605     pr->qe = NULL;
606   }
607   if (NULL != pr->gh)
608   {
609     GNUNET_DHT_get_stop (pr->gh);
610     pr->gh = NULL;
611   }
612   if (GNUNET_SCHEDULER_NO_TASK != pr->warn_task)
613   {
614     GNUNET_SCHEDULER_cancel (pr->warn_task);
615     pr->warn_task = GNUNET_SCHEDULER_NO_TASK;
616   }
617   GNUNET_assert (GNUNET_OK ==
618                  GNUNET_CONTAINER_multihashmap_remove (pr_map,
619                                                        &pr->public_data.query,
620                                                        pr));
621   GNUNET_STATISTICS_update (GSF_stats,
622                             gettext_noop ("# Pending requests active"), -1,
623                             GNUNET_NO);
624   GNUNET_free (pr);
625   return GNUNET_YES;
626 }
627
628
629 /**
630  * Explicitly cancel a pending request.
631  *
632  * @param pr request to cancel
633  * @param full_cleanup fully purge the request
634  */
635 void
636 GSF_pending_request_cancel_ (struct GSF_PendingRequest *pr, int full_cleanup)
637 {
638   GSF_LocalLookupContinuation cont;
639
640   if (NULL == pr_map)
641     return;                     /* already cleaned up! */
642   if (GNUNET_YES != full_cleanup)
643   {
644     /* make request inactive (we're no longer interested in more results),
645      * but do NOT remove from our data-structures, we still need it there
646      * to prevent the request from looping */
647     pr->rh = NULL;
648     if (NULL != (cont = pr->llc_cont))
649     {
650       pr->llc_cont = NULL;
651       cont (pr->llc_cont_cls, pr, pr->local_result);
652     }
653     GSF_plan_notify_request_done_ (pr);
654     if (NULL != pr->qe)
655     {
656       GNUNET_DATASTORE_cancel (pr->qe);
657       pr->qe = NULL;
658     }
659     if (NULL != pr->gh)
660     {
661       GNUNET_DHT_get_stop (pr->gh);
662       pr->gh = NULL;
663     }
664     if (GNUNET_SCHEDULER_NO_TASK != pr->warn_task)
665     {
666       GNUNET_SCHEDULER_cancel (pr->warn_task);
667       pr->warn_task = GNUNET_SCHEDULER_NO_TASK;
668     }
669     return;
670   }
671   GNUNET_assert (GNUNET_YES ==
672                  clean_request (NULL, &pr->public_data.query, pr));
673 }
674
675
676 /**
677  * Iterate over all pending requests.
678  *
679  * @param it function to call for each request
680  * @param cls closure for it
681  */
682 void
683 GSF_iterate_pending_requests_ (GSF_PendingRequestIterator it, void *cls)
684 {
685   GNUNET_CONTAINER_multihashmap_iterate (pr_map,
686                                          (GNUNET_CONTAINER_HashMapIterator) it,
687                                          cls);
688 }
689
690
691
692
693 /**
694  * Closure for "process_reply" function.
695  */
696 struct ProcessReplyClosure
697 {
698   /**
699    * The data for the reply.
700    */
701   const void *data;
702
703   /**
704    * Who gave us this reply? NULL for local host (or DHT)
705    */
706   struct GSF_ConnectedPeer *sender;
707
708   /**
709    * When the reply expires.
710    */
711   struct GNUNET_TIME_Absolute expiration;
712
713   /**
714    * Size of data.
715    */
716   size_t size;
717
718   /**
719    * Type of the block.
720    */
721   enum GNUNET_BLOCK_Type type;
722
723   /**
724    * How much was this reply worth to us?
725    */
726   uint32_t priority;
727
728   /**
729    * Anonymity requirements for this reply.
730    */
731   uint32_t anonymity_level;
732
733   /**
734    * Evaluation result (returned).
735    */
736   enum GNUNET_BLOCK_EvaluationResult eval;
737
738   /**
739    * Did we find a matching request?
740    */
741   int request_found;
742 };
743
744
745 /**
746  * Update the performance data for the sender (if any) since
747  * the sender successfully answered one of our queries.
748  *
749  * @param prq information about the sender
750  * @param pr request that was satisfied
751  */
752 static void
753 update_request_performance_data (struct ProcessReplyClosure *prq,
754                                  struct GSF_PendingRequest *pr)
755 {
756   if (prq->sender == NULL)
757     return;
758   GSF_peer_update_performance_ (prq->sender, pr->public_data.start_time,
759                                 prq->priority);
760 }
761
762
763 /**
764  * We have received a reply; handle it!
765  *
766  * @param cls response (struct ProcessReplyClosure)
767  * @param key our query
768  * @param value value in the hash map (info about the query)
769  * @return GNUNET_YES (we should continue to iterate)
770  */
771 static int
772 process_reply (void *cls, const GNUNET_HashCode * key, void *value)
773 {
774   struct ProcessReplyClosure *prq = cls;
775   struct GSF_PendingRequest *pr = value;
776   GNUNET_HashCode chash;
777
778   if (NULL == pr->rh)
779     return GNUNET_YES;
780 #if DEBUG_FS
781   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
782               "Matched result (type %u) for query `%s' with pending request\n",
783               (unsigned int) prq->type, GNUNET_h2s (key));
784 #endif
785   GNUNET_STATISTICS_update (GSF_stats,
786                             gettext_noop ("# replies received and matched"), 1,
787                             GNUNET_NO);
788   prq->eval =
789       GNUNET_BLOCK_evaluate (GSF_block_ctx, prq->type, key, &pr->bf, pr->mingle,
790                              &pr->public_data.namespace,
791                              (prq->type ==
792                               GNUNET_BLOCK_TYPE_FS_SBLOCK) ?
793                              sizeof (GNUNET_HashCode) : 0, prq->data,
794                              prq->size);
795   switch (prq->eval)
796   {
797   case GNUNET_BLOCK_EVALUATION_OK_MORE:
798     update_request_performance_data (prq, pr);
799     break;
800   case GNUNET_BLOCK_EVALUATION_OK_LAST:
801     /* short cut: stop processing early, no BF-update, etc. */
802     update_request_performance_data (prq, pr);
803     GNUNET_LOAD_update (GSF_rt_entry_lifetime,
804                         GNUNET_TIME_absolute_get_duration (pr->
805                                                            public_data.start_time).rel_value);
806     /* pass on to other peers / local clients */
807     pr->rh (pr->rh_cls, prq->eval, pr, prq->anonymity_level, prq->expiration,
808             prq->type, prq->data, prq->size);
809     return GNUNET_YES;
810   case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
811     GNUNET_STATISTICS_update (GSF_stats,
812                               gettext_noop
813                               ("# duplicate replies discarded (bloomfilter)"),
814                               1, GNUNET_NO);
815 #if DEBUG_FS && 0
816     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
817                 "Duplicate response `%s', discarding.\n", GNUNET_h2s (&mhash));
818 #endif
819     return GNUNET_YES;          /* duplicate */
820   case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
821     return GNUNET_YES;          /* wrong namespace */
822   case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
823     GNUNET_break (0);
824     return GNUNET_YES;
825   case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
826     GNUNET_break (0);
827     return GNUNET_YES;
828   case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
829     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Unsupported block type %u\n"),
830                 prq->type);
831     return GNUNET_NO;
832   }
833   /* update bloomfilter */
834   GNUNET_CRYPTO_hash (prq->data, prq->size, &chash);
835   GSF_pending_request_update_ (pr, &chash, 1);
836   if (NULL == prq->sender)
837   {
838 #if DEBUG_FS
839     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
840                 "Found result for query `%s' in local datastore\n",
841                 GNUNET_h2s (key));
842 #endif
843     GNUNET_STATISTICS_update (GSF_stats,
844                               gettext_noop ("# results found locally"), 1,
845                               GNUNET_NO);
846   }
847   else
848   {
849     GSF_dht_lookup_ (pr);
850   }
851   prq->priority += pr->public_data.original_priority;
852   pr->public_data.priority = 0;
853   pr->public_data.original_priority = 0;
854   pr->public_data.results_found++;
855   prq->request_found = GNUNET_YES;
856   /* finally, pass on to other peer / local client */
857   pr->rh (pr->rh_cls, prq->eval, pr, prq->anonymity_level, prq->expiration,
858           prq->type, prq->data, prq->size);
859   return GNUNET_YES;
860 }
861
862
863 /**
864  * Context for the 'put_migration_continuation'.
865  */
866 struct PutMigrationContext
867 {
868
869   /**
870    * Start time for the operation.
871    */
872   struct GNUNET_TIME_Absolute start;
873
874   /**
875    * Request origin.
876    */
877   struct GNUNET_PeerIdentity origin;
878
879   /**
880    * GNUNET_YES if we had a matching request for this block,
881    * GNUNET_NO if not.
882    */
883   int requested;
884 };
885
886
887 /**
888  * Continuation called to notify client about result of the
889  * operation.
890  *
891  * @param cls closure
892  * @param success GNUNET_SYSERR on failure
893  * @param msg NULL on success, otherwise an error message
894  */
895 static void
896 put_migration_continuation (void *cls, int success, const char *msg)
897 {
898   struct PutMigrationContext *pmc = cls;
899   struct GNUNET_TIME_Relative delay;
900   struct GNUNET_TIME_Relative block_time;
901   struct GSF_ConnectedPeer *cp;
902   struct GSF_PeerPerformanceData *ppd;
903
904   delay = GNUNET_TIME_absolute_get_duration (pmc->start);
905   cp = GSF_peer_get_ (&pmc->origin);
906   if ((GNUNET_OK != success) && (GNUNET_NO == pmc->requested))
907   {
908     /* block migration for a bit... */
909     if (NULL != cp)
910     {
911       ppd = GSF_get_peer_performance_data_ (cp);
912       ppd->migration_duplication++;
913       block_time =
914           GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
915                                          5 * ppd->migration_duplication +
916                                          GNUNET_CRYPTO_random_u32
917                                          (GNUNET_CRYPTO_QUALITY_WEAK, 5));
918       GSF_block_peer_migration_ (cp, block_time);
919     }
920   }
921   else
922   {
923     if (NULL != cp)
924     {
925       ppd = GSF_get_peer_performance_data_ (cp);
926       ppd->migration_duplication = 0;   /* reset counter */
927     }
928   }
929   GNUNET_free (pmc);
930   /* FIXME: should we really update the load value on failure? */
931   if (NULL != datastore_put_load)
932     GNUNET_LOAD_update (datastore_put_load, delay.rel_value);
933   if (GNUNET_OK == success)
934     return;
935   GNUNET_STATISTICS_update (GSF_stats,
936                             gettext_noop ("# Datastore `PUT' failures"), 1,
937                             GNUNET_NO);
938 }
939
940
941 /**
942  * Test if the DATABASE (PUT) load on this peer is too high
943  * to even consider processing the query at
944  * all.
945  *
946  * @return GNUNET_YES if the load is too high to do anything (load high)
947  *         GNUNET_NO to process normally (load normal or low)
948  */
949 static int
950 test_put_load_too_high (uint32_t priority)
951 {
952   double ld;
953
954   if (NULL == datastore_put_load)
955     return GNUNET_NO;
956   if (GNUNET_LOAD_get_average (datastore_put_load) < 50)
957     return GNUNET_NO;           /* very fast */
958   ld = GNUNET_LOAD_get_load (datastore_put_load);
959   if (ld < 2.0 * (1 + priority))
960     return GNUNET_NO;
961   GNUNET_STATISTICS_update (GSF_stats,
962                             gettext_noop
963                             ("# storage requests dropped due to high load"), 1,
964                             GNUNET_NO);
965   return GNUNET_YES;
966 }
967
968
969 /**
970  * Iterator called on each result obtained for a DHT
971  * operation that expects a reply
972  *
973  * @param cls closure
974  * @param exp when will this value expire
975  * @param key key of the result
976  * @param get_path peers on reply path (or NULL if not recorded)
977  * @param get_path_length number of entries in get_path
978  * @param put_path peers on the PUT path (or NULL if not recorded)
979  * @param put_path_length number of entries in get_path
980  * @param type type of the result
981  * @param size number of bytes in data
982  * @param data pointer to the result data
983  */
984 static void
985 handle_dht_reply (void *cls, struct GNUNET_TIME_Absolute exp,
986                   const GNUNET_HashCode * key,
987                   const struct GNUNET_PeerIdentity *get_path,
988                   unsigned int get_path_length,
989                   const struct GNUNET_PeerIdentity *put_path,
990                   unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
991                   size_t size, const void *data)
992 {
993   struct GSF_PendingRequest *pr = cls;
994   struct ProcessReplyClosure prq;
995   struct PutMigrationContext *pmc;
996
997   GNUNET_STATISTICS_update (GSF_stats,
998                             gettext_noop ("# Replies received from DHT"), 1,
999                             GNUNET_NO);
1000   memset (&prq, 0, sizeof (prq));
1001   prq.data = data;
1002   prq.expiration = exp;
1003   prq.size = size;
1004   prq.type = type;
1005   process_reply (&prq, key, pr);
1006   if ((GNUNET_YES == active_to_migration) &&
1007       (GNUNET_NO == test_put_load_too_high (prq.priority)))
1008   {
1009 #if DEBUG_FS
1010     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1011                 "Replicating result for query `%s' with priority %u\n",
1012                 GNUNET_h2s (key), prq.priority);
1013 #endif
1014     pmc = GNUNET_malloc (sizeof (struct PutMigrationContext));
1015     pmc->start = GNUNET_TIME_absolute_get ();
1016     pmc->requested = GNUNET_YES;
1017     if (NULL ==
1018         GNUNET_DATASTORE_put (GSF_dsh, 0, key, size, data, type, prq.priority,
1019                               1 /* anonymity */ ,
1020                               0 /* replication */ ,
1021                               exp, 1 + prq.priority, MAX_DATASTORE_QUEUE,
1022                               GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1023                               &put_migration_continuation, pmc))
1024     {
1025       put_migration_continuation (pmc, GNUNET_NO, NULL);
1026     }
1027   }
1028 }
1029
1030
1031 /**
1032  * Consider looking up the data in the DHT (anonymity-level permitting).
1033  *
1034  * @param pr the pending request to process
1035  */
1036 void
1037 GSF_dht_lookup_ (struct GSF_PendingRequest *pr)
1038 {
1039   const void *xquery;
1040   size_t xquery_size;
1041   struct GNUNET_PeerIdentity pi;
1042   char buf[sizeof (GNUNET_HashCode) * 2];
1043
1044   if (0 != pr->public_data.anonymity_level)
1045     return;
1046   if (NULL != pr->gh)
1047   {
1048     GNUNET_DHT_get_stop (pr->gh);
1049     pr->gh = NULL;
1050   }
1051   xquery = NULL;
1052   xquery_size = 0;
1053   if (GNUNET_BLOCK_TYPE_FS_SBLOCK == pr->public_data.type)
1054   {
1055     xquery = buf;
1056     memcpy (buf, &pr->public_data.namespace, sizeof (GNUNET_HashCode));
1057     xquery_size = sizeof (GNUNET_HashCode);
1058   }
1059   if (0 != (pr->public_data.options & GSF_PRO_FORWARD_ONLY))
1060   {
1061     GNUNET_assert (0 != pr->sender_pid);
1062     GNUNET_PEER_resolve (pr->sender_pid, &pi);
1063     memcpy (&buf[xquery_size], &pi, sizeof (struct GNUNET_PeerIdentity));
1064     xquery_size += sizeof (struct GNUNET_PeerIdentity);
1065   }
1066   pr->gh =
1067       GNUNET_DHT_get_start (GSF_dht, GNUNET_TIME_UNIT_FOREVER_REL,
1068                             pr->public_data.type, &pr->public_data.query,
1069                             5 /* DEFAULT_GET_REPLICATION */ ,
1070                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
1071                             /* FIXME: can no longer pass pr->bf/pr->mingle... */
1072                             xquery, xquery_size, &handle_dht_reply, pr);
1073 }
1074
1075
1076 /**
1077  * Task that issues a warning if the datastore lookup takes too long.
1078  *
1079  * @param cls the 'struct GSF_PendingRequest'
1080  * @param tc task context
1081  */
1082 static void
1083 warn_delay_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1084 {
1085   struct GSF_PendingRequest *pr = cls;
1086
1087   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1088               _("Datastore lookup already took %llu ms!\n"),
1089               (unsigned long long)
1090               GNUNET_TIME_absolute_get_duration (pr->qe_start).rel_value);
1091   pr->warn_task =
1092       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, &warn_delay_task,
1093                                     pr);
1094 }
1095
1096
1097 /**
1098  * Task that issues a warning if the datastore lookup takes too long.
1099  *
1100  * @param cls the 'struct GSF_PendingRequest'
1101  * @param tc task context
1102  */
1103 static void
1104 odc_warn_delay_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1105 {
1106   struct GSF_PendingRequest *pr = cls;
1107
1108   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1109               _("On-demand lookup already took %llu ms!\n"),
1110               (unsigned long long)
1111               GNUNET_TIME_absolute_get_duration (pr->qe_start).rel_value);
1112   pr->warn_task =
1113       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1114                                     &odc_warn_delay_task, pr);
1115 }
1116
1117
1118 /**
1119  * We're processing (local) results for a search request
1120  * from another peer.  Pass applicable results to the
1121  * peer and if we are done either clean up (operation
1122  * complete) or forward to other peers (more results possible).
1123  *
1124  * @param cls our closure (struct PendingRequest)
1125  * @param key key for the content
1126  * @param size number of bytes in data
1127  * @param data content stored
1128  * @param type type of the content
1129  * @param priority priority of the content
1130  * @param anonymity anonymity-level for the content
1131  * @param expiration expiration time for the content
1132  * @param uid unique identifier for the datum;
1133  *        maybe 0 if no unique identifier is available
1134  */
1135 static void
1136 process_local_reply (void *cls, const GNUNET_HashCode * key, size_t size,
1137                      const void *data, enum GNUNET_BLOCK_Type type,
1138                      uint32_t priority, uint32_t anonymity,
1139                      struct GNUNET_TIME_Absolute expiration, uint64_t uid)
1140 {
1141   struct GSF_PendingRequest *pr = cls;
1142   GSF_LocalLookupContinuation cont;
1143   struct ProcessReplyClosure prq;
1144   GNUNET_HashCode query;
1145   unsigned int old_rf;
1146
1147   GNUNET_SCHEDULER_cancel (pr->warn_task);
1148   pr->warn_task = GNUNET_SCHEDULER_NO_TASK;
1149   if (NULL != pr->qe)
1150   {
1151     pr->qe = NULL;
1152     if (NULL == key)
1153     {
1154       GNUNET_STATISTICS_update (GSF_stats,
1155                                 gettext_noop
1156                                 ("# Datastore lookups concluded (no results)"),
1157                                 1, GNUNET_NO);
1158     }
1159     if (GNUNET_NO == pr->have_first_uid)
1160     {
1161       pr->first_uid = uid;
1162       pr->have_first_uid = 1;
1163     }
1164     else
1165     {
1166       if ((uid == pr->first_uid) && (key != NULL))
1167       {
1168         GNUNET_STATISTICS_update (GSF_stats,
1169                                   gettext_noop
1170                                   ("# Datastore lookups concluded (seen all)"),
1171                                   1, GNUNET_NO);
1172         key = NULL;             /* all replies seen! */
1173       }
1174       pr->have_first_uid++;
1175       if ((pr->have_first_uid > MAX_RESULTS) && (key != NULL))
1176       {
1177         GNUNET_STATISTICS_update (GSF_stats,
1178                                   gettext_noop
1179                                   ("# Datastore lookups aborted (more than MAX_RESULTS)"),
1180                                   1, GNUNET_NO);
1181         key = NULL;             /* all replies seen! */
1182       }
1183     }
1184   }
1185   if (NULL == key)
1186   {
1187 #if DEBUG_FS
1188     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1189                 "No further local responses available.\n");
1190 #endif
1191     if ((pr->public_data.type == GNUNET_BLOCK_TYPE_FS_DBLOCK) ||
1192         (pr->public_data.type == GNUNET_BLOCK_TYPE_FS_IBLOCK))
1193       GNUNET_STATISTICS_update (GSF_stats,
1194                                 gettext_noop
1195                                 ("# requested DBLOCK or IBLOCK not found"), 1,
1196                                 GNUNET_NO);
1197     goto check_error_and_continue;
1198   }
1199 #if DEBUG_FS
1200   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1201               "Received reply for `%s' of type %d with UID %llu from datastore.\n",
1202               GNUNET_h2s (key), type, (unsigned long long) uid);
1203 #endif
1204   if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
1205   {
1206 #if DEBUG_FS
1207     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1208                 "Found ONDEMAND block, performing on-demand encoding\n");
1209 #endif
1210     GNUNET_STATISTICS_update (GSF_stats,
1211                               gettext_noop
1212                               ("# on-demand blocks matched requests"), 1,
1213                               GNUNET_NO);
1214     pr->qe_start = GNUNET_TIME_absolute_get ();
1215     pr->warn_task =
1216         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1217                                       &odc_warn_delay_task, pr);
1218     if (GNUNET_OK ==
1219         GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
1220                                           anonymity, expiration, uid,
1221                                           &process_local_reply, pr))
1222     {
1223       GNUNET_STATISTICS_update (GSF_stats,
1224                                 gettext_noop
1225                                 ("# on-demand lookups performed successfully"),
1226                                 1, GNUNET_NO);
1227       return;                   /* we're done */
1228     }
1229     GNUNET_STATISTICS_update (GSF_stats,
1230                               gettext_noop ("# on-demand lookups failed"), 1,
1231                               GNUNET_NO);
1232     GNUNET_SCHEDULER_cancel (pr->warn_task);
1233     pr->warn_task =
1234         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1235                                       &warn_delay_task, pr);
1236     pr->qe =
1237         GNUNET_DATASTORE_get_key (GSF_dsh, pr->local_result_offset - 1,
1238                                   &pr->public_data.query,
1239                                   pr->public_data.type ==
1240                                   GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1241                                   GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1242                                   (0 !=
1243                                    (GSF_PRO_PRIORITY_UNLIMITED &
1244                                     pr->public_data.options)) ? UINT_MAX : 1
1245                                   /* queue priority */ ,
1246                                   (0 !=
1247                                    (GSF_PRO_PRIORITY_UNLIMITED &
1248                                     pr->public_data.options)) ? UINT_MAX :
1249                                   datastore_queue_size
1250                                   /* max queue size */ ,
1251                                   GNUNET_TIME_UNIT_FOREVER_REL,
1252                                   &process_local_reply, pr);
1253     if (NULL != pr->qe)
1254       return;                   /* we're done */
1255     GNUNET_STATISTICS_update (GSF_stats,
1256                               gettext_noop
1257                               ("# Datastore lookups concluded (error queueing)"),
1258                               1, GNUNET_NO);
1259     goto check_error_and_continue;
1260   }
1261   old_rf = pr->public_data.results_found;
1262   memset (&prq, 0, sizeof (prq));
1263   prq.data = data;
1264   prq.expiration = expiration;
1265   prq.size = size;
1266   if (GNUNET_OK !=
1267       GNUNET_BLOCK_get_key (GSF_block_ctx, type, data, size, &query))
1268   {
1269     GNUNET_break (0);
1270     GNUNET_DATASTORE_remove (GSF_dsh, key, size, data, -1, -1,
1271                              GNUNET_TIME_UNIT_FOREVER_REL, NULL, NULL);
1272     pr->qe_start = GNUNET_TIME_absolute_get ();
1273     pr->warn_task =
1274         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1275                                       &warn_delay_task, pr);
1276     pr->qe =
1277         GNUNET_DATASTORE_get_key (GSF_dsh, pr->local_result_offset - 1,
1278                                   &pr->public_data.query,
1279                                   pr->public_data.type ==
1280                                   GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1281                                   GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1282                                   (0 !=
1283                                    (GSF_PRO_PRIORITY_UNLIMITED &
1284                                     pr->public_data.options)) ? UINT_MAX : 1
1285                                   /* queue priority */ ,
1286                                   (0 !=
1287                                    (GSF_PRO_PRIORITY_UNLIMITED &
1288                                     pr->public_data.options)) ? UINT_MAX :
1289                                   datastore_queue_size
1290                                   /* max queue size */ ,
1291                                   GNUNET_TIME_UNIT_FOREVER_REL,
1292                                   &process_local_reply, pr);
1293     if (pr->qe == NULL)
1294     {
1295       GNUNET_STATISTICS_update (GSF_stats,
1296                                 gettext_noop
1297                                 ("# Datastore lookups concluded (error queueing)"),
1298                                 1, GNUNET_NO);
1299       goto check_error_and_continue;
1300     }
1301     return;
1302   }
1303   prq.type = type;
1304   prq.priority = priority;
1305   prq.request_found = GNUNET_NO;
1306   prq.anonymity_level = anonymity;
1307   if ((old_rf == 0) && (pr->public_data.results_found == 0))
1308     GSF_update_datastore_delay_ (pr->public_data.start_time);
1309   process_reply (&prq, key, pr);
1310   pr->local_result = prq.eval;
1311   if (prq.eval == GNUNET_BLOCK_EVALUATION_OK_LAST)
1312   {
1313     GNUNET_STATISTICS_update (GSF_stats,
1314                               gettext_noop
1315                               ("# Datastore lookups concluded (found last result)"),
1316                               1, GNUNET_NO);
1317     goto check_error_and_continue;
1318   }
1319   if ((0 == (GSF_PRO_PRIORITY_UNLIMITED & pr->public_data.options)) &&
1320       ((GNUNET_YES == GSF_test_get_load_too_high_ (0)) ||
1321        (pr->public_data.results_found > 5 + 2 * pr->public_data.priority)))
1322   {
1323 #if DEBUG_FS > 2
1324     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Load too high, done with request\n");
1325 #endif
1326     GNUNET_STATISTICS_update (GSF_stats,
1327                               gettext_noop
1328                               ("# Datastore lookups concluded (load too high)"),
1329                               1, GNUNET_NO);
1330     goto check_error_and_continue;
1331   }
1332   pr->qe_start = GNUNET_TIME_absolute_get ();
1333   pr->warn_task =
1334       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, &warn_delay_task,
1335                                     pr);
1336   pr->qe =
1337       GNUNET_DATASTORE_get_key (GSF_dsh, pr->local_result_offset++,
1338                                 &pr->public_data.query,
1339                                 pr->public_data.type ==
1340                                 GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1341                                 GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1342                                 (0 !=
1343                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1344                                   public_data.options)) ? UINT_MAX : 1
1345                                 /* queue priority */ ,
1346                                 (0 !=
1347                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1348                                   public_data.options)) ? UINT_MAX :
1349                                 datastore_queue_size
1350                                 /* max queue size */ ,
1351                                 GNUNET_TIME_UNIT_FOREVER_REL,
1352                                 &process_local_reply, pr);
1353   /* check if we successfully queued another datastore request;
1354    * if so, return, otherwise call our continuation (if we have
1355    * any) */
1356 check_error_and_continue:
1357   if (NULL != pr->qe)
1358     return;
1359   if (GNUNET_SCHEDULER_NO_TASK != pr->warn_task)
1360   {
1361     GNUNET_SCHEDULER_cancel (pr->warn_task);
1362     pr->warn_task = GNUNET_SCHEDULER_NO_TASK;
1363   }
1364   if (NULL == (cont = pr->llc_cont))
1365     return;                     /* no continuation */
1366   pr->llc_cont = NULL;
1367   cont (pr->llc_cont_cls, pr, pr->local_result);
1368 }
1369
1370
1371 /**
1372  * Is the given target a legitimate peer for forwarding the given request?
1373  *
1374  * @param pr request
1375  * @param target
1376  * @return GNUNET_YES if this request could be forwarded to the given peer
1377  */
1378 int
1379 GSF_pending_request_test_target_ (struct GSF_PendingRequest *pr,
1380                                   const struct GNUNET_PeerIdentity *target)
1381 {
1382   struct GNUNET_PeerIdentity pi;
1383
1384   if (0 == pr->origin_pid)
1385     return GNUNET_YES;
1386   GNUNET_PEER_resolve (pr->origin_pid, &pi);
1387   return (0 ==
1388           memcmp (&pi, target,
1389                   sizeof (struct GNUNET_PeerIdentity))) ? GNUNET_NO :
1390       GNUNET_YES;
1391 }
1392
1393
1394 /**
1395  * Look up the request in the local datastore.
1396  *
1397  * @param pr the pending request to process
1398  * @param cont function to call at the end
1399  * @param cont_cls closure for cont
1400  */
1401 void
1402 GSF_local_lookup_ (struct GSF_PendingRequest *pr,
1403                    GSF_LocalLookupContinuation cont, void *cont_cls)
1404 {
1405   GNUNET_assert (NULL == pr->gh);
1406   GNUNET_assert (NULL == pr->llc_cont);
1407   pr->llc_cont = cont;
1408   pr->llc_cont_cls = cont_cls;
1409   pr->qe_start = GNUNET_TIME_absolute_get ();
1410   pr->warn_task =
1411       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, &warn_delay_task,
1412                                     pr);
1413   GNUNET_STATISTICS_update (GSF_stats,
1414                             gettext_noop ("# Datastore lookups initiated"), 1,
1415                             GNUNET_NO);
1416   pr->qe =
1417       GNUNET_DATASTORE_get_key (GSF_dsh, pr->local_result_offset++,
1418                                 &pr->public_data.query,
1419                                 pr->public_data.type ==
1420                                 GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1421                                 GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1422                                 (0 !=
1423                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1424                                   public_data.options)) ? UINT_MAX : 1
1425                                 /* queue priority */ ,
1426                                 (0 !=
1427                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1428                                   public_data.options)) ? UINT_MAX :
1429                                 datastore_queue_size
1430                                 /* max queue size */ ,
1431                                 GNUNET_TIME_UNIT_FOREVER_REL,
1432                                 &process_local_reply, pr);
1433   if (NULL != pr->qe)
1434     return;
1435   GNUNET_STATISTICS_update (GSF_stats,
1436                             gettext_noop
1437                             ("# Datastore lookups concluded (error queueing)"),
1438                             1, GNUNET_NO);
1439   GNUNET_SCHEDULER_cancel (pr->warn_task);
1440   pr->warn_task = GNUNET_SCHEDULER_NO_TASK;
1441   pr->llc_cont = NULL;
1442   if (NULL != cont)
1443     cont (cont_cls, pr, pr->local_result);
1444 }
1445
1446
1447
1448 /**
1449  * Handle P2P "CONTENT" message.  Checks that the message is
1450  * well-formed and then checks if there are any pending requests for
1451  * this content and possibly passes it on (to local clients or other
1452  * peers).  Does NOT perform migration (content caching at this peer).
1453  *
1454  * @param cp the other peer involved (sender or receiver, NULL
1455  *        for loopback messages where we are both sender and receiver)
1456  * @param message the actual message
1457  * @return GNUNET_OK if the message was well-formed,
1458  *         GNUNET_SYSERR if the message was malformed (close connection,
1459  *         do not cache under any circumstances)
1460  */
1461 int
1462 GSF_handle_p2p_content_ (struct GSF_ConnectedPeer *cp,
1463                          const struct GNUNET_MessageHeader *message)
1464 {
1465   const struct PutMessage *put;
1466   uint16_t msize;
1467   size_t dsize;
1468   enum GNUNET_BLOCK_Type type;
1469   struct GNUNET_TIME_Absolute expiration;
1470   GNUNET_HashCode query;
1471   struct ProcessReplyClosure prq;
1472   struct GNUNET_TIME_Relative block_time;
1473   double putl;
1474   struct PutMigrationContext *pmc;
1475
1476   msize = ntohs (message->size);
1477   if (msize < sizeof (struct PutMessage))
1478   {
1479     GNUNET_break_op (0);
1480     return GNUNET_SYSERR;
1481   }
1482   put = (const struct PutMessage *) message;
1483   dsize = msize - sizeof (struct PutMessage);
1484   type = ntohl (put->type);
1485   expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
1486   if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
1487     return GNUNET_SYSERR;
1488   if (GNUNET_OK !=
1489       GNUNET_BLOCK_get_key (GSF_block_ctx, type, &put[1], dsize, &query))
1490   {
1491     GNUNET_break_op (0);
1492     return GNUNET_SYSERR;
1493   }
1494   GNUNET_STATISTICS_update (GSF_stats,
1495                             gettext_noop ("# GAP PUT messages received"), 1,
1496                             GNUNET_NO);
1497   /* now, lookup 'query' */
1498   prq.data = (const void *) &put[1];
1499   if (NULL != cp)
1500     prq.sender = cp;
1501   else
1502     prq.sender = NULL;
1503   prq.size = dsize;
1504   prq.type = type;
1505   prq.expiration = expiration;
1506   prq.priority = 0;
1507   prq.anonymity_level = UINT32_MAX;
1508   prq.request_found = GNUNET_NO;
1509   GNUNET_CONTAINER_multihashmap_get_multiple (pr_map, &query, &process_reply,
1510                                               &prq);
1511   if (NULL != cp)
1512   {
1513     GSF_connected_peer_change_preference_ (cp,
1514                                            CONTENT_BANDWIDTH_VALUE +
1515                                            1000 * prq.priority);
1516     GSF_get_peer_performance_data_ (cp)->trust += prq.priority;
1517   }
1518   if ((GNUNET_YES == active_to_migration) &&
1519       (GNUNET_NO == test_put_load_too_high (prq.priority)))
1520   {
1521 #if DEBUG_FS
1522     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1523                 "Replicating result for query `%s' with priority %u\n",
1524                 GNUNET_h2s (&query), prq.priority);
1525 #endif
1526     pmc = GNUNET_malloc (sizeof (struct PutMigrationContext));
1527     pmc->start = GNUNET_TIME_absolute_get ();
1528     pmc->requested = prq.request_found;
1529     GNUNET_assert (0 != GSF_get_peer_performance_data_ (cp)->pid);
1530     GNUNET_PEER_resolve (GSF_get_peer_performance_data_ (cp)->pid,
1531                          &pmc->origin);
1532     if (NULL ==
1533         GNUNET_DATASTORE_put (GSF_dsh, 0, &query, dsize, &put[1], type,
1534                               prq.priority, 1 /* anonymity */ ,
1535                               0 /* replication */ ,
1536                               expiration, 1 + prq.priority, MAX_DATASTORE_QUEUE,
1537                               GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1538                               &put_migration_continuation, pmc))
1539     {
1540       put_migration_continuation (pmc, GNUNET_NO, NULL);
1541     }
1542   }
1543   else
1544   {
1545 #if DEBUG_FS
1546     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1547                 "Choosing not to keep content `%s' (%d/%d)\n",
1548                 GNUNET_h2s (&query), active_to_migration,
1549                 test_put_load_too_high (prq.priority));
1550 #endif
1551   }
1552   putl = GNUNET_LOAD_get_load (datastore_put_load);
1553   if ((NULL != (cp = prq.sender)) && (GNUNET_NO == prq.request_found) &&
1554       ((GNUNET_YES != active_to_migration) ||
1555        (putl > 2.5 * (1 + prq.priority))))
1556   {
1557     if (GNUNET_YES != active_to_migration)
1558       putl = 1.0 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 5);
1559     block_time =
1560         GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1561                                        5000 +
1562                                        GNUNET_CRYPTO_random_u32
1563                                        (GNUNET_CRYPTO_QUALITY_WEAK,
1564                                         (unsigned int) (60000 * putl * putl)));
1565     GSF_block_peer_migration_ (cp, block_time);
1566   }
1567   return GNUNET_OK;
1568 }
1569
1570
1571 /**
1572  * Setup the subsystem.
1573  */
1574 void
1575 GSF_pending_request_init_ ()
1576 {
1577   unsigned long long bps;
1578
1579   if (GNUNET_OK !=
1580       GNUNET_CONFIGURATION_get_value_number (GSF_cfg, "fs",
1581                                              "MAX_PENDING_REQUESTS",
1582                                              &max_pending_requests))
1583   {
1584     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1585                 _
1586                 ("Configuration fails to specify `%s', assuming default value."),
1587                 "MAX_PENDING_REQUESTS");
1588   }
1589   if (GNUNET_OK !=
1590       GNUNET_CONFIGURATION_get_value_number (GSF_cfg, "core", "TOTAL_QUOTA_OUT",
1591                                              &bps))
1592   {
1593     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1594                 _
1595                 ("Configuration fails to specify `%s', assuming default value."),
1596                 "TOTAL_QUOTA_IN");
1597     bps = 65536;
1598   }
1599   /* queue size should be #queries we can have pending and satisfy within
1600    * a carry interval: */
1601   datastore_queue_size =
1602       bps * GNUNET_CONSTANTS_MAX_BANDWIDTH_CARRY_S / DBLOCK_SIZE;
1603
1604   active_to_migration =
1605       GNUNET_CONFIGURATION_get_value_yesno (GSF_cfg, "FS", "CONTENT_CACHING");
1606   datastore_put_load = GNUNET_LOAD_value_init (DATASTORE_LOAD_AUTODECLINE);
1607   pr_map = GNUNET_CONTAINER_multihashmap_create (32 * 1024);
1608   requests_by_expiration_heap =
1609       GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1610 }
1611
1612
1613 /**
1614  * Shutdown the subsystem.
1615  */
1616 void
1617 GSF_pending_request_done_ ()
1618 {
1619   GNUNET_CONTAINER_multihashmap_iterate (pr_map, &clean_request, NULL);
1620   GNUNET_CONTAINER_multihashmap_destroy (pr_map);
1621   pr_map = NULL;
1622   GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
1623   requests_by_expiration_heap = NULL;
1624   GNUNET_LOAD_value_free (datastore_put_load);
1625   datastore_put_load = NULL;
1626 }
1627
1628
1629 /* end of gnunet-service-fs_pr.c */