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