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