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