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