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