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