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