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