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