- FIX: GNUNET_SET_STATUS_HALF_DONE is never called only GNUNET_SET_STATUS_DONE
[oweals/gnunet.git] / src / fs / gnunet-service-fs_pr.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009-2013 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_util_lib.h"
28 #include "gnunet_load_lib.h"
29 #include "gnunet-service-fs.h"
30 #include "gnunet-service-fs_cp.h"
31 #include "gnunet-service-fs_indexing.h"
32 #include "gnunet-service-fs_pe.h"
33 #include "gnunet-service-fs_pr.h"
34 #include "gnunet-service-fs_mesh.h"
35
36
37 /**
38  * Desired replication level for GETs.
39  */
40 #define DHT_GET_REPLICATION 5
41
42 /**
43  * Maximum size of the datastore queue for P2P operations.  Needs to
44  * be large enough to queue MAX_QUEUE_PER_PEER operations for roughly
45  * the number of active (connected) peers.
46  */
47 #define MAX_DATASTORE_QUEUE (16 * MAX_QUEUE_PER_PEER)
48
49 /**
50  * Bandwidth value of a 0-priority content (must be fairly high
51  * compared to query since content is typically significantly larger
52  * -- and more valueable since it can take many queries to get one
53  * piece of content).
54  */
55 #define CONTENT_BANDWIDTH_VALUE 800
56
57 /**
58  * Hard limit on the number of results we may get from the datastore per query.
59  */
60 #define MAX_RESULTS (100 * 1024)
61
62 /**
63  * Collect an instane number of statistics?  May cause excessive IPC.
64  */
65 #define INSANE_STATISTICS GNUNET_NO
66
67 /**
68  * If obtaining a block via mesh fails, how often do we retry it before
69  * giving up for good (and sticking to non-anonymous transfer)?
70  */
71 #define MESH_RETRY_MAX 3
72
73
74 /**
75  * An active request.
76  */
77 struct GSF_PendingRequest
78 {
79   /**
80    * Public data for the request.
81    */
82   struct GSF_PendingRequestData public_data;
83
84   /**
85    * Function to call if we encounter a reply.
86    */
87   GSF_PendingRequestReplyHandler rh;
88
89   /**
90    * Closure for @e rh
91    */
92   void *rh_cls;
93
94   /**
95    * Array of hash codes of replies we've already seen.
96    */
97   struct GNUNET_HashCode *replies_seen;
98
99   /**
100    * Bloomfilter masking replies we've already seen.
101    */
102   struct GNUNET_CONTAINER_BloomFilter *bf;
103
104   /**
105    * Entry for this pending request in the expiration heap, or NULL.
106    */
107   struct GNUNET_CONTAINER_HeapNode *hnode;
108
109   /**
110    * Datastore queue entry for this request (or NULL for none).
111    */
112   struct GNUNET_DATASTORE_QueueEntry *qe;
113
114   /**
115    * DHT request handle for this request (or NULL for none).
116    */
117   struct GNUNET_DHT_GetHandle *gh;
118
119   /**
120    * Mesh request handle for this request (or NULL for none).
121    */
122   struct GSF_MeshRequest *mesh_request;
123
124   /**
125    * Function to call upon completion of the local get
126    * request, or NULL for none.
127    */
128   GSF_LocalLookupContinuation llc_cont;
129
130   /**
131    * Closure for llc_cont.
132    */
133   void *llc_cont_cls;
134
135   /**
136    * Last result from the local datastore lookup evaluation.
137    */
138   enum GNUNET_BLOCK_EvaluationResult local_result;
139
140   /**
141    * Identity of the peer that we should use for the 'sender'
142    * (recipient of the response) when forwarding (0 for none).
143    */
144   GNUNET_PEER_Id sender_pid;
145
146   /**
147    * Identity of the peer that we should never forward this query
148    * to since it originated this query (0 for none).
149    */
150   GNUNET_PEER_Id origin_pid;
151
152   /**
153    * Time we started the last datastore lookup.
154    */
155   struct GNUNET_TIME_Absolute qe_start;
156
157   /**
158    * Task that warns us if the local datastore lookup takes too long.
159    */
160   GNUNET_SCHEDULER_TaskIdentifier warn_task;
161
162   /**
163    * Current offset for querying our local datastore for results.
164    * Starts at a random value, incremented until we get the same
165    * UID again (detected using 'first_uid'), which is then used
166    * to termiante the iteration.
167    */
168   uint64_t local_result_offset;
169
170   /**
171    * Unique ID of the first result from the local datastore;
172    * used to detect wrap-around of the offset.
173    */
174   uint64_t first_uid;
175
176   /**
177    * How often have we retried this request via 'mesh'?
178    * (used to bound overall retries).
179    */
180   unsigned int mesh_retry_count;
181
182   /**
183    * Number of valid entries in the 'replies_seen' array.
184    */
185   unsigned int replies_seen_count;
186
187   /**
188    * Length of the 'replies_seen' array.
189    */
190   unsigned int replies_seen_size;
191
192   /**
193    * Mingle value we currently use for the bf.
194    */
195   uint32_t mingle;
196
197   /**
198    * Do we have a first UID yet?
199    */
200   unsigned int have_first_uid;
201
202 };
203
204
205 /**
206  * All pending requests, ordered by the query.  Entries
207  * are of type 'struct GSF_PendingRequest*'.
208  */
209 static struct GNUNET_CONTAINER_MultiHashMap *pr_map;
210
211
212 /**
213  * Datastore 'PUT' load tracking.
214  */
215 static struct GNUNET_LOAD_Value *datastore_put_load;
216
217
218 /**
219  * Are we allowed to migrate content to this peer.
220  */
221 static int active_to_migration;
222
223
224 /**
225  * Heap with the request that will expire next at the top.  Contains
226  * pointers of type "struct PendingRequest*"; these will *also* be
227  * aliased from the "requests_by_peer" data structures and the
228  * "requests_by_query" table.  Note that requests from our clients
229  * don't expire and are thus NOT in the "requests_by_expiration"
230  * (or the "requests_by_peer" tables).
231  */
232 static struct GNUNET_CONTAINER_Heap *requests_by_expiration_heap;
233
234
235 /**
236  * Maximum number of requests (from other peers, overall) that we're
237  * willing to have pending at any given point in time.  Can be changed
238  * via the configuration file (32k is just the default).
239  */
240 static unsigned long long max_pending_requests = (32 * 1024);
241
242
243
244 /**
245  * Recalculate our bloom filter for filtering replies.  This function
246  * will create a new bloom filter from scratch, so it should only be
247  * called if we have no bloomfilter at all (and hence can create a
248  * fresh one of minimal size without problems) OR if our peer is the
249  * initiator (in which case we may resize to larger than mimimum size).
250  *
251  * @param pr request for which the BF is to be recomputed
252  */
253 static void
254 refresh_bloomfilter (struct GSF_PendingRequest *pr)
255 {
256   if (pr->bf != NULL)
257     GNUNET_CONTAINER_bloomfilter_free (pr->bf);
258   pr->mingle =
259       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
260   pr->bf =
261       GNUNET_BLOCK_construct_bloomfilter (pr->mingle, pr->replies_seen,
262                                           pr->replies_seen_count);
263 }
264
265
266 /**
267  * Create a new pending request.
268  *
269  * @param options request options
270  * @param type type of the block that is being requested
271  * @param query key for the lookup
272  * @param target preferred target for the request, NULL for none
273  * @param bf_data raw data for bloom filter for known replies, can be NULL
274  * @param bf_size number of bytes in @a bf_data
275  * @param mingle mingle value for bf
276  * @param anonymity_level desired anonymity level
277  * @param priority maximum outgoing cummulative request priority to use
278  * @param ttl current time-to-live for the request
279  * @param sender_pid peer ID to use for the sender when forwarding, 0 for none
280  * @param origin_pid peer ID of origin of query (do not loop back)
281  * @param replies_seen hash codes of known local replies
282  * @param replies_seen_count size of the @a replies_seen array
283  * @param rh handle to call when we get a reply
284  * @param rh_cls closure for @a rh
285  * @return handle for the new pending request
286  */
287 struct GSF_PendingRequest *
288 GSF_pending_request_create_ (enum GSF_PendingRequestOptions options,
289                              enum GNUNET_BLOCK_Type type,
290                              const struct GNUNET_HashCode *query,
291                              const struct GNUNET_PeerIdentity *target,
292                              const char *bf_data, size_t bf_size,
293                              uint32_t mingle, uint32_t anonymity_level,
294                              uint32_t priority, int32_t ttl,
295                              GNUNET_PEER_Id sender_pid,
296                              GNUNET_PEER_Id origin_pid,
297                              const struct GNUNET_HashCode *replies_seen,
298                              unsigned int replies_seen_count,
299                              GSF_PendingRequestReplyHandler rh, void *rh_cls)
300 {
301   struct GSF_PendingRequest *pr;
302   struct GSF_PendingRequest *dpr;
303   size_t extra;
304   struct GNUNET_HashCode *eptr;
305
306   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
307               "Creating request handle for `%s' of type %d\n",
308               GNUNET_h2s (query), type);
309 #if INSANE_STATISTICS
310   GNUNET_STATISTICS_update (GSF_stats,
311                             gettext_noop ("# Pending requests created"), 1,
312                             GNUNET_NO);
313 #endif
314   extra = 0;
315   if (NULL != target)
316     extra += sizeof (struct GNUNET_PeerIdentity);
317   pr = GNUNET_malloc (sizeof (struct GSF_PendingRequest) + extra);
318   pr->local_result_offset =
319       GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
320   pr->public_data.query = *query;
321   eptr = (struct GNUNET_HashCode *) &pr[1];
322   if (NULL != target)
323   {
324     pr->public_data.target = (struct GNUNET_PeerIdentity *) eptr;
325     memcpy (eptr, target, sizeof (struct GNUNET_PeerIdentity));
326   }
327   pr->public_data.anonymity_level = anonymity_level;
328   pr->public_data.priority = priority;
329   pr->public_data.original_priority = priority;
330   pr->public_data.options = options;
331   pr->public_data.type = type;
332   pr->public_data.start_time = GNUNET_TIME_absolute_get ();
333   pr->sender_pid = sender_pid;
334   pr->origin_pid = origin_pid;
335   pr->rh = rh;
336   pr->rh_cls = rh_cls;
337   GNUNET_assert ((sender_pid != 0) || (0 == (options & GSF_PRO_FORWARD_ONLY)));
338   if (ttl >= 0)
339     pr->public_data.ttl =
340         GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_multiply
341                                           (GNUNET_TIME_UNIT_SECONDS,
342                                            (uint32_t) ttl));
343   else
344     pr->public_data.ttl =
345         GNUNET_TIME_absolute_subtract (pr->public_data.start_time,
346                                        GNUNET_TIME_relative_multiply
347                                        (GNUNET_TIME_UNIT_SECONDS,
348                                         (uint32_t) (-ttl)));
349   if (replies_seen_count > 0)
350   {
351     pr->replies_seen_size = replies_seen_count;
352     pr->replies_seen =
353         GNUNET_malloc (sizeof (struct GNUNET_HashCode) * pr->replies_seen_size);
354     memcpy (pr->replies_seen, replies_seen,
355             replies_seen_count * sizeof (struct GNUNET_HashCode));
356     pr->replies_seen_count = replies_seen_count;
357   }
358   if (NULL != bf_data)
359   {
360     pr->bf =
361         GNUNET_CONTAINER_bloomfilter_init (bf_data, bf_size,
362                                            GNUNET_CONSTANTS_BLOOMFILTER_K);
363     pr->mingle = mingle;
364   }
365   else if ((replies_seen_count > 0) &&
366            (0 != (options & GSF_PRO_BLOOMFILTER_FULL_REFRESH)))
367   {
368     refresh_bloomfilter (pr);
369   }
370   GNUNET_CONTAINER_multihashmap_put (pr_map,
371                                      &pr->public_data.query, pr,
372                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
373   if (0 == (options & GSF_PRO_REQUEST_NEVER_EXPIRES))
374   {
375     pr->hnode =
376         GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap, pr,
377                                       pr->public_data.ttl.abs_value_us);
378     /* make sure we don't track too many requests */
379     while (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) >
380            max_pending_requests)
381     {
382       dpr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
383       GNUNET_assert (dpr != NULL);
384       if (pr == dpr)
385         break;                  /* let the request live briefly... */
386       if (NULL != dpr->rh)
387         dpr->rh (dpr->rh_cls, GNUNET_BLOCK_EVALUATION_REQUEST_VALID, dpr,
388                  UINT32_MAX, GNUNET_TIME_UNIT_FOREVER_ABS, GNUNET_TIME_UNIT_FOREVER_ABS,
389                  GNUNET_BLOCK_TYPE_ANY, NULL, 0);
390       GSF_pending_request_cancel_ (dpr, GNUNET_YES);
391     }
392   }
393   GNUNET_STATISTICS_update (GSF_stats,
394                             gettext_noop ("# Pending requests active"), 1,
395                             GNUNET_NO);
396   return pr;
397 }
398
399 /**
400  * Obtain the public data associated with a pending request
401  *
402  * @param pr pending request
403  * @return associated public data
404  */
405 struct GSF_PendingRequestData *
406 GSF_pending_request_get_data_ (struct GSF_PendingRequest *pr)
407 {
408   return &pr->public_data;
409 }
410
411
412 /**
413  * Test if two pending requests are compatible (would generate
414  * the same query modulo filters and should thus be processed
415  * jointly).
416  *
417  * @param pra a pending request
418  * @param prb another pending request
419  * @return #GNUNET_OK if the requests are compatible
420  */
421 int
422 GSF_pending_request_is_compatible_ (struct GSF_PendingRequest *pra,
423                                     struct GSF_PendingRequest *prb)
424 {
425   if ((pra->public_data.type != prb->public_data.type) ||
426       (0 !=
427        memcmp (&pra->public_data.query, &prb->public_data.query,
428                sizeof (struct GNUNET_HashCode))))
429     return GNUNET_NO;
430   return GNUNET_OK;
431 }
432
433
434
435 /**
436  * Update a given pending request with additional replies
437  * that have been seen.
438  *
439  * @param pr request to update
440  * @param replies_seen hash codes of replies that we've seen
441  * @param replies_seen_count size of the replies_seen array
442  */
443 void
444 GSF_pending_request_update_ (struct GSF_PendingRequest *pr,
445                              const struct GNUNET_HashCode * replies_seen,
446                              unsigned int replies_seen_count)
447 {
448   unsigned int i;
449   struct GNUNET_HashCode mhash;
450
451   if (replies_seen_count + pr->replies_seen_count < pr->replies_seen_count)
452     return;                     /* integer overflow */
453   if (0 != (pr->public_data.options & GSF_PRO_BLOOMFILTER_FULL_REFRESH))
454   {
455     /* we're responsible for the BF, full refresh */
456     if (replies_seen_count + pr->replies_seen_count > pr->replies_seen_size)
457       GNUNET_array_grow (pr->replies_seen, pr->replies_seen_size,
458                          replies_seen_count + pr->replies_seen_count);
459     memcpy (&pr->replies_seen[pr->replies_seen_count], replies_seen,
460             sizeof (struct GNUNET_HashCode) * replies_seen_count);
461     pr->replies_seen_count += replies_seen_count;
462     refresh_bloomfilter (pr);
463   }
464   else
465   {
466     if (NULL == pr->bf)
467     {
468       /* we're not the initiator, but the initiator did not give us
469        * any bloom-filter, so we need to create one on-the-fly */
470       pr->mingle =
471           GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
472       pr->bf =
473           GNUNET_BLOCK_construct_bloomfilter (pr->mingle, replies_seen,
474                                               replies_seen_count);
475     }
476     else
477     {
478       for (i = 0; i < pr->replies_seen_count; i++)
479       {
480         GNUNET_BLOCK_mingle_hash (&replies_seen[i], pr->mingle, &mhash);
481         GNUNET_CONTAINER_bloomfilter_add (pr->bf, &mhash);
482       }
483     }
484   }
485   if (NULL != pr->gh)
486     GNUNET_DHT_get_filter_known_results (pr->gh,
487                                          replies_seen_count,
488                                          replies_seen);
489 }
490
491
492 /**
493  * Generate the message corresponding to the given pending request for
494  * transmission to other peers (or at least determine its size).
495  *
496  * @param pr request to generate the message for
497  * @param buf_size number of bytes available in @a buf
498  * @param buf where to copy the message (can be NULL)
499  * @return number of bytes needed (if `>` @a buf_size) or used
500  */
501 size_t
502 GSF_pending_request_get_message_ (struct GSF_PendingRequest *pr,
503                                   size_t buf_size, void *buf)
504 {
505   char lbuf[GNUNET_SERVER_MAX_MESSAGE_SIZE];
506   struct GetMessage *gm;
507   struct GNUNET_HashCode *ext;
508   size_t msize;
509   unsigned int k;
510   uint32_t bm;
511   uint32_t prio;
512   size_t bf_size;
513   struct GNUNET_TIME_Absolute now;
514   int64_t ttl;
515   int do_route;
516
517   if (buf_size > 0)
518     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
519                 "Building request message for `%s' of type %d\n",
520                 GNUNET_h2s (&pr->public_data.query), pr->public_data.type);
521   k = 0;
522   bm = 0;
523   do_route = (0 == (pr->public_data.options & GSF_PRO_FORWARD_ONLY));
524   if ((!do_route) && (pr->sender_pid == 0))
525   {
526     GNUNET_break (0);
527     do_route = GNUNET_YES;
528   }
529   if (!do_route)
530   {
531     bm |= GET_MESSAGE_BIT_RETURN_TO;
532     k++;
533   }
534   if (NULL != pr->public_data.target)
535   {
536     bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
537     k++;
538   }
539   bf_size = GNUNET_CONTAINER_bloomfilter_get_size (pr->bf);
540   msize = sizeof (struct GetMessage) + bf_size + k * sizeof (struct GNUNET_HashCode);
541   GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
542   if (buf_size < msize)
543     return msize;
544   gm = (struct GetMessage *) lbuf;
545   gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
546   gm->header.size = htons (msize);
547   gm->type = htonl (pr->public_data.type);
548   if (do_route)
549     prio =
550         GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
551                                   pr->public_data.priority + 1);
552   else
553     prio = 0;
554   pr->public_data.priority -= prio;
555   pr->public_data.num_transmissions++;
556   pr->public_data.respect_offered += prio;
557   gm->priority = htonl (prio);
558   now = GNUNET_TIME_absolute_get ();
559   ttl = (int64_t) (pr->public_data.ttl.abs_value_us - now.abs_value_us);
560   gm->ttl = htonl (ttl / 1000LL / 1000LL);
561   gm->filter_mutator = htonl (pr->mingle);
562   gm->hash_bitmap = htonl (bm);
563   gm->query = pr->public_data.query;
564   ext = (struct GNUNET_HashCode *) & gm[1];
565   k = 0;
566   if (!do_route)
567     GNUNET_PEER_resolve (pr->sender_pid,
568                          (struct GNUNET_PeerIdentity *) &ext[k++]);
569   if (NULL != pr->public_data.target)
570     memcpy (&ext[k++],
571             pr->public_data.target,
572             sizeof (struct GNUNET_PeerIdentity));
573   if (pr->bf != NULL)
574     GNUNET_assert (GNUNET_SYSERR !=
575                    GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
576                                                               (char *) &ext[k],
577                                                               bf_size));
578   memcpy (buf, gm, msize);
579   return msize;
580 }
581
582
583 /**
584  * Iterator to free pending requests.
585  *
586  * @param cls closure, unused
587  * @param key current key code
588  * @param value value in the hash map (pending request)
589  * @return #GNUNET_YES (we should continue to iterate)
590  */
591 static int
592 clean_request (void *cls, const struct GNUNET_HashCode * key, void *value)
593 {
594   struct GSF_PendingRequest *pr = value;
595   GSF_LocalLookupContinuation cont;
596
597   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
598               "Cleaning up pending request for `%s'.\n", GNUNET_h2s (key));
599   if (NULL != (cont = pr->llc_cont))
600   {
601     pr->llc_cont = NULL;
602     cont (pr->llc_cont_cls, pr, pr->local_result);
603   }
604   GSF_plan_notify_request_done_ (pr);
605   GNUNET_free_non_null (pr->replies_seen);
606   if (NULL != pr->bf)
607   {
608     GNUNET_CONTAINER_bloomfilter_free (pr->bf);
609     pr->bf = NULL;
610   }
611   GNUNET_PEER_change_rc (pr->sender_pid, -1);
612   pr->sender_pid = 0;
613   GNUNET_PEER_change_rc (pr->origin_pid, -1);
614   pr->origin_pid = 0;
615   if (NULL != pr->hnode)
616   {
617     GNUNET_CONTAINER_heap_remove_node (pr->hnode);
618     pr->hnode = NULL;
619   }
620   if (NULL != pr->qe)
621   {
622     GNUNET_DATASTORE_cancel (pr->qe);
623     pr->qe = NULL;
624   }
625   if (NULL != pr->gh)
626   {
627     GNUNET_DHT_get_stop (pr->gh);
628     pr->gh = NULL;
629   }
630   if (NULL != pr->mesh_request)
631   {
632     GSF_mesh_query_cancel (pr->mesh_request);
633     pr->mesh_request = NULL;
634   }
635   if (GNUNET_SCHEDULER_NO_TASK != pr->warn_task)
636   {
637     GNUNET_SCHEDULER_cancel (pr->warn_task);
638     pr->warn_task = GNUNET_SCHEDULER_NO_TASK;
639   }
640   GNUNET_assert (GNUNET_OK ==
641                  GNUNET_CONTAINER_multihashmap_remove (pr_map,
642                                                        &pr->public_data.query,
643                                                        pr));
644   GNUNET_STATISTICS_update (GSF_stats,
645                             gettext_noop ("# Pending requests active"), -1,
646                             GNUNET_NO);
647   GNUNET_free (pr);
648   return GNUNET_YES;
649 }
650
651
652 /**
653  * Explicitly cancel a pending request.
654  *
655  * @param pr request to cancel
656  * @param full_cleanup fully purge the request
657  */
658 void
659 GSF_pending_request_cancel_ (struct GSF_PendingRequest *pr, int full_cleanup)
660 {
661   GSF_LocalLookupContinuation cont;
662
663   if (NULL == pr_map)
664     return;                     /* already cleaned up! */
665   if (GNUNET_YES != full_cleanup)
666   {
667     /* make request inactive (we're no longer interested in more results),
668      * but do NOT remove from our data-structures, we still need it there
669      * to prevent the request from looping */
670     pr->rh = NULL;
671     if (NULL != (cont = pr->llc_cont))
672     {
673       pr->llc_cont = NULL;
674       cont (pr->llc_cont_cls, pr, pr->local_result);
675     }
676     GSF_plan_notify_request_done_ (pr);
677     if (NULL != pr->qe)
678     {
679       GNUNET_DATASTORE_cancel (pr->qe);
680       pr->qe = NULL;
681     }
682     if (NULL != pr->gh)
683     {
684       GNUNET_DHT_get_stop (pr->gh);
685       pr->gh = NULL;
686     }
687     if (NULL != pr->mesh_request)
688     {
689       GSF_mesh_query_cancel (pr->mesh_request);
690       pr->mesh_request = NULL;
691     }
692     if (GNUNET_SCHEDULER_NO_TASK != pr->warn_task)
693     {
694       GNUNET_SCHEDULER_cancel (pr->warn_task);
695       pr->warn_task = GNUNET_SCHEDULER_NO_TASK;
696     }
697     return;
698   }
699   GNUNET_assert (GNUNET_YES ==
700                  clean_request (NULL, &pr->public_data.query, pr));
701 }
702
703
704 /**
705  * Iterate over all pending requests.
706  *
707  * @param it function to call for each request
708  * @param cls closure for it
709  */
710 void
711 GSF_iterate_pending_requests_ (GSF_PendingRequestIterator it, void *cls)
712 {
713   GNUNET_CONTAINER_multihashmap_iterate (pr_map,
714                                          (GNUNET_CONTAINER_HashMapIterator) it,
715                                          cls);
716 }
717
718
719
720
721 /**
722  * Closure for "process_reply" function.
723  */
724 struct ProcessReplyClosure
725 {
726   /**
727    * The data for the reply.
728    */
729   const void *data;
730
731   /**
732    * Who gave us this reply? NULL for local host (or DHT)
733    */
734   struct GSF_ConnectedPeer *sender;
735
736   /**
737    * When the reply expires.
738    */
739   struct GNUNET_TIME_Absolute expiration;
740
741   /**
742    * Size of data.
743    */
744   size_t size;
745
746   /**
747    * Type of the block.
748    */
749   enum GNUNET_BLOCK_Type type;
750
751   /**
752    * How much was this reply worth to us?
753    */
754   uint32_t priority;
755
756   /**
757    * Anonymity requirements for this reply.
758    */
759   uint32_t anonymity_level;
760
761   /**
762    * Evaluation result (returned).
763    */
764   enum GNUNET_BLOCK_EvaluationResult eval;
765
766   /**
767    * Did we find a matching request?
768    */
769   int request_found;
770 };
771
772
773 /**
774  * Update the performance data for the sender (if any) since
775  * the sender successfully answered one of our queries.
776  *
777  * @param prq information about the sender
778  * @param pr request that was satisfied
779  */
780 static void
781 update_request_performance_data (struct ProcessReplyClosure *prq,
782                                  struct GSF_PendingRequest *pr)
783 {
784   if (prq->sender == NULL)
785     return;
786   GSF_peer_update_performance_ (prq->sender, pr->public_data.start_time,
787                                 prq->priority);
788 }
789
790
791 /**
792  * We have received a reply; handle it!
793  *
794  * @param cls response (struct ProcessReplyClosure)
795  * @param key our query
796  * @param value value in the hash map (info about the query)
797  * @return #GNUNET_YES (we should continue to iterate)
798  */
799 static int
800 process_reply (void *cls, const struct GNUNET_HashCode * key, void *value)
801 {
802   struct ProcessReplyClosure *prq = cls;
803   struct GSF_PendingRequest *pr = value;
804   struct GNUNET_HashCode chash;
805   struct GNUNET_TIME_Absolute last_transmission;
806
807   if (NULL == pr->rh)
808     return GNUNET_YES;
809   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
810               "Matched result (type %u) for query `%s' with pending request\n",
811               (unsigned int) prq->type, GNUNET_h2s (key));
812   GNUNET_STATISTICS_update (GSF_stats,
813                             gettext_noop ("# replies received and matched"), 1,
814                             GNUNET_NO);
815   prq->eval =
816       GNUNET_BLOCK_evaluate (GSF_block_ctx, prq->type, key, &pr->bf, pr->mingle,
817                              NULL, 0, prq->data,
818                              prq->size);
819   switch (prq->eval)
820   {
821   case GNUNET_BLOCK_EVALUATION_OK_MORE:
822     update_request_performance_data (prq, pr);
823     break;
824   case GNUNET_BLOCK_EVALUATION_OK_LAST:
825     /* short cut: stop processing early, no BF-update, etc. */
826     update_request_performance_data (prq, pr);
827     GNUNET_LOAD_update (GSF_rt_entry_lifetime,
828                         GNUNET_TIME_absolute_get_duration (pr->
829                                                            public_data.start_time).rel_value_us);
830     if (GNUNET_YES !=
831         GSF_request_plan_reference_get_last_transmission_ (pr->public_data.pr_head,
832                                                            prq->sender,
833                                                            &last_transmission))
834       last_transmission.abs_value_us = GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us;
835     /* pass on to other peers / local clients */
836     pr->rh (pr->rh_cls, prq->eval, pr, prq->anonymity_level, prq->expiration,
837             last_transmission, prq->type, prq->data, prq->size);
838     return GNUNET_YES;
839   case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
840 #if INSANE_STATISTICS
841     GNUNET_STATISTICS_update (GSF_stats,
842                               gettext_noop
843                               ("# duplicate replies discarded (bloomfilter)"),
844                               1, GNUNET_NO);
845 #endif
846     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
847                 "Duplicate response, discarding.\n");
848     return GNUNET_YES;          /* duplicate */
849   case GNUNET_BLOCK_EVALUATION_RESULT_IRRELEVANT:
850     GNUNET_STATISTICS_update (GSF_stats,
851                               gettext_noop
852                               ("# irrelevant replies discarded"),
853                               1, GNUNET_NO);
854     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
855                 "Irrelevant response, ignoring.\n");
856     return GNUNET_YES;
857   case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
858     return GNUNET_YES;          /* wrong namespace */
859   case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
860     GNUNET_break (0);
861     return GNUNET_YES;
862   case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
863     GNUNET_break (0);
864     return GNUNET_YES;
865   case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
866     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Unsupported block type %u\n"),
867                 prq->type);
868     return GNUNET_NO;
869   }
870   /* update bloomfilter */
871   GNUNET_CRYPTO_hash (prq->data, prq->size, &chash);
872   GSF_pending_request_update_ (pr, &chash, 1);
873   if (NULL == prq->sender)
874   {
875     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
876                 "Found result for query `%s' in local datastore\n",
877                 GNUNET_h2s (key));
878     GNUNET_STATISTICS_update (GSF_stats,
879                               gettext_noop ("# results found locally"), 1,
880                               GNUNET_NO);
881   }
882   else
883   {
884     GSF_dht_lookup_ (pr);
885   }
886   prq->priority += pr->public_data.original_priority;
887   pr->public_data.priority = 0;
888   pr->public_data.original_priority = 0;
889   pr->public_data.results_found++;
890   prq->request_found = GNUNET_YES;
891   /* finally, pass on to other peer / local client */
892   if (! GSF_request_plan_reference_get_last_transmission_ (pr->public_data.pr_head,
893                                                            prq->sender,
894                                                            &last_transmission))
895     last_transmission.abs_value_us = GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us;
896   pr->rh (pr->rh_cls, prq->eval, pr,
897           prq->anonymity_level, prq->expiration,
898           last_transmission, prq->type, prq->data, prq->size);
899   return GNUNET_YES;
900 }
901
902
903 /**
904  * Context for put_migration_continuation().
905  */
906 struct PutMigrationContext
907 {
908
909   /**
910    * Start time for the operation.
911    */
912   struct GNUNET_TIME_Absolute start;
913
914   /**
915    * Request origin.
916    */
917   struct GNUNET_PeerIdentity origin;
918
919   /**
920    * GNUNET_YES if we had a matching request for this block,
921    * GNUNET_NO if not.
922    */
923   int requested;
924 };
925
926
927 /**
928  * Continuation called to notify client about result of the
929  * operation.
930  *
931  * @param cls closure
932  * @param success #GNUNET_SYSERR on failure
933  * @param min_expiration minimum expiration time required for content to be stored
934  * @param msg NULL on success, otherwise an error message
935  */
936 static void
937 put_migration_continuation (void *cls, int success,
938                             struct GNUNET_TIME_Absolute min_expiration,
939                             const char *msg)
940 {
941   struct PutMigrationContext *pmc = cls;
942   struct GSF_ConnectedPeer *cp;
943   struct GNUNET_TIME_Relative mig_pause;
944   struct GSF_PeerPerformanceData *ppd;
945
946   if (NULL != datastore_put_load)
947   {
948     if (GNUNET_SYSERR != success)
949     {
950       GNUNET_LOAD_update (datastore_put_load,
951                           GNUNET_TIME_absolute_get_duration (pmc->start).rel_value_us);
952     }
953     else
954     {
955       /* on queue failure / timeout, increase the put load dramatically */
956       GNUNET_LOAD_update (datastore_put_load,
957                           GNUNET_TIME_UNIT_MINUTES.rel_value_us);
958     }
959   }
960   cp = GSF_peer_get_ (&pmc->origin);
961   if (GNUNET_OK == success)
962   {
963     if (NULL != cp)
964     {
965       ppd = GSF_get_peer_performance_data_ (cp);
966       ppd->migration_delay.rel_value_us /= 2;
967     }
968     GNUNET_free (pmc);
969     return;
970   }
971   if ( (GNUNET_NO == success) &&
972        (GNUNET_NO == pmc->requested) &&
973        (NULL != cp) )
974   {
975     ppd = GSF_get_peer_performance_data_ (cp);
976     if (min_expiration.abs_value_us > 0)
977     {
978       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
979                   "Asking to stop migration for %s because datastore is full\n",
980                   GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (min_expiration), GNUNET_YES));
981       GSF_block_peer_migration_ (cp, min_expiration);
982     }
983     else
984     {
985       ppd->migration_delay = GNUNET_TIME_relative_max (GNUNET_TIME_UNIT_SECONDS,
986                                                        ppd->migration_delay);
987       ppd->migration_delay = GNUNET_TIME_relative_min (GNUNET_TIME_UNIT_HOURS,
988                                                        ppd->migration_delay);
989       mig_pause.rel_value_us = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
990                                                          ppd->migration_delay.rel_value_us);
991       ppd->migration_delay = GNUNET_TIME_relative_multiply (ppd->migration_delay, 2);
992       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
993                   "Replicated content already exists locally, asking to stop migration for %s\n",
994                   GNUNET_STRINGS_relative_time_to_string (mig_pause, GNUNET_YES));
995       GSF_block_peer_migration_ (cp, GNUNET_TIME_relative_to_absolute (mig_pause));
996     }
997   }
998   GNUNET_free (pmc);
999   GNUNET_STATISTICS_update (GSF_stats,
1000                             gettext_noop ("# Datastore `PUT' failures"), 1,
1001                             GNUNET_NO);
1002 }
1003
1004
1005 /**
1006  * Test if the DATABASE (PUT) load on this peer is too high
1007  * to even consider processing the query at
1008  * all.
1009  *
1010  * @param priority the priority of the item
1011  * @return #GNUNET_YES if the load is too high to do anything (load high)
1012  *         #GNUNET_NO to process normally (load normal or low)
1013  */
1014 static int
1015 test_put_load_too_high (uint32_t priority)
1016 {
1017   double ld;
1018
1019   if (NULL == datastore_put_load)
1020     return GNUNET_NO;
1021   if (GNUNET_LOAD_get_average (datastore_put_load) < 50)
1022     return GNUNET_NO;           /* very fast */
1023   ld = GNUNET_LOAD_get_load (datastore_put_load);
1024   if (ld < 2.0 * (1 + priority))
1025     return GNUNET_NO;
1026   GNUNET_STATISTICS_update (GSF_stats,
1027                             gettext_noop
1028                             ("# storage requests dropped due to high load"), 1,
1029                             GNUNET_NO);
1030   return GNUNET_YES;
1031 }
1032
1033
1034 /**
1035  * Iterator called on each result obtained for a DHT
1036  * operation that expects a reply
1037  *
1038  * @param cls closure
1039  * @param exp when will this value expire
1040  * @param key key of the result
1041  * @param get_path peers on reply path (or NULL if not recorded)
1042  * @param get_path_length number of entries in @a get_path
1043  * @param put_path peers on the PUT path (or NULL if not recorded)
1044  * @param put_path_length number of entries in @a get_path
1045  * @param type type of the result
1046  * @param size number of bytes in @a data
1047  * @param data pointer to the result data
1048  */
1049 static void
1050 handle_dht_reply (void *cls, struct GNUNET_TIME_Absolute exp,
1051                   const struct GNUNET_HashCode * key,
1052                   const struct GNUNET_PeerIdentity *get_path,
1053                   unsigned int get_path_length,
1054                   const struct GNUNET_PeerIdentity *put_path,
1055                   unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
1056                   size_t size, const void *data)
1057 {
1058   struct GSF_PendingRequest *pr = cls;
1059   struct ProcessReplyClosure prq;
1060   struct PutMigrationContext *pmc;
1061
1062   GNUNET_STATISTICS_update (GSF_stats,
1063                             gettext_noop ("# Replies received from DHT"), 1,
1064                             GNUNET_NO);
1065   memset (&prq, 0, sizeof (prq));
1066   prq.data = data;
1067   prq.expiration = exp;
1068   /* do not allow migrated content to live longer than 1 year */
1069   prq.expiration = GNUNET_TIME_absolute_min (GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_YEARS),
1070                                              prq.expiration);
1071   prq.size = size;
1072   prq.type = type;
1073   process_reply (&prq, key, pr);
1074   if ((GNUNET_YES == active_to_migration) &&
1075       (GNUNET_NO == test_put_load_too_high (prq.priority)))
1076   {
1077     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1078                 "Replicating result for query `%s' with priority %u\n",
1079                 GNUNET_h2s (key), prq.priority);
1080     pmc = GNUNET_malloc (sizeof (struct PutMigrationContext));
1081     pmc->start = GNUNET_TIME_absolute_get ();
1082     pmc->requested = GNUNET_YES;
1083     if (NULL ==
1084         GNUNET_DATASTORE_put (GSF_dsh, 0, key, size, data, type, prq.priority,
1085                               1 /* anonymity */ ,
1086                               0 /* replication */ ,
1087                               exp, 1 + prq.priority, MAX_DATASTORE_QUEUE,
1088                               GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1089                               &put_migration_continuation, pmc))
1090     {
1091       put_migration_continuation (pmc, GNUNET_SYSERR, GNUNET_TIME_UNIT_ZERO_ABS, NULL);
1092     }
1093   }
1094 }
1095
1096
1097 /**
1098  * Consider looking up the data in the DHT (anonymity-level permitting).
1099  *
1100  * @param pr the pending request to process
1101  */
1102 void
1103 GSF_dht_lookup_ (struct GSF_PendingRequest *pr)
1104 {
1105   const void *xquery;
1106   size_t xquery_size;
1107   struct GNUNET_PeerIdentity pi;
1108   char buf[sizeof (struct GNUNET_HashCode) * 2] GNUNET_ALIGN;
1109
1110   if (0 != pr->public_data.anonymity_level)
1111     return;
1112   if (NULL != pr->gh)
1113   {
1114     GNUNET_DHT_get_stop (pr->gh);
1115     pr->gh = NULL;
1116   }
1117   xquery = NULL;
1118   xquery_size = 0;
1119   if (0 != (pr->public_data.options & GSF_PRO_FORWARD_ONLY))
1120   {
1121     GNUNET_assert (0 != pr->sender_pid);
1122     GNUNET_PEER_resolve (pr->sender_pid, &pi);
1123     memcpy (&buf[xquery_size], &pi, sizeof (struct GNUNET_PeerIdentity));
1124     xquery_size += sizeof (struct GNUNET_PeerIdentity);
1125   }
1126   pr->gh =
1127       GNUNET_DHT_get_start (GSF_dht,
1128                             pr->public_data.type, &pr->public_data.query,
1129                             DHT_GET_REPLICATION,
1130                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
1131                             xquery, xquery_size, &handle_dht_reply, pr);
1132   if ( (NULL != pr->gh) &&
1133        (0 != pr->replies_seen_count) )
1134     GNUNET_DHT_get_filter_known_results (pr->gh,
1135                                          pr->replies_seen_count,
1136                                          pr->replies_seen);
1137 }
1138
1139
1140 /**
1141  * Function called with a reply from the mesh.
1142  *
1143  * @param cls the pending request struct
1144  * @param type type of the block, ANY on error
1145  * @param expiration expiration time for the block
1146  * @param data_size number of bytes in 'data', 0 on error
1147  * @param data reply block data, NULL on error
1148  */
1149 static void
1150 mesh_reply_proc (void *cls,
1151                    enum GNUNET_BLOCK_Type type,
1152                    struct GNUNET_TIME_Absolute expiration,
1153                    size_t data_size,
1154                    const void *data)
1155 {
1156   struct GSF_PendingRequest *pr = cls;
1157   struct ProcessReplyClosure prq;
1158   struct GNUNET_HashCode query;
1159
1160   pr->mesh_request = NULL;
1161   if (GNUNET_BLOCK_TYPE_ANY == type)
1162   {
1163     GNUNET_break (NULL == data);
1164     GNUNET_break (0 == data_size);
1165     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1166                 "Error retrieiving block via mesh\n");
1167     pr->mesh_retry_count++;
1168     if (pr->mesh_retry_count >= MESH_RETRY_MAX)
1169       return; /* give up on mesh */
1170     /* retry -- without delay, as this is non-anonymous
1171        and mesh/mesh connect will take some time anyway */
1172     pr->mesh_request = GSF_mesh_query (pr->public_data.target,
1173                                            &pr->public_data.query,
1174                                            pr->public_data.type,
1175                                            &mesh_reply_proc,
1176                                            pr);
1177     return;
1178   }
1179   if (GNUNET_YES !=
1180       GNUNET_BLOCK_get_key (GSF_block_ctx,
1181                             type,
1182                             data, data_size, &query))
1183   {
1184     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1185                 "Failed to derive key for block of type %d\n",
1186                 (int) type);
1187     GNUNET_break_op (0);
1188     return;
1189   }
1190   GNUNET_STATISTICS_update (GSF_stats,
1191                             gettext_noop ("# Replies received from MESH"), 1,
1192                             GNUNET_NO);
1193   memset (&prq, 0, sizeof (prq));
1194   prq.data = data;
1195   prq.expiration = expiration;
1196   /* do not allow migrated content to live longer than 1 year */
1197   prq.expiration = GNUNET_TIME_absolute_min (GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_YEARS),
1198                                              prq.expiration);
1199   prq.size = data_size;
1200   prq.type = type;
1201   process_reply (&prq, &query, pr);
1202 }
1203
1204
1205 /**
1206  * Consider downloading via mesh (if possible)
1207  *
1208  * @param pr the pending request to process
1209  */
1210 void
1211 GSF_mesh_lookup_ (struct GSF_PendingRequest *pr)
1212 {
1213   if (0 != pr->public_data.anonymity_level)
1214     return;
1215   if (0 == pr->public_data.target)
1216   {
1217     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1218                 "Cannot do mesh-based download, target peer not known\n");
1219     return;
1220   }
1221   if (NULL != pr->mesh_request)
1222     return;
1223   pr->mesh_request = GSF_mesh_query (pr->public_data.target,
1224                                      &pr->public_data.query,
1225                                      pr->public_data.type,
1226                                      &mesh_reply_proc,
1227                                      pr);
1228 }
1229
1230
1231 /**
1232  * Task that issues a warning if the datastore lookup takes too long.
1233  *
1234  * @param cls the 'struct GSF_PendingRequest'
1235  * @param tc task context
1236  */
1237 static void
1238 warn_delay_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1239 {
1240   struct GSF_PendingRequest *pr = cls;
1241
1242   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1243               _("Datastore lookup already took %s!\n"),
1244               GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (pr->qe_start), GNUNET_YES));
1245   pr->warn_task =
1246       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, &warn_delay_task,
1247                                     pr);
1248 }
1249
1250
1251 /**
1252  * Task that issues a warning if the datastore lookup takes too long.
1253  *
1254  * @param cls the 'struct GSF_PendingRequest'
1255  * @param tc task context
1256  */
1257 static void
1258 odc_warn_delay_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1259 {
1260   struct GSF_PendingRequest *pr = cls;
1261
1262   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1263               _("On-demand lookup already took %s!\n"),
1264               GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (pr->qe_start), GNUNET_YES));
1265   pr->warn_task =
1266       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1267                                     &odc_warn_delay_task, pr);
1268 }
1269
1270
1271 /**
1272  * We're processing (local) results for a search request
1273  * from another peer.  Pass applicable results to the
1274  * peer and if we are done either clean up (operation
1275  * complete) or forward to other peers (more results possible).
1276  *
1277  * @param cls our closure (struct PendingRequest)
1278  * @param key key for the content
1279  * @param size number of bytes in data
1280  * @param data content stored
1281  * @param type type of the content
1282  * @param priority priority of the content
1283  * @param anonymity anonymity-level for the content
1284  * @param expiration expiration time for the content
1285  * @param uid unique identifier for the datum;
1286  *        maybe 0 if no unique identifier is available
1287  */
1288 static void
1289 process_local_reply (void *cls, const struct GNUNET_HashCode * key, size_t size,
1290                      const void *data, enum GNUNET_BLOCK_Type type,
1291                      uint32_t priority, uint32_t anonymity,
1292                      struct GNUNET_TIME_Absolute expiration, uint64_t uid)
1293 {
1294   struct GSF_PendingRequest *pr = cls;
1295   GSF_LocalLookupContinuation cont;
1296   struct ProcessReplyClosure prq;
1297   struct GNUNET_HashCode query;
1298   unsigned int old_rf;
1299
1300   GNUNET_SCHEDULER_cancel (pr->warn_task);
1301   pr->warn_task = GNUNET_SCHEDULER_NO_TASK;
1302   if (NULL != pr->qe)
1303   {
1304     pr->qe = NULL;
1305     if (NULL == key)
1306     {
1307 #if INSANE_STATISTICS
1308       GNUNET_STATISTICS_update (GSF_stats,
1309                                 gettext_noop
1310                                 ("# Datastore lookups concluded (no results)"),
1311                                 1, GNUNET_NO);
1312 #endif
1313     }
1314     if (GNUNET_NO == pr->have_first_uid)
1315     {
1316       pr->first_uid = uid;
1317       pr->have_first_uid = 1;
1318     }
1319     else
1320     {
1321       if ((uid == pr->first_uid) && (key != NULL))
1322       {
1323         GNUNET_STATISTICS_update (GSF_stats,
1324                                   gettext_noop
1325                                   ("# Datastore lookups concluded (seen all)"),
1326                                   1, GNUNET_NO);
1327         key = NULL;             /* all replies seen! */
1328       }
1329       pr->have_first_uid++;
1330       if ((pr->have_first_uid > MAX_RESULTS) && (key != NULL))
1331       {
1332         GNUNET_STATISTICS_update (GSF_stats,
1333                                   gettext_noop
1334                                   ("# Datastore lookups aborted (more than MAX_RESULTS)"),
1335                                   1, GNUNET_NO);
1336         key = NULL;             /* all replies seen! */
1337       }
1338     }
1339   }
1340   if (NULL == key)
1341   {
1342     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1343                 "No further local responses available.\n");
1344 #if INSANE_STATISTICS
1345     if ((pr->public_data.type == GNUNET_BLOCK_TYPE_FS_DBLOCK) ||
1346         (pr->public_data.type == GNUNET_BLOCK_TYPE_FS_IBLOCK))
1347       GNUNET_STATISTICS_update (GSF_stats,
1348                                 gettext_noop
1349                                 ("# requested DBLOCK or IBLOCK not found"), 1,
1350                                 GNUNET_NO);
1351 #endif
1352     goto check_error_and_continue;
1353   }
1354   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1355               "Received reply for `%s' of type %d with UID %llu from datastore.\n",
1356               GNUNET_h2s (key), type, (unsigned long long) uid);
1357   if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
1358   {
1359     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1360                 "Found ONDEMAND block, performing on-demand encoding\n");
1361     GNUNET_STATISTICS_update (GSF_stats,
1362                               gettext_noop
1363                               ("# on-demand blocks matched requests"), 1,
1364                               GNUNET_NO);
1365     pr->qe_start = GNUNET_TIME_absolute_get ();
1366     pr->warn_task =
1367         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1368                                       &odc_warn_delay_task, pr);
1369     if (GNUNET_OK ==
1370         GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
1371                                           anonymity, expiration, uid,
1372                                           &process_local_reply, pr))
1373     {
1374       GNUNET_STATISTICS_update (GSF_stats,
1375                                 gettext_noop
1376                                 ("# on-demand lookups performed successfully"),
1377                                 1, GNUNET_NO);
1378       return;                   /* we're done */
1379     }
1380     GNUNET_STATISTICS_update (GSF_stats,
1381                               gettext_noop ("# on-demand lookups failed"), 1,
1382                               GNUNET_NO);
1383     GNUNET_SCHEDULER_cancel (pr->warn_task);
1384     pr->warn_task =
1385         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1386                                       &warn_delay_task, pr);
1387     pr->qe =
1388         GNUNET_DATASTORE_get_key (GSF_dsh, pr->local_result_offset - 1,
1389                                   &pr->public_data.query,
1390                                   pr->public_data.type ==
1391                                   GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1392                                   GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1393                                   (0 !=
1394                                    (GSF_PRO_PRIORITY_UNLIMITED &
1395                                     pr->public_data.options)) ? UINT_MAX : 1
1396                                   /* queue priority */ ,
1397                                   (0 !=
1398                                    (GSF_PRO_PRIORITY_UNLIMITED &
1399                                     pr->public_data.options)) ? UINT_MAX :
1400                                   GSF_datastore_queue_size
1401                                   /* max queue size */ ,
1402                                   GNUNET_TIME_UNIT_FOREVER_REL,
1403                                   &process_local_reply, pr);
1404     if (NULL != pr->qe)
1405       return;                   /* we're done */
1406     GNUNET_STATISTICS_update (GSF_stats,
1407                               gettext_noop
1408                               ("# Datastore lookups concluded (error queueing)"),
1409                               1, GNUNET_NO);
1410     goto check_error_and_continue;
1411   }
1412   old_rf = pr->public_data.results_found;
1413   memset (&prq, 0, sizeof (prq));
1414   prq.data = data;
1415   prq.expiration = expiration;
1416   prq.size = size;
1417   if (GNUNET_OK !=
1418       GNUNET_BLOCK_get_key (GSF_block_ctx, type, data, size, &query))
1419   {
1420     GNUNET_break (0);
1421     GNUNET_DATASTORE_remove (GSF_dsh, key, size, data, -1, -1,
1422                              GNUNET_TIME_UNIT_FOREVER_REL, NULL, NULL);
1423     pr->qe_start = GNUNET_TIME_absolute_get ();
1424     pr->warn_task =
1425         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1426                                       &warn_delay_task, pr);
1427     pr->qe =
1428         GNUNET_DATASTORE_get_key (GSF_dsh, pr->local_result_offset - 1,
1429                                   &pr->public_data.query,
1430                                   pr->public_data.type ==
1431                                   GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1432                                   GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1433                                   (0 !=
1434                                    (GSF_PRO_PRIORITY_UNLIMITED &
1435                                     pr->public_data.options)) ? UINT_MAX : 1
1436                                   /* queue priority */ ,
1437                                   (0 !=
1438                                    (GSF_PRO_PRIORITY_UNLIMITED &
1439                                     pr->public_data.options)) ? UINT_MAX :
1440                                   GSF_datastore_queue_size
1441                                   /* max queue size */ ,
1442                                   GNUNET_TIME_UNIT_FOREVER_REL,
1443                                   &process_local_reply, pr);
1444     if (pr->qe == NULL)
1445     {
1446       GNUNET_STATISTICS_update (GSF_stats,
1447                                 gettext_noop
1448                                 ("# Datastore lookups concluded (error queueing)"),
1449                                 1, GNUNET_NO);
1450       goto check_error_and_continue;
1451     }
1452     return;
1453   }
1454   prq.type = type;
1455   prq.priority = priority;
1456   prq.request_found = GNUNET_NO;
1457   prq.anonymity_level = anonymity;
1458   if ((old_rf == 0) && (pr->public_data.results_found == 0))
1459     GSF_update_datastore_delay_ (pr->public_data.start_time);
1460   process_reply (&prq, key, pr);
1461   pr->local_result = prq.eval;
1462   if (prq.eval == GNUNET_BLOCK_EVALUATION_OK_LAST)
1463   {
1464     GNUNET_STATISTICS_update (GSF_stats,
1465                               gettext_noop
1466                               ("# Datastore lookups concluded (found last result)"),
1467                               1, GNUNET_NO);
1468     goto check_error_and_continue;
1469   }
1470   if ((0 == (GSF_PRO_PRIORITY_UNLIMITED & pr->public_data.options)) &&
1471       ((GNUNET_YES == GSF_test_get_load_too_high_ (0)) ||
1472        (pr->public_data.results_found > 5 + 2 * pr->public_data.priority)))
1473   {
1474     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Load too high, done with request\n");
1475     GNUNET_STATISTICS_update (GSF_stats,
1476                               gettext_noop
1477                               ("# Datastore lookups concluded (load too high)"),
1478                               1, GNUNET_NO);
1479     goto check_error_and_continue;
1480   }
1481   pr->qe_start = GNUNET_TIME_absolute_get ();
1482   pr->warn_task =
1483       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, &warn_delay_task,
1484                                     pr);
1485   pr->qe =
1486       GNUNET_DATASTORE_get_key (GSF_dsh, pr->local_result_offset++,
1487                                 &pr->public_data.query,
1488                                 pr->public_data.type ==
1489                                 GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1490                                 GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1491                                 (0 !=
1492                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1493                                   public_data.options)) ? UINT_MAX : 1
1494                                 /* queue priority */ ,
1495                                 (0 !=
1496                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1497                                   public_data.options)) ? UINT_MAX :
1498                                 GSF_datastore_queue_size
1499                                 /* max queue size */ ,
1500                                 GNUNET_TIME_UNIT_FOREVER_REL,
1501                                 &process_local_reply, pr);
1502   /* check if we successfully queued another datastore request;
1503    * if so, return, otherwise call our continuation (if we have
1504    * any) */
1505 check_error_and_continue:
1506   if (NULL != pr->qe)
1507     return;
1508   if (GNUNET_SCHEDULER_NO_TASK != pr->warn_task)
1509   {
1510     GNUNET_SCHEDULER_cancel (pr->warn_task);
1511     pr->warn_task = GNUNET_SCHEDULER_NO_TASK;
1512   }
1513   if (NULL == (cont = pr->llc_cont))
1514     return;                     /* no continuation */
1515   pr->llc_cont = NULL;
1516   cont (pr->llc_cont_cls, pr, pr->local_result);
1517 }
1518
1519
1520 /**
1521  * Is the given target a legitimate peer for forwarding the given request?
1522  *
1523  * @param pr request
1524  * @param target
1525  * @return GNUNET_YES if this request could be forwarded to the given peer
1526  */
1527 int
1528 GSF_pending_request_test_target_ (struct GSF_PendingRequest *pr,
1529                                   const struct GNUNET_PeerIdentity *target)
1530 {
1531   struct GNUNET_PeerIdentity pi;
1532
1533   if (0 == pr->origin_pid)
1534     return GNUNET_YES;
1535   GNUNET_PEER_resolve (pr->origin_pid, &pi);
1536   return (0 ==
1537           memcmp (&pi, target,
1538                   sizeof (struct GNUNET_PeerIdentity))) ? GNUNET_NO :
1539       GNUNET_YES;
1540 }
1541
1542
1543 /**
1544  * Look up the request in the local datastore.
1545  *
1546  * @param pr the pending request to process
1547  * @param cont function to call at the end
1548  * @param cont_cls closure for cont
1549  */
1550 void
1551 GSF_local_lookup_ (struct GSF_PendingRequest *pr,
1552                    GSF_LocalLookupContinuation cont, void *cont_cls)
1553 {
1554   GNUNET_assert (NULL == pr->gh);
1555   GNUNET_assert (NULL == pr->mesh_request);
1556   GNUNET_assert (NULL == pr->llc_cont);
1557   pr->llc_cont = cont;
1558   pr->llc_cont_cls = cont_cls;
1559   pr->qe_start = GNUNET_TIME_absolute_get ();
1560   pr->warn_task =
1561       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, &warn_delay_task,
1562                                     pr);
1563 #if INSANE_STATISTICS
1564   GNUNET_STATISTICS_update (GSF_stats,
1565                             gettext_noop ("# Datastore lookups initiated"), 1,
1566                             GNUNET_NO);
1567 #endif
1568   pr->qe =
1569       GNUNET_DATASTORE_get_key (GSF_dsh, pr->local_result_offset++,
1570                                 &pr->public_data.query,
1571                                 pr->public_data.type ==
1572                                 GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1573                                 GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1574                                 (0 !=
1575                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1576                                   public_data.options)) ? UINT_MAX : 1
1577                                 /* queue priority */ ,
1578                                 (0 !=
1579                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1580                                   public_data.options)) ? UINT_MAX :
1581                                 GSF_datastore_queue_size
1582                                 /* max queue size */ ,
1583                                 GNUNET_TIME_UNIT_FOREVER_REL,
1584                                 &process_local_reply, pr);
1585   if (NULL != pr->qe)
1586     return;
1587   GNUNET_STATISTICS_update (GSF_stats,
1588                             gettext_noop
1589                             ("# Datastore lookups concluded (error queueing)"),
1590                             1, GNUNET_NO);
1591   GNUNET_SCHEDULER_cancel (pr->warn_task);
1592   pr->warn_task = GNUNET_SCHEDULER_NO_TASK;
1593   pr->llc_cont = NULL;
1594   if (NULL != cont)
1595     cont (cont_cls, pr, pr->local_result);
1596 }
1597
1598
1599
1600 /**
1601  * Handle P2P "CONTENT" message.  Checks that the message is
1602  * well-formed and then checks if there are any pending requests for
1603  * this content and possibly passes it on (to local clients or other
1604  * peers).  Does NOT perform migration (content caching at this peer).
1605  *
1606  * @param cp the other peer involved (sender or receiver, NULL
1607  *        for loopback messages where we are both sender and receiver)
1608  * @param message the actual message
1609  * @return GNUNET_OK if the message was well-formed,
1610  *         GNUNET_SYSERR if the message was malformed (close connection,
1611  *         do not cache under any circumstances)
1612  */
1613 int
1614 GSF_handle_p2p_content_ (struct GSF_ConnectedPeer *cp,
1615                          const struct GNUNET_MessageHeader *message)
1616 {
1617   const struct PutMessage *put;
1618   uint16_t msize;
1619   size_t dsize;
1620   enum GNUNET_BLOCK_Type type;
1621   struct GNUNET_TIME_Absolute expiration;
1622   struct GNUNET_HashCode query;
1623   struct ProcessReplyClosure prq;
1624   struct GNUNET_TIME_Relative block_time;
1625   double putl;
1626   struct PutMigrationContext *pmc;
1627
1628   msize = ntohs (message->size);
1629   if (msize < sizeof (struct PutMessage))
1630   {
1631     GNUNET_break_op (0);
1632     return GNUNET_SYSERR;
1633   }
1634   put = (const struct PutMessage *) message;
1635   dsize = msize - sizeof (struct PutMessage);
1636   type = ntohl (put->type);
1637   expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
1638   /* do not allow migrated content to live longer than 1 year */
1639   expiration = GNUNET_TIME_absolute_min (GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_YEARS),
1640                                          expiration);
1641   if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
1642     return GNUNET_SYSERR;
1643   if (GNUNET_OK !=
1644       GNUNET_BLOCK_get_key (GSF_block_ctx, type, &put[1], dsize, &query))
1645   {
1646     GNUNET_break_op (0);
1647     return GNUNET_SYSERR;
1648   }
1649   GNUNET_STATISTICS_update (GSF_stats,
1650                             gettext_noop ("# GAP PUT messages received"), 1,
1651                             GNUNET_NO);
1652   /* now, lookup 'query' */
1653   prq.data = (const void *) &put[1];
1654   prq.sender = cp;
1655   prq.size = dsize;
1656   prq.type = type;
1657   prq.expiration = expiration;
1658   prq.priority = 0;
1659   prq.anonymity_level = UINT32_MAX;
1660   prq.request_found = GNUNET_NO;
1661   GNUNET_CONTAINER_multihashmap_get_multiple (pr_map, &query, &process_reply,
1662                                               &prq);
1663   if (NULL != cp)
1664   {
1665     GSF_connected_peer_change_preference_ (cp,
1666                                            CONTENT_BANDWIDTH_VALUE +
1667                                            1000 * prq.priority);
1668     GSF_get_peer_performance_data_ (cp)->respect += prq.priority;
1669   }
1670   if ((GNUNET_YES == active_to_migration) &&
1671       (NULL != cp) &&
1672       (GNUNET_NO == test_put_load_too_high (prq.priority)))
1673   {
1674     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1675                 "Replicating result for query `%s' with priority %u\n",
1676                 GNUNET_h2s (&query), prq.priority);
1677     pmc = GNUNET_malloc (sizeof (struct PutMigrationContext));
1678     pmc->start = GNUNET_TIME_absolute_get ();
1679     pmc->requested = prq.request_found;
1680     GNUNET_assert (0 != GSF_get_peer_performance_data_ (cp)->pid);
1681     GNUNET_PEER_resolve (GSF_get_peer_performance_data_ (cp)->pid,
1682                          &pmc->origin);
1683     if (NULL ==
1684         GNUNET_DATASTORE_put (GSF_dsh, 0, &query, dsize, &put[1], type,
1685                               prq.priority, 1 /* anonymity */ ,
1686                               0 /* replication */ ,
1687                               expiration, 1 + prq.priority, MAX_DATASTORE_QUEUE,
1688                               GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1689                               &put_migration_continuation, pmc))
1690     {
1691       put_migration_continuation (pmc, GNUNET_SYSERR, GNUNET_TIME_UNIT_ZERO_ABS, NULL);
1692     }
1693   }
1694   else if (NULL != cp)
1695   {
1696     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1697                 "Choosing not to keep content `%s' (%d/%d)\n",
1698                 GNUNET_h2s (&query), active_to_migration,
1699                 test_put_load_too_high (prq.priority));
1700   }
1701   putl = GNUNET_LOAD_get_load (datastore_put_load);
1702   if ( (NULL != cp) &&
1703        (GNUNET_NO == prq.request_found) &&
1704        ( (GNUNET_YES != active_to_migration) ||
1705          (putl > 2.5 * (1 + prq.priority)) ) )
1706   {
1707     if (GNUNET_YES != active_to_migration)
1708       putl = 1.0 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 5);
1709     block_time =
1710         GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1711                                        5000 +
1712                                        GNUNET_CRYPTO_random_u32
1713                                        (GNUNET_CRYPTO_QUALITY_WEAK,
1714                                         (unsigned int) (60000 * putl * putl)));
1715     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1716                 "Asking to stop migration for %s because of load %f and events %d/%d\n",
1717                 GNUNET_STRINGS_relative_time_to_string (block_time,
1718                                                         GNUNET_YES),
1719                 putl,
1720                 active_to_migration,
1721                 (GNUNET_NO == prq.request_found));
1722     GSF_block_peer_migration_ (cp, GNUNET_TIME_relative_to_absolute (block_time));
1723   }
1724   return GNUNET_OK;
1725 }
1726
1727
1728 /**
1729  * Setup the subsystem.
1730  */
1731 void
1732 GSF_pending_request_init_ ()
1733 {
1734   if (GNUNET_OK !=
1735       GNUNET_CONFIGURATION_get_value_number (GSF_cfg, "fs",
1736                                              "MAX_PENDING_REQUESTS",
1737                                              &max_pending_requests))
1738   {
1739     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_INFO,
1740                                "fs", "MAX_PENDING_REQUESTS");
1741   }
1742   active_to_migration =
1743       GNUNET_CONFIGURATION_get_value_yesno (GSF_cfg, "FS", "CONTENT_CACHING");
1744   datastore_put_load = GNUNET_LOAD_value_init (DATASTORE_LOAD_AUTODECLINE);
1745   pr_map = GNUNET_CONTAINER_multihashmap_create (32 * 1024, GNUNET_YES);
1746   requests_by_expiration_heap =
1747       GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1748 }
1749
1750
1751 /**
1752  * Shutdown the subsystem.
1753  */
1754 void
1755 GSF_pending_request_done_ ()
1756 {
1757   GNUNET_CONTAINER_multihashmap_iterate (pr_map, &clean_request, NULL);
1758   GNUNET_CONTAINER_multihashmap_destroy (pr_map);
1759   pr_map = NULL;
1760   GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
1761   requests_by_expiration_heap = NULL;
1762   GNUNET_LOAD_value_free (datastore_put_load);
1763   datastore_put_load = NULL;
1764 }
1765
1766
1767 /* end of gnunet-service-fs_pr.c */