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