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