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