wip
[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                    GNUNET_BLOCK_EVALUATION_REQUEST_VALID,
342                    dpr,
343                    GNUNET_TIME_UNIT_FOREVER_ABS,
344                    GNUNET_BLOCK_TYPE_ANY,
345                    NULL, 0);
346           GSF_pending_request_cancel_ (dpr);
347         }
348     }
349   return pr;
350 }
351
352
353 /**
354  * Obtain the public data associated with a pending request
355  * 
356  * @param pr pending request
357  * @return associated public data
358  */
359 struct GSF_PendingRequestData *
360 GSF_pending_request_get_data_ (struct GSF_PendingRequest *pr)
361 {
362   return &pr->public_data;
363 }
364
365
366 /**
367  * Update a given pending request with additional replies
368  * that have been seen.
369  *
370  * @param pr request to update
371  * @param replies_seen hash codes of replies that we've seen
372  * @param replies_seen_count size of the replies_seen array
373  */
374 void
375 GSF_pending_request_update_ (struct GSF_PendingRequest *pr,
376                              const GNUNET_HashCode *replies_seen,
377                              unsigned int replies_seen_count)
378 {
379   unsigned int i;
380   GNUNET_HashCode mhash;
381
382   if (replies_seen_count + pr->replies_seen_count < pr->replies_seen_count)
383     return; /* integer overflow */
384   if (0 != (pr->public_data.options & GSF_PRO_BLOOMFILTER_FULL_REFRESH))
385     {
386       /* we're responsible for the BF, full refresh */
387       if (replies_seen_count + pr->replies_seen_count > pr->replies_seen_size)
388         GNUNET_array_grow (pr->replies_seen,
389                            pr->replies_seen_size,
390                            replies_seen_count + pr->replies_seen_count);
391       memcpy (&pr->replies_seen[pr->replies_seen_count],
392               replies_seen,
393               sizeof (GNUNET_HashCode) * replies_seen_count);
394       pr->replies_seen_count += replies_seen_count;
395       if (GNUNET_NO == refresh_bloomfilter (pr))
396         {
397           /* bf not recalculated, simply extend it with new bits */
398           for (i=0;i<pr->replies_seen_count;i++)
399             {
400               GNUNET_BLOCK_mingle_hash (&replies_seen[i],
401                                         pr->mingle,
402                                         &mhash);
403               GNUNET_CONTAINER_bloomfilter_add (pr->bf, &mhash);
404             }
405         }
406     }
407   else
408     {
409       if (NULL == pr->bf)
410         {
411           /* we're not the initiator, but the initiator did not give us
412              any bloom-filter, so we need to create one on-the-fly */
413           pr->mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 
414                                                  UINT32_MAX);
415           pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
416                                                       compute_bloomfilter_size (replies_seen_count),
417                                                       BLOOMFILTER_K);
418         }
419       for (i=0;i<pr->replies_seen_count;i++)
420         {
421           GNUNET_BLOCK_mingle_hash (&replies_seen[i],
422                                     pr->mingle,
423                                     &mhash);
424           GNUNET_CONTAINER_bloomfilter_add (pr->bf, &mhash);
425         }
426     }
427 }
428
429
430 /**
431  * Generate the message corresponding to the given pending request for
432  * transmission to other peers (or at least determine its size).
433  *
434  * @param pr request to generate the message for
435  * @param buf_size number of bytes available in buf
436  * @param buf where to copy the message (can be NULL)
437  * @return number of bytes needed (if > buf_size) or used
438  */
439 size_t
440 GSF_pending_request_get_message_ (struct GSF_PendingRequest *pr,
441                                   size_t buf_size,
442                                   void *buf)
443 {
444   char lbuf[GNUNET_SERVER_MAX_MESSAGE_SIZE];
445   struct GetMessage *gm;
446   GNUNET_HashCode *ext;
447   size_t msize;
448   unsigned int k;
449   uint32_t bm;
450   uint32_t prio;
451   size_t bf_size;
452   struct GNUNET_TIME_Absolute now;
453   int64_t ttl;
454   int do_route;
455
456 #if DEBUG_FS
457   if (buf_size > 0)
458     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
459                 "Building request message for `%s' of type %d\n",
460                 GNUNET_h2s (&pr->public_data.query),
461                 pr->public_data.type);
462 #endif 
463   k = 0;
464   bm = 0;
465   do_route = (0 == (pr->public_data.options & GSF_PRO_FORWARD_ONLY));
466   if (! do_route)
467     {
468       bm |= GET_MESSAGE_BIT_RETURN_TO;
469       k++;      
470     }
471   if (GNUNET_BLOCK_TYPE_FS_SBLOCK == pr->public_data.type)
472     {
473       bm |= GET_MESSAGE_BIT_SKS_NAMESPACE;
474       k++;
475     }
476   if (GNUNET_YES == pr->public_data.has_target)
477     {
478       bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
479       k++;
480     }
481   bf_size = GNUNET_CONTAINER_bloomfilter_get_size (pr->bf);
482   msize = sizeof (struct GetMessage) + bf_size + k * sizeof(GNUNET_HashCode);
483   GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
484   if (buf_size < msize)
485     return msize;  
486   gm = (struct GetMessage*) lbuf;
487   gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
488   gm->header.size = htons (msize);
489   gm->type = htonl (pr->public_data.type);
490   if (do_route)
491     prio = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
492                                      pr->public_data.priority + 1);
493   else
494     prio = 0;
495   pr->public_data.priority -= prio;
496   gm->priority = htonl (prio);
497   now = GNUNET_TIME_absolute_get ();
498   ttl = (int64_t) (pr->public_data.ttl.abs_value - now.abs_value);
499   gm->ttl = htonl (ttl / 1000);
500   gm->filter_mutator = htonl(pr->mingle); 
501   gm->hash_bitmap = htonl (bm);
502   gm->query = pr->public_data.query;
503   ext = (GNUNET_HashCode*) &gm[1];
504   k = 0;  
505   if (! do_route)
506     GNUNET_PEER_resolve (pr->sender_pid, 
507                          (struct GNUNET_PeerIdentity*) &ext[k++]);
508   if (GNUNET_BLOCK_TYPE_FS_SBLOCK == pr->public_data.type)
509     memcpy (&ext[k++], 
510             &pr->public_data.namespace, 
511             sizeof (GNUNET_HashCode));
512   if (GNUNET_YES == pr->public_data.has_target)
513     GNUNET_PEER_resolve (pr->sender_pid, 
514                          (struct GNUNET_PeerIdentity*) &ext[k++]);
515   if (pr->bf != NULL)
516     GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
517                                                (char*) &ext[k],
518                                                bf_size);
519   memcpy (buf, gm, msize);
520   return msize;
521 }
522
523
524 /**
525  * Iterator to free pending requests.
526  *
527  * @param cls closure, unused
528  * @param key current key code
529  * @param value value in the hash map (pending request)
530  * @return GNUNET_YES (we should continue to iterate)
531  */
532 static int 
533 clean_request (void *cls,
534                const GNUNET_HashCode * key,
535                void *value)
536 {
537   struct GSF_PendingRequest *pr = value;
538   
539   GSF_plan_notify_request_done_ (pr);
540   GNUNET_free_non_null (pr->replies_seen);
541   if (NULL != pr->bf)
542     GNUNET_CONTAINER_bloomfilter_free (pr->bf);
543   GNUNET_PEER_change_rc (pr->sender_pid, -1);
544   if (NULL != pr->hnode)
545     GNUNET_CONTAINER_heap_remove_node (pr->hnode);
546   if (NULL != pr->qe)
547     GNUNET_DATASTORE_cancel (pr->qe);
548   if (NULL != pr->gh)
549     GNUNET_DHT_get_stop (pr->gh);
550   GNUNET_free (pr);
551   return GNUNET_YES;
552 }
553
554
555 /**
556  * Explicitly cancel a pending request.
557  *
558  * @param pr request to cancel
559  */
560 void
561 GSF_pending_request_cancel_ (struct GSF_PendingRequest *pr)
562 {
563   GNUNET_assert (GNUNET_OK ==
564                  GNUNET_CONTAINER_multihashmap_remove (pr_map,
565                                                        &pr->public_data.query,
566                                                        pr));
567   GNUNET_assert (GNUNET_YES ==
568                  clean_request (NULL, &pr->public_data.query, pr));  
569 }
570
571
572 /**
573  * Iterate over all pending requests.
574  *
575  * @param it function to call for each request
576  * @param cls closure for it
577  */
578 void
579 GSF_iterate_pending_requests_ (GSF_PendingRequestIterator it,
580                                void *cls)
581 {
582   GNUNET_CONTAINER_multihashmap_iterate (pr_map,
583                                          (GNUNET_CONTAINER_HashMapIterator) it,
584                                          cls);
585 }
586
587
588
589
590 /**
591  * Closure for "process_reply" function.
592  */
593 struct ProcessReplyClosure
594 {
595   /**
596    * The data for the reply.
597    */
598   const void *data;
599
600   /**
601    * Who gave us this reply? NULL for local host (or DHT)
602    */
603   struct GSF_ConnectedPeer *sender;
604
605   /**
606    * When the reply expires.
607    */
608   struct GNUNET_TIME_Absolute expiration;
609
610   /**
611    * Size of data.
612    */
613   size_t size;
614
615   /**
616    * Type of the block.
617    */
618   enum GNUNET_BLOCK_Type type;
619
620   /**
621    * How much was this reply worth to us?
622    */
623   uint32_t priority;
624
625   /**
626    * Anonymity requirements for this reply.
627    */
628   uint32_t anonymity_level;
629
630   /**
631    * Evaluation result (returned).
632    */
633   enum GNUNET_BLOCK_EvaluationResult eval;
634
635   /**
636    * Did we find a matching request?
637    */
638   int request_found;
639 };
640
641
642 /**
643  * Update the performance data for the sender (if any) since
644  * the sender successfully answered one of our queries.
645  *
646  * @param prq information about the sender
647  * @param pr request that was satisfied
648  */
649 static void
650 update_request_performance_data (struct ProcessReplyClosure *prq,
651                                  struct GSF_PendingRequest *pr)
652 {
653   if (prq->sender == NULL)
654     return;      
655   GSF_peer_update_performance_ (prq->sender,
656                                 pr->public_data.start_time,
657                                 prq->priority);
658 }
659                                 
660
661 /**
662  * We have received a reply; handle it!
663  *
664  * @param cls response (struct ProcessReplyClosure)
665  * @param key our query
666  * @param value value in the hash map (info about the query)
667  * @return GNUNET_YES (we should continue to iterate)
668  */
669 static int
670 process_reply (void *cls,
671                const GNUNET_HashCode * key,
672                void *value)
673 {
674   struct ProcessReplyClosure *prq = cls;
675   struct GSF_PendingRequest *pr = value;
676   GNUNET_HashCode chash;
677
678 #if DEBUG_FS
679   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
680               "Matched result (type %u) for query `%s' with pending request\n",
681               (unsigned int) prq->type,
682               GNUNET_h2s (key));
683 #endif  
684   GNUNET_STATISTICS_update (GSF_stats,
685                             gettext_noop ("# replies received and matched"),
686                             1,
687                             GNUNET_NO);
688   prq->eval = GNUNET_BLOCK_evaluate (GSF_block_ctx,
689                                      prq->type,
690                                      key,
691                                      &pr->bf,
692                                      pr->mingle,
693                                      &pr->public_data.namespace, 
694                                      (prq->type == GNUNET_BLOCK_TYPE_FS_SBLOCK) ? sizeof (GNUNET_HashCode) : 0,
695                                      prq->data,
696                                      prq->size);
697   switch (prq->eval)
698     {
699     case GNUNET_BLOCK_EVALUATION_OK_MORE:
700       update_request_performance_data (prq, pr);
701       break;
702     case GNUNET_BLOCK_EVALUATION_OK_LAST:
703       /* short cut: stop processing early, no BF-update, etc. */
704       update_request_performance_data (prq, pr);
705       GNUNET_LOAD_update (GSF_rt_entry_lifetime,
706                           GNUNET_TIME_absolute_get_duration (pr->public_data.start_time).rel_value);
707       /* pass on to other peers / local clients */
708       pr->rh (pr->rh_cls,             
709               prq->eval,
710               pr,
711               prq->expiration,
712               prq->type,
713               prq->data, prq->size);
714       return GNUNET_YES;
715     case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
716       GNUNET_STATISTICS_update (GSF_stats,
717                                 gettext_noop ("# duplicate replies discarded (bloomfilter)"),
718                                 1,
719                                 GNUNET_NO);
720 #if DEBUG_FS && 0
721       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
722                   "Duplicate response `%s', discarding.\n",
723                   GNUNET_h2s (&mhash));
724 #endif
725       return GNUNET_YES; /* duplicate */
726     case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
727       return GNUNET_YES; /* wrong namespace */  
728     case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
729       GNUNET_break (0);
730       return GNUNET_YES;
731     case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
732       GNUNET_break (0);
733       return GNUNET_YES;
734     case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
735       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
736                   _("Unsupported block type %u\n"),
737                   prq->type);
738       return GNUNET_NO;
739     }
740   /* update bloomfilter */
741   GNUNET_CRYPTO_hash (prq->data,
742                       prq->size,
743                       &chash);
744   GSF_pending_request_update_ (pr, &chash, 1);
745   if (NULL == prq->sender)
746     {
747 #if DEBUG_FS
748       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
749                   "Found result for query `%s' in local datastore\n",
750                   GNUNET_h2s (key));
751 #endif
752       GNUNET_STATISTICS_update (GSF_stats,
753                                 gettext_noop ("# results found locally"),
754                                 1,
755                                 GNUNET_NO);      
756     }
757   else
758     {     
759       GSF_dht_lookup_ (pr);
760     }
761   prq->priority += pr->public_data.original_priority;
762   pr->public_data.priority = 0;
763   pr->public_data.original_priority = 0;
764   pr->public_data.results_found++;
765   prq->request_found = GNUNET_YES;
766   /* finally, pass on to other peer / local client */
767   pr->rh (pr->rh_cls,
768           prq->eval,
769           pr, 
770           prq->expiration,
771           prq->type,
772           prq->data, prq->size);
773   return GNUNET_YES;
774 }
775
776
777 /**
778  * Context for the 'put_migration_continuation'.
779  */
780 struct PutMigrationContext
781 {
782
783   /**
784    * Start time for the operation.
785    */
786   struct GNUNET_TIME_Absolute start;
787
788   /**
789    * Request origin.
790    */
791   struct GNUNET_PeerIdentity origin;
792
793   /**
794    * GNUNET_YES if we had a matching request for this block,
795    * GNUNET_NO if not.
796    */
797   int requested;
798 };
799
800
801 /**
802  * Continuation called to notify client about result of the
803  * operation.
804  *
805  * @param cls closure
806  * @param success GNUNET_SYSERR on failure
807  * @param msg NULL on success, otherwise an error message
808  */
809 static void 
810 put_migration_continuation (void *cls,
811                             int success,
812                             const char *msg)
813 {
814   struct PutMigrationContext *pmc = cls;
815   struct GNUNET_TIME_Relative delay;
816   struct GNUNET_TIME_Relative block_time;  
817   struct GSF_ConnectedPeer *cp;
818   struct GSF_PeerPerformanceData *ppd;
819                          
820   delay = GNUNET_TIME_absolute_get_duration (pmc->start);
821   cp = GSF_peer_get_ (&pmc->origin);
822   if ( (GNUNET_OK != success) &&
823        (GNUNET_NO == pmc->requested) )
824     {
825       /* block migration for a bit... */
826       if (NULL != cp)
827         {
828           ppd = GSF_get_peer_performance_data_ (cp);
829           ppd->migration_duplication++;
830           block_time = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
831                                                       5 * ppd->migration_duplication + 
832                                                       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 5));
833           GSF_block_peer_migration_ (cp, block_time);
834         }
835     }
836   else
837     {
838       if (NULL != cp)
839         {
840           ppd = GSF_get_peer_performance_data_ (cp);
841           ppd->migration_duplication = 0; /* reset counter */
842         }
843     }
844   GNUNET_free (pmc);
845   /* FIXME: should we really update the load value on failure? */
846   GNUNET_LOAD_update (datastore_put_load,
847                       delay.rel_value);
848   if (GNUNET_OK == success)
849     return;
850   GNUNET_STATISTICS_update (GSF_stats,
851                             gettext_noop ("# datastore 'put' failures"),
852                             1,
853                             GNUNET_NO);
854 }
855
856
857 /**
858  * Test if the DATABASE (PUT) load on this peer is too high
859  * to even consider processing the query at
860  * all.  
861  * 
862  * @return GNUNET_YES if the load is too high to do anything (load high)
863  *         GNUNET_NO to process normally (load normal or low)
864  */
865 static int
866 test_put_load_too_high (uint32_t priority)
867 {
868   double ld;
869
870   if (GNUNET_LOAD_get_average (datastore_put_load) < 50)
871     return GNUNET_NO; /* very fast */
872   ld = GNUNET_LOAD_get_load (datastore_put_load);
873   if (ld < 2.0 * (1 + priority))
874     return GNUNET_NO;
875   GNUNET_STATISTICS_update (GSF_stats,
876                             gettext_noop ("# storage requests dropped due to high load"),
877                             1,
878                             GNUNET_NO);
879   return GNUNET_YES;
880 }
881
882
883 /**
884  * Iterator called on each result obtained for a DHT
885  * operation that expects a reply
886  *
887  * @param cls closure
888  * @param exp when will this value expire
889  * @param key key of the result
890  * @param get_path NULL-terminated array of pointers
891  *                 to the peers on reverse GET path (or NULL if not recorded)
892  * @param put_path NULL-terminated array of pointers
893  *                 to the peers on the PUT path (or NULL if not recorded)
894  * @param type type of the result
895  * @param size number of bytes in data
896  * @param data pointer to the result data
897  */
898 static void
899 handle_dht_reply (void *cls,
900                   struct GNUNET_TIME_Absolute exp,
901                   const GNUNET_HashCode *key,
902                   const struct GNUNET_PeerIdentity * const *get_path,
903                   const struct GNUNET_PeerIdentity * const *put_path,
904                   enum GNUNET_BLOCK_Type type,
905                   size_t size,
906                   const void *data)
907 {
908   struct GSF_PendingRequest *pr = cls;
909   struct ProcessReplyClosure prq;
910   struct PutMigrationContext *pmc;
911
912   memset (&prq, 0, sizeof (prq));
913   prq.data = data;
914   prq.expiration = exp;
915   prq.size = size;  
916   prq.type = type;
917   process_reply (&prq, key, pr);
918   if ( (GNUNET_YES == active_to_migration) &&
919        (GNUNET_NO == test_put_load_too_high (prq.priority)) )
920     {      
921 #if DEBUG_FS
922       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
923                   "Replicating result for query `%s' with priority %u\n",
924                   GNUNET_h2s (key),
925                   prq.priority);
926 #endif
927       pmc = GNUNET_malloc (sizeof (struct PutMigrationContext));
928       pmc->start = GNUNET_TIME_absolute_get ();
929       pmc->requested = GNUNET_YES;
930       GNUNET_DATASTORE_put (GSF_dsh,
931                             0, key, size, data,
932                             type, prq.priority, 1 /* anonymity */, 
933                             0 /* replication */,
934                             exp, 
935                             1 + prq.priority, MAX_DATASTORE_QUEUE,
936                             GNUNET_CONSTANTS_SERVICE_TIMEOUT,
937                             &put_migration_continuation, 
938                             pmc);
939     }
940 }
941
942
943 /**
944  * Consider looking up the data in the DHT (anonymity-level permitting).
945  *
946  * @param pr the pending request to process
947  */
948 void
949 GSF_dht_lookup_ (struct GSF_PendingRequest *pr)
950 {
951   const void *xquery;
952   size_t xquery_size;
953   struct GNUNET_PeerIdentity pi;
954   char buf[sizeof (GNUNET_HashCode) * 2];
955
956   if (0 != pr->public_data.anonymity_level)
957     return;
958   if (NULL != pr->gh)
959     {
960       GNUNET_DHT_get_stop (pr->gh);
961       pr->gh = NULL;
962     }
963   xquery = NULL;
964   xquery_size = 0;
965   if (GNUNET_BLOCK_TYPE_FS_SBLOCK == pr->public_data.type)
966     {
967       xquery = buf;
968       memcpy (buf, &pr->public_data.namespace, sizeof (GNUNET_HashCode));
969       xquery_size = sizeof (GNUNET_HashCode);
970     }
971   if (0 != (pr->public_data.options & GSF_PRO_FORWARD_ONLY))
972     {
973       GNUNET_PEER_resolve (pr->sender_pid,
974                            &pi);
975       memcpy (&buf[xquery_size], &pi, sizeof (struct GNUNET_PeerIdentity));
976       xquery_size += sizeof (struct GNUNET_PeerIdentity);
977     }
978   pr->gh = GNUNET_DHT_get_start (GSF_dht,
979                                  GNUNET_TIME_UNIT_FOREVER_REL,
980                                  pr->public_data.type,
981                                  &pr->public_data.query,
982                                  DEFAULT_GET_REPLICATION,
983                                  GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
984                                  pr->bf,
985                                  pr->mingle,
986                                  xquery,
987                                  xquery_size,
988                                  &handle_dht_reply,
989                                  pr);
990 }
991
992 /**
993  * We're processing (local) results for a search request
994  * from another peer.  Pass applicable results to the
995  * peer and if we are done either clean up (operation
996  * complete) or forward to other peers (more results possible).
997  *
998  * @param cls our closure (struct PendingRequest)
999  * @param key key for the content
1000  * @param size number of bytes in data
1001  * @param data content stored
1002  * @param type type of the content
1003  * @param priority priority of the content
1004  * @param anonymity anonymity-level for the content
1005  * @param expiration expiration time for the content
1006  * @param uid unique identifier for the datum;
1007  *        maybe 0 if no unique identifier is available
1008  */
1009 static void
1010 process_local_reply (void *cls,
1011                      const GNUNET_HashCode *key,
1012                      size_t size,
1013                      const void *data,
1014                      enum GNUNET_BLOCK_Type type,
1015                      uint32_t priority,
1016                      uint32_t anonymity,
1017                      struct GNUNET_TIME_Absolute expiration, 
1018                      uint64_t uid)
1019 {
1020   struct GSF_PendingRequest *pr = cls;
1021   GSF_LocalLookupContinuation cont;
1022   struct ProcessReplyClosure prq;
1023   GNUNET_HashCode query;
1024   unsigned int old_rf;
1025   
1026   if (NULL == key)
1027     {
1028 #if DEBUG_FS
1029       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1030                   "No further local responses available.\n");
1031 #endif
1032       pr->qe = NULL;
1033       if (NULL != (cont = pr->llc_cont))
1034         {
1035           pr->llc_cont = NULL;
1036           cont (pr->llc_cont_cls,
1037                 pr,
1038                 pr->local_result);
1039         }
1040       return;
1041     }
1042 #if DEBUG_FS
1043   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1044               "New local response to `%s' of type %u.\n",
1045               GNUNET_h2s (key),
1046               type);
1047 #endif
1048   if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
1049     {
1050 #if DEBUG_FS
1051       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1052                   "Found ONDEMAND block, performing on-demand encoding\n");
1053 #endif
1054       GNUNET_STATISTICS_update (GSF_stats,
1055                                 gettext_noop ("# on-demand blocks matched requests"),
1056                                 1,
1057                                 GNUNET_NO);
1058       if (GNUNET_OK != 
1059           GNUNET_FS_handle_on_demand_block (key, size, data, type, priority, 
1060                                             anonymity, expiration, uid, 
1061                                             &process_local_reply,
1062                                             pr))
1063         {
1064           if (pr->qe != NULL)
1065             GNUNET_DATASTORE_iterate_get_next (GSF_dsh);
1066         }
1067       return;
1068     }
1069   old_rf = pr->public_data.results_found;
1070   memset (&prq, 0, sizeof (prq));
1071   prq.data = data;
1072   prq.expiration = expiration;
1073   prq.size = size;  
1074   if (GNUNET_OK != 
1075       GNUNET_BLOCK_get_key (GSF_block_ctx,
1076                             type,
1077                             data,
1078                             size,
1079                             &query))
1080     {
1081       GNUNET_break (0);
1082       GNUNET_DATASTORE_remove (GSF_dsh,
1083                                key,
1084                                size, data,
1085                                -1, -1, 
1086                                GNUNET_TIME_UNIT_FOREVER_REL,
1087                                NULL, NULL);
1088       GNUNET_DATASTORE_iterate_get_next (GSF_dsh);
1089       return;
1090     }
1091   prq.type = type;
1092   prq.priority = priority;  
1093   prq.request_found = GNUNET_NO;
1094   prq.anonymity_level = anonymity;
1095   if ( (old_rf == 0) &&
1096        (pr->public_data.results_found == 0) )
1097     GSF_update_datastore_delay_ (pr->public_data.start_time);
1098   process_reply (&prq, key, pr);
1099   pr->local_result = prq.eval;
1100   if (pr->qe == NULL)
1101     {
1102 #if DEBUG_FS
1103       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1104                   "Request cancelled, not asking datastore for more\n");
1105 #endif
1106     }
1107   if ( (0 == (GSF_PRO_PRIORITY_UNLIMITED & pr->public_data.options)) &&
1108        ( (GNUNET_YES == GSF_test_get_load_too_high_ (0)) ||
1109          (pr->public_data.results_found > 5 + 2 * pr->public_data.priority) ) )
1110     {
1111 #if DEBUG_FS > 2
1112       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1113                   "Load too high, done with request\n");
1114 #endif
1115       GNUNET_STATISTICS_update (GSF_stats,
1116                                 gettext_noop ("# processing result set cut short due to load"),
1117                                 1,
1118                                 GNUNET_NO);
1119       GNUNET_DATASTORE_cancel (pr->qe);
1120       pr->qe = NULL;
1121       if (NULL != (cont = pr->llc_cont))
1122         {
1123           pr->llc_cont = NULL;
1124           cont (pr->llc_cont_cls,
1125                 pr,
1126                 pr->local_result);
1127         }
1128       return;
1129     }
1130   GNUNET_DATASTORE_iterate_get_next (GSF_dsh);
1131 }
1132
1133
1134 /**
1135  * Look up the request in the local datastore.
1136  *
1137  * @param pr the pending request to process
1138  * @param cont function to call at the end
1139  * @param cont_cls closure for cont
1140  */
1141 void
1142 GSF_local_lookup_ (struct GSF_PendingRequest *pr,
1143                    GSF_LocalLookupContinuation cont,
1144                    void *cont_cls)
1145 {
1146   GNUNET_assert (NULL == pr->gh);
1147   GNUNET_assert (NULL == pr->llc_cont);
1148   pr->llc_cont = cont;
1149   pr->llc_cont_cls = cont_cls;
1150   pr->qe = GNUNET_DATASTORE_iterate_key (GSF_dsh,
1151                                          &pr->public_data.query,
1152                                          pr->public_data.type == GNUNET_BLOCK_TYPE_FS_DBLOCK 
1153                                          ? GNUNET_BLOCK_TYPE_ANY 
1154                                          : pr->public_data.type, 
1155                                          (0 != (GSF_PRO_PRIORITY_UNLIMITED & pr->public_data.options))
1156                                          ? UINT_MAX
1157                                          : 1 /* queue priority */,
1158                                          (0 != (GSF_PRO_PRIORITY_UNLIMITED & pr->public_data.options))
1159                                          ? UINT_MAX
1160                                          : 1 /* max queue size */,
1161                                          GNUNET_TIME_UNIT_FOREVER_REL,
1162                                          &process_local_reply,
1163                                          pr);
1164 }
1165
1166
1167
1168 /**
1169  * Handle P2P "CONTENT" message.  Checks that the message is
1170  * well-formed and then checks if there are any pending requests for
1171  * this content and possibly passes it on (to local clients or other
1172  * peers).  Does NOT perform migration (content caching at this peer).
1173  *
1174  * @param cp the other peer involved (sender or receiver, NULL
1175  *        for loopback messages where we are both sender and receiver)
1176  * @param message the actual message
1177  * @return GNUNET_OK if the message was well-formed,
1178  *         GNUNET_SYSERR if the message was malformed (close connection,
1179  *         do not cache under any circumstances)
1180  */
1181 int
1182 GSF_handle_p2p_content_ (struct GSF_ConnectedPeer *cp,
1183                          const struct GNUNET_MessageHeader *message)
1184 {
1185   const struct PutMessage *put;
1186   uint16_t msize;
1187   size_t dsize;
1188   enum GNUNET_BLOCK_Type type;
1189   struct GNUNET_TIME_Absolute expiration;
1190   GNUNET_HashCode query;
1191   struct ProcessReplyClosure prq;
1192   struct GNUNET_TIME_Relative block_time;  
1193   double putl;
1194   struct PutMigrationContext *pmc;
1195
1196   msize = ntohs (message->size);
1197   if (msize < sizeof (struct PutMessage))
1198     {
1199       GNUNET_break_op(0);
1200       return GNUNET_SYSERR;
1201     }
1202   put = (const struct PutMessage*) message;
1203   dsize = msize - sizeof (struct PutMessage);
1204   type = ntohl (put->type);
1205   expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
1206   if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
1207     return GNUNET_SYSERR;
1208   if (GNUNET_OK !=
1209       GNUNET_BLOCK_get_key (GSF_block_ctx,
1210                             type,
1211                             &put[1],
1212                             dsize,
1213                             &query))
1214     {
1215       GNUNET_break_op (0);
1216       return GNUNET_SYSERR;
1217     }
1218   /* now, lookup 'query' */
1219   prq.data = (const void*) &put[1];
1220   if (NULL != cp)
1221     prq.sender = cp;
1222   else
1223     prq.sender = NULL;
1224   prq.size = dsize;
1225   prq.type = type;
1226   prq.expiration = expiration;
1227   prq.priority = 0;
1228   prq.anonymity_level = 1;
1229   prq.request_found = GNUNET_NO;
1230   GNUNET_CONTAINER_multihashmap_get_multiple (pr_map,
1231                                               &query,
1232                                               &process_reply,
1233                                               &prq);
1234   if (NULL != cp)
1235     {
1236       GSF_connected_peer_change_preference_ (cp, CONTENT_BANDWIDTH_VALUE + 1000 * prq.priority);
1237       GSF_get_peer_performance_data_ (cp)->trust += prq.priority;
1238     }
1239   if ( (GNUNET_YES == active_to_migration) &&
1240        (GNUNET_NO == test_put_load_too_high (prq.priority)) )
1241     {      
1242 #if DEBUG_FS
1243       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1244                   "Replicating result for query `%s' with priority %u\n",
1245                   GNUNET_h2s (&query),
1246                   prq.priority);
1247 #endif
1248       pmc = GNUNET_malloc (sizeof (struct PutMigrationContext));
1249       pmc->start = GNUNET_TIME_absolute_get ();
1250       pmc->requested = prq.request_found;
1251       GNUNET_PEER_resolve (GSF_get_peer_performance_data_ (cp)->pid,
1252                            &pmc->origin);
1253       GNUNET_DATASTORE_put (GSF_dsh,
1254                             0, &query, dsize, &put[1],
1255                             type, prq.priority, 1 /* anonymity */, 
1256                             0 /* replication */,
1257                             expiration, 
1258                             1 + prq.priority, MAX_DATASTORE_QUEUE,
1259                             GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1260                             &put_migration_continuation, 
1261                             pmc);
1262     }
1263   else
1264     {
1265 #if DEBUG_FS
1266       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1267                   "Choosing not to keep content `%s' (%d/%d)\n",
1268                   GNUNET_h2s (&query),
1269                   active_to_migration,
1270                   test_put_load_too_high (prq.priority));
1271 #endif
1272     }
1273   putl = GNUNET_LOAD_get_load (datastore_put_load);
1274   if ( (NULL != (cp = prq.sender)) &&
1275        (GNUNET_NO == prq.request_found) &&
1276        ( (GNUNET_YES != active_to_migration) ||
1277          (putl > 2.5 * (1 + prq.priority)) ) ) 
1278     {
1279       if (GNUNET_YES != active_to_migration) 
1280         putl = 1.0 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 5);
1281       block_time = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1282                                                   5000 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1283                                                                                    (unsigned int) (60000 * putl * putl)));
1284       GSF_block_peer_migration_ (cp, block_time);
1285     }  
1286   return GNUNET_OK;
1287 }
1288
1289
1290 /**
1291  * Setup the subsystem.
1292  */
1293 void
1294 GSF_pending_request_init_ ()
1295 {
1296   if (GNUNET_OK !=
1297       GNUNET_CONFIGURATION_get_value_number (GSF_cfg,
1298                                              "fs",
1299                                              "MAX_PENDING_REQUESTS",
1300                                              &max_pending_requests))
1301     {
1302       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1303                   _("Configuration fails to specify `%s', assuming default value."),
1304                   "MAX_PENDING_REQUESTS");
1305     }
1306   active_to_migration = GNUNET_CONFIGURATION_get_value_yesno (GSF_cfg,
1307                                                               "FS",
1308                                                               "CONTENT_CACHING");
1309   datastore_put_load = GNUNET_LOAD_value_init (DATASTORE_LOAD_AUTODECLINE);
1310   pr_map = GNUNET_CONTAINER_multihashmap_create (32 * 1024);
1311   requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN); 
1312 }
1313
1314
1315 /**
1316  * Shutdown the subsystem.
1317  */
1318 void
1319 GSF_pending_request_done_ ()
1320 {
1321   GNUNET_CONTAINER_multihashmap_iterate (pr_map,
1322                                          &clean_request,
1323                                          NULL);
1324   GNUNET_CONTAINER_multihashmap_destroy (pr_map);
1325   pr_map = NULL;
1326   GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
1327   requests_by_expiration_heap = NULL;
1328   GNUNET_LOAD_value_free (datastore_put_load);
1329   datastore_put_load = NULL;
1330 }
1331
1332
1333 /* end of gnunet-service-fs_pr.c */