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