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