fix more leaks
[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 '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 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 'replies_seen' array
283  * @param rh handle to call when we get a reply
284  * @param rh_cls closure for 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 buf
498  * @param buf where to copy the message (can be NULL)
499  * @return number of bytes needed (if > 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 the '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  * @return GNUNET_YES if the load is too high to do anything (load high)
1011  *         GNUNET_NO to process normally (load normal or low)
1012  */
1013 static int
1014 test_put_load_too_high (uint32_t priority)
1015 {
1016   double ld;
1017
1018   if (NULL == datastore_put_load)
1019     return GNUNET_NO;
1020   if (GNUNET_LOAD_get_average (datastore_put_load) < 50)
1021     return GNUNET_NO;           /* very fast */
1022   ld = GNUNET_LOAD_get_load (datastore_put_load);
1023   if (ld < 2.0 * (1 + priority))
1024     return GNUNET_NO;
1025   GNUNET_STATISTICS_update (GSF_stats,
1026                             gettext_noop
1027                             ("# storage requests dropped due to high load"), 1,
1028                             GNUNET_NO);
1029   return GNUNET_YES;
1030 }
1031
1032
1033 /**
1034  * Iterator called on each result obtained for a DHT
1035  * operation that expects a reply
1036  *
1037  * @param cls closure
1038  * @param exp when will this value expire
1039  * @param key key of the result
1040  * @param get_path peers on reply path (or NULL if not recorded)
1041  * @param get_path_length number of entries in get_path
1042  * @param put_path peers on the PUT path (or NULL if not recorded)
1043  * @param put_path_length number of entries in get_path
1044  * @param type type of the result
1045  * @param size number of bytes in data
1046  * @param data pointer to the result data
1047  */
1048 static void
1049 handle_dht_reply (void *cls, struct GNUNET_TIME_Absolute exp,
1050                   const struct GNUNET_HashCode * key,
1051                   const struct GNUNET_PeerIdentity *get_path,
1052                   unsigned int get_path_length,
1053                   const struct GNUNET_PeerIdentity *put_path,
1054                   unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
1055                   size_t size, const void *data)
1056 {
1057   struct GSF_PendingRequest *pr = cls;
1058   struct ProcessReplyClosure prq;
1059   struct PutMigrationContext *pmc;
1060
1061   GNUNET_STATISTICS_update (GSF_stats,
1062                             gettext_noop ("# Replies received from DHT"), 1,
1063                             GNUNET_NO);
1064   memset (&prq, 0, sizeof (prq));
1065   prq.data = data;
1066   prq.expiration = exp;
1067   /* do not allow migrated content to live longer than 1 year */
1068   prq.expiration = GNUNET_TIME_absolute_min (GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_YEARS),
1069                                              prq.expiration);
1070   prq.size = size;
1071   prq.type = type;
1072   process_reply (&prq, key, pr);
1073   if ((GNUNET_YES == active_to_migration) &&
1074       (GNUNET_NO == test_put_load_too_high (prq.priority)))
1075   {
1076     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1077                 "Replicating result for query `%s' with priority %u\n",
1078                 GNUNET_h2s (key), prq.priority);
1079     pmc = GNUNET_malloc (sizeof (struct PutMigrationContext));
1080     pmc->start = GNUNET_TIME_absolute_get ();
1081     pmc->requested = GNUNET_YES;
1082     if (NULL ==
1083         GNUNET_DATASTORE_put (GSF_dsh, 0, key, size, data, type, prq.priority,
1084                               1 /* anonymity */ ,
1085                               0 /* replication */ ,
1086                               exp, 1 + prq.priority, MAX_DATASTORE_QUEUE,
1087                               GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1088                               &put_migration_continuation, pmc))
1089     {
1090       put_migration_continuation (pmc, GNUNET_SYSERR, GNUNET_TIME_UNIT_ZERO_ABS, NULL);
1091     }
1092   }
1093 }
1094
1095
1096 /**
1097  * Consider looking up the data in the DHT (anonymity-level permitting).
1098  *
1099  * @param pr the pending request to process
1100  */
1101 void
1102 GSF_dht_lookup_ (struct GSF_PendingRequest *pr)
1103 {
1104   const void *xquery;
1105   size_t xquery_size;
1106   struct GNUNET_PeerIdentity pi;
1107   char buf[sizeof (struct GNUNET_HashCode) * 2] GNUNET_ALIGN;
1108
1109   if (0 != pr->public_data.anonymity_level)
1110     return;
1111   if (NULL != pr->gh)
1112   {
1113     GNUNET_DHT_get_stop (pr->gh);
1114     pr->gh = NULL;
1115   }
1116   xquery = NULL;
1117   xquery_size = 0;
1118   if (0 != (pr->public_data.options & GSF_PRO_FORWARD_ONLY))
1119   {
1120     GNUNET_assert (0 != pr->sender_pid);
1121     GNUNET_PEER_resolve (pr->sender_pid, &pi);
1122     memcpy (&buf[xquery_size], &pi, sizeof (struct GNUNET_PeerIdentity));
1123     xquery_size += sizeof (struct GNUNET_PeerIdentity);
1124   }
1125   pr->gh =
1126       GNUNET_DHT_get_start (GSF_dht,
1127                             pr->public_data.type, &pr->public_data.query,
1128                             DHT_GET_REPLICATION,
1129                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
1130                             xquery, xquery_size, &handle_dht_reply, pr);
1131   if ( (NULL != pr->gh) &&
1132        (0 != pr->replies_seen_count) )
1133     GNUNET_DHT_get_filter_known_results (pr->gh,
1134                                          pr->replies_seen_count,
1135                                          pr->replies_seen);
1136 }
1137
1138
1139 /**
1140  * Function called with a reply from the mesh.
1141  *
1142  * @param cls the pending request struct
1143  * @param type type of the block, ANY on error
1144  * @param expiration expiration time for the block
1145  * @param data_size number of bytes in 'data', 0 on error
1146  * @param data reply block data, NULL on error
1147  */
1148 static void
1149 mesh_reply_proc (void *cls,
1150                    enum GNUNET_BLOCK_Type type,
1151                    struct GNUNET_TIME_Absolute expiration,
1152                    size_t data_size,
1153                    const void *data)
1154 {
1155   struct GSF_PendingRequest *pr = cls;
1156   struct ProcessReplyClosure prq;
1157   struct GNUNET_HashCode query;
1158
1159   pr->mesh_request = NULL;
1160   if (GNUNET_BLOCK_TYPE_ANY == type)
1161   {
1162     GNUNET_break (NULL == data);
1163     GNUNET_break (0 == data_size);
1164     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1165                 "Error retrieiving block via mesh\n");
1166     pr->mesh_retry_count++;
1167     if (pr->mesh_retry_count >= MESH_RETRY_MAX)
1168       return; /* give up on mesh */
1169     /* retry -- without delay, as this is non-anonymous
1170        and mesh/mesh connect will take some time anyway */
1171     pr->mesh_request = GSF_mesh_query (pr->public_data.target,
1172                                            &pr->public_data.query,
1173                                            pr->public_data.type,
1174                                            &mesh_reply_proc,
1175                                            pr);
1176     return;
1177   }
1178   if (GNUNET_YES !=
1179       GNUNET_BLOCK_get_key (GSF_block_ctx,
1180                             type,
1181                             data, data_size, &query))
1182   {
1183     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1184                 "Failed to derive key for block of type %d\n",
1185                 (int) type);
1186     GNUNET_break_op (0);
1187     return;
1188   }
1189   GNUNET_STATISTICS_update (GSF_stats,
1190                             gettext_noop ("# Replies received from MESH"), 1,
1191                             GNUNET_NO);
1192   memset (&prq, 0, sizeof (prq));
1193   prq.data = data;
1194   prq.expiration = expiration;
1195   /* do not allow migrated content to live longer than 1 year */
1196   prq.expiration = GNUNET_TIME_absolute_min (GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_YEARS),
1197                                              prq.expiration);
1198   prq.size = data_size;
1199   prq.type = type;
1200   process_reply (&prq, &query, pr);
1201 }
1202
1203
1204 /**
1205  * Consider downloading via mesh (if possible)
1206  *
1207  * @param pr the pending request to process
1208  */
1209 void
1210 GSF_mesh_lookup_ (struct GSF_PendingRequest *pr)
1211 {
1212   if (0 != pr->public_data.anonymity_level)
1213     return;
1214   if (0 == pr->public_data.target)
1215   {
1216     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1217                 "Cannot do mesh-based download, target peer not known\n");
1218     return;
1219   }
1220   if (NULL != pr->mesh_request)
1221     return;
1222   pr->mesh_request = GSF_mesh_query (pr->public_data.target,
1223                                      &pr->public_data.query,
1224                                      pr->public_data.type,
1225                                      &mesh_reply_proc,
1226                                      pr);
1227 }
1228
1229
1230 /**
1231  * Task that issues a warning if the datastore lookup takes too long.
1232  *
1233  * @param cls the 'struct GSF_PendingRequest'
1234  * @param tc task context
1235  */
1236 static void
1237 warn_delay_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1238 {
1239   struct GSF_PendingRequest *pr = cls;
1240
1241   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1242               _("Datastore lookup already took %s!\n"),
1243               GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (pr->qe_start), GNUNET_YES));
1244   pr->warn_task =
1245       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, &warn_delay_task,
1246                                     pr);
1247 }
1248
1249
1250 /**
1251  * Task that issues a warning if the datastore lookup takes too long.
1252  *
1253  * @param cls the 'struct GSF_PendingRequest'
1254  * @param tc task context
1255  */
1256 static void
1257 odc_warn_delay_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1258 {
1259   struct GSF_PendingRequest *pr = cls;
1260
1261   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1262               _("On-demand lookup already took %s!\n"),
1263               GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (pr->qe_start), GNUNET_YES));
1264   pr->warn_task =
1265       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1266                                     &odc_warn_delay_task, pr);
1267 }
1268
1269
1270 /**
1271  * We're processing (local) results for a search request
1272  * from another peer.  Pass applicable results to the
1273  * peer and if we are done either clean up (operation
1274  * complete) or forward to other peers (more results possible).
1275  *
1276  * @param cls our closure (struct PendingRequest)
1277  * @param key key for the content
1278  * @param size number of bytes in data
1279  * @param data content stored
1280  * @param type type of the content
1281  * @param priority priority of the content
1282  * @param anonymity anonymity-level for the content
1283  * @param expiration expiration time for the content
1284  * @param uid unique identifier for the datum;
1285  *        maybe 0 if no unique identifier is available
1286  */
1287 static void
1288 process_local_reply (void *cls, const struct GNUNET_HashCode * key, size_t size,
1289                      const void *data, enum GNUNET_BLOCK_Type type,
1290                      uint32_t priority, uint32_t anonymity,
1291                      struct GNUNET_TIME_Absolute expiration, uint64_t uid)
1292 {
1293   struct GSF_PendingRequest *pr = cls;
1294   GSF_LocalLookupContinuation cont;
1295   struct ProcessReplyClosure prq;
1296   struct GNUNET_HashCode query;
1297   unsigned int old_rf;
1298
1299   GNUNET_SCHEDULER_cancel (pr->warn_task);
1300   pr->warn_task = GNUNET_SCHEDULER_NO_TASK;
1301   if (NULL != pr->qe)
1302   {
1303     pr->qe = NULL;
1304     if (NULL == key)
1305     {
1306 #if INSANE_STATISTICS
1307       GNUNET_STATISTICS_update (GSF_stats,
1308                                 gettext_noop
1309                                 ("# Datastore lookups concluded (no results)"),
1310                                 1, GNUNET_NO);
1311 #endif
1312     }
1313     if (GNUNET_NO == pr->have_first_uid)
1314     {
1315       pr->first_uid = uid;
1316       pr->have_first_uid = 1;
1317     }
1318     else
1319     {
1320       if ((uid == pr->first_uid) && (key != NULL))
1321       {
1322         GNUNET_STATISTICS_update (GSF_stats,
1323                                   gettext_noop
1324                                   ("# Datastore lookups concluded (seen all)"),
1325                                   1, GNUNET_NO);
1326         key = NULL;             /* all replies seen! */
1327       }
1328       pr->have_first_uid++;
1329       if ((pr->have_first_uid > MAX_RESULTS) && (key != NULL))
1330       {
1331         GNUNET_STATISTICS_update (GSF_stats,
1332                                   gettext_noop
1333                                   ("# Datastore lookups aborted (more than MAX_RESULTS)"),
1334                                   1, GNUNET_NO);
1335         key = NULL;             /* all replies seen! */
1336       }
1337     }
1338   }
1339   if (NULL == key)
1340   {
1341     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1342                 "No further local responses available.\n");
1343 #if INSANE_STATISTICS
1344     if ((pr->public_data.type == GNUNET_BLOCK_TYPE_FS_DBLOCK) ||
1345         (pr->public_data.type == GNUNET_BLOCK_TYPE_FS_IBLOCK))
1346       GNUNET_STATISTICS_update (GSF_stats,
1347                                 gettext_noop
1348                                 ("# requested DBLOCK or IBLOCK not found"), 1,
1349                                 GNUNET_NO);
1350 #endif
1351     goto check_error_and_continue;
1352   }
1353   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1354               "Received reply for `%s' of type %d with UID %llu from datastore.\n",
1355               GNUNET_h2s (key), type, (unsigned long long) uid);
1356   if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
1357   {
1358     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1359                 "Found ONDEMAND block, performing on-demand encoding\n");
1360     GNUNET_STATISTICS_update (GSF_stats,
1361                               gettext_noop
1362                               ("# on-demand blocks matched requests"), 1,
1363                               GNUNET_NO);
1364     pr->qe_start = GNUNET_TIME_absolute_get ();
1365     pr->warn_task =
1366         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1367                                       &odc_warn_delay_task, pr);
1368     if (GNUNET_OK ==
1369         GNUNET_FS_handle_on_demand_block (key, size, data, type, priority,
1370                                           anonymity, expiration, uid,
1371                                           &process_local_reply, pr))
1372     {
1373       GNUNET_STATISTICS_update (GSF_stats,
1374                                 gettext_noop
1375                                 ("# on-demand lookups performed successfully"),
1376                                 1, GNUNET_NO);
1377       return;                   /* we're done */
1378     }
1379     GNUNET_STATISTICS_update (GSF_stats,
1380                               gettext_noop ("# on-demand lookups failed"), 1,
1381                               GNUNET_NO);
1382     GNUNET_SCHEDULER_cancel (pr->warn_task);
1383     pr->warn_task =
1384         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1385                                       &warn_delay_task, pr);
1386     pr->qe =
1387         GNUNET_DATASTORE_get_key (GSF_dsh, pr->local_result_offset - 1,
1388                                   &pr->public_data.query,
1389                                   pr->public_data.type ==
1390                                   GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1391                                   GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1392                                   (0 !=
1393                                    (GSF_PRO_PRIORITY_UNLIMITED &
1394                                     pr->public_data.options)) ? UINT_MAX : 1
1395                                   /* queue priority */ ,
1396                                   (0 !=
1397                                    (GSF_PRO_PRIORITY_UNLIMITED &
1398                                     pr->public_data.options)) ? UINT_MAX :
1399                                   GSF_datastore_queue_size
1400                                   /* max queue size */ ,
1401                                   GNUNET_TIME_UNIT_FOREVER_REL,
1402                                   &process_local_reply, pr);
1403     if (NULL != pr->qe)
1404       return;                   /* we're done */
1405     GNUNET_STATISTICS_update (GSF_stats,
1406                               gettext_noop
1407                               ("# Datastore lookups concluded (error queueing)"),
1408                               1, GNUNET_NO);
1409     goto check_error_and_continue;
1410   }
1411   old_rf = pr->public_data.results_found;
1412   memset (&prq, 0, sizeof (prq));
1413   prq.data = data;
1414   prq.expiration = expiration;
1415   prq.size = size;
1416   if (GNUNET_OK !=
1417       GNUNET_BLOCK_get_key (GSF_block_ctx, type, data, size, &query))
1418   {
1419     GNUNET_break (0);
1420     GNUNET_DATASTORE_remove (GSF_dsh, key, size, data, -1, -1,
1421                              GNUNET_TIME_UNIT_FOREVER_REL, NULL, NULL);
1422     pr->qe_start = GNUNET_TIME_absolute_get ();
1423     pr->warn_task =
1424         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1425                                       &warn_delay_task, pr);
1426     pr->qe =
1427         GNUNET_DATASTORE_get_key (GSF_dsh, pr->local_result_offset - 1,
1428                                   &pr->public_data.query,
1429                                   pr->public_data.type ==
1430                                   GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1431                                   GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1432                                   (0 !=
1433                                    (GSF_PRO_PRIORITY_UNLIMITED &
1434                                     pr->public_data.options)) ? UINT_MAX : 1
1435                                   /* queue priority */ ,
1436                                   (0 !=
1437                                    (GSF_PRO_PRIORITY_UNLIMITED &
1438                                     pr->public_data.options)) ? UINT_MAX :
1439                                   GSF_datastore_queue_size
1440                                   /* max queue size */ ,
1441                                   GNUNET_TIME_UNIT_FOREVER_REL,
1442                                   &process_local_reply, pr);
1443     if (pr->qe == NULL)
1444     {
1445       GNUNET_STATISTICS_update (GSF_stats,
1446                                 gettext_noop
1447                                 ("# Datastore lookups concluded (error queueing)"),
1448                                 1, GNUNET_NO);
1449       goto check_error_and_continue;
1450     }
1451     return;
1452   }
1453   prq.type = type;
1454   prq.priority = priority;
1455   prq.request_found = GNUNET_NO;
1456   prq.anonymity_level = anonymity;
1457   if ((old_rf == 0) && (pr->public_data.results_found == 0))
1458     GSF_update_datastore_delay_ (pr->public_data.start_time);
1459   process_reply (&prq, key, pr);
1460   pr->local_result = prq.eval;
1461   if (prq.eval == GNUNET_BLOCK_EVALUATION_OK_LAST)
1462   {
1463     GNUNET_STATISTICS_update (GSF_stats,
1464                               gettext_noop
1465                               ("# Datastore lookups concluded (found last result)"),
1466                               1, GNUNET_NO);
1467     goto check_error_and_continue;
1468   }
1469   if ((0 == (GSF_PRO_PRIORITY_UNLIMITED & pr->public_data.options)) &&
1470       ((GNUNET_YES == GSF_test_get_load_too_high_ (0)) ||
1471        (pr->public_data.results_found > 5 + 2 * pr->public_data.priority)))
1472   {
1473     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Load too high, done with request\n");
1474     GNUNET_STATISTICS_update (GSF_stats,
1475                               gettext_noop
1476                               ("# Datastore lookups concluded (load too high)"),
1477                               1, GNUNET_NO);
1478     goto check_error_and_continue;
1479   }
1480   pr->qe_start = GNUNET_TIME_absolute_get ();
1481   pr->warn_task =
1482       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, &warn_delay_task,
1483                                     pr);
1484   pr->qe =
1485       GNUNET_DATASTORE_get_key (GSF_dsh, pr->local_result_offset++,
1486                                 &pr->public_data.query,
1487                                 pr->public_data.type ==
1488                                 GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1489                                 GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1490                                 (0 !=
1491                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1492                                   public_data.options)) ? UINT_MAX : 1
1493                                 /* queue priority */ ,
1494                                 (0 !=
1495                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1496                                   public_data.options)) ? UINT_MAX :
1497                                 GSF_datastore_queue_size
1498                                 /* max queue size */ ,
1499                                 GNUNET_TIME_UNIT_FOREVER_REL,
1500                                 &process_local_reply, pr);
1501   /* check if we successfully queued another datastore request;
1502    * if so, return, otherwise call our continuation (if we have
1503    * any) */
1504 check_error_and_continue:
1505   if (NULL != pr->qe)
1506     return;
1507   if (GNUNET_SCHEDULER_NO_TASK != pr->warn_task)
1508   {
1509     GNUNET_SCHEDULER_cancel (pr->warn_task);
1510     pr->warn_task = GNUNET_SCHEDULER_NO_TASK;
1511   }
1512   if (NULL == (cont = pr->llc_cont))
1513     return;                     /* no continuation */
1514   pr->llc_cont = NULL;
1515   cont (pr->llc_cont_cls, pr, pr->local_result);
1516 }
1517
1518
1519 /**
1520  * Is the given target a legitimate peer for forwarding the given request?
1521  *
1522  * @param pr request
1523  * @param target
1524  * @return GNUNET_YES if this request could be forwarded to the given peer
1525  */
1526 int
1527 GSF_pending_request_test_target_ (struct GSF_PendingRequest *pr,
1528                                   const struct GNUNET_PeerIdentity *target)
1529 {
1530   struct GNUNET_PeerIdentity pi;
1531
1532   if (0 == pr->origin_pid)
1533     return GNUNET_YES;
1534   GNUNET_PEER_resolve (pr->origin_pid, &pi);
1535   return (0 ==
1536           memcmp (&pi, target,
1537                   sizeof (struct GNUNET_PeerIdentity))) ? GNUNET_NO :
1538       GNUNET_YES;
1539 }
1540
1541
1542 /**
1543  * Look up the request in the local datastore.
1544  *
1545  * @param pr the pending request to process
1546  * @param cont function to call at the end
1547  * @param cont_cls closure for cont
1548  */
1549 void
1550 GSF_local_lookup_ (struct GSF_PendingRequest *pr,
1551                    GSF_LocalLookupContinuation cont, void *cont_cls)
1552 {
1553   GNUNET_assert (NULL == pr->gh);
1554   GNUNET_assert (NULL == pr->mesh_request);
1555   GNUNET_assert (NULL == pr->llc_cont);
1556   pr->llc_cont = cont;
1557   pr->llc_cont_cls = cont_cls;
1558   pr->qe_start = GNUNET_TIME_absolute_get ();
1559   pr->warn_task =
1560       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, &warn_delay_task,
1561                                     pr);
1562 #if INSANE_STATISTICS
1563   GNUNET_STATISTICS_update (GSF_stats,
1564                             gettext_noop ("# Datastore lookups initiated"), 1,
1565                             GNUNET_NO);
1566 #endif
1567   pr->qe =
1568       GNUNET_DATASTORE_get_key (GSF_dsh, pr->local_result_offset++,
1569                                 &pr->public_data.query,
1570                                 pr->public_data.type ==
1571                                 GNUNET_BLOCK_TYPE_FS_DBLOCK ?
1572                                 GNUNET_BLOCK_TYPE_ANY : pr->public_data.type,
1573                                 (0 !=
1574                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1575                                   public_data.options)) ? UINT_MAX : 1
1576                                 /* queue priority */ ,
1577                                 (0 !=
1578                                  (GSF_PRO_PRIORITY_UNLIMITED & pr->
1579                                   public_data.options)) ? UINT_MAX :
1580                                 GSF_datastore_queue_size
1581                                 /* max queue size */ ,
1582                                 GNUNET_TIME_UNIT_FOREVER_REL,
1583                                 &process_local_reply, pr);
1584   if (NULL != pr->qe)
1585     return;
1586   GNUNET_STATISTICS_update (GSF_stats,
1587                             gettext_noop
1588                             ("# Datastore lookups concluded (error queueing)"),
1589                             1, GNUNET_NO);
1590   GNUNET_SCHEDULER_cancel (pr->warn_task);
1591   pr->warn_task = GNUNET_SCHEDULER_NO_TASK;
1592   pr->llc_cont = NULL;
1593   if (NULL != cont)
1594     cont (cont_cls, pr, pr->local_result);
1595 }
1596
1597
1598
1599 /**
1600  * Handle P2P "CONTENT" message.  Checks that the message is
1601  * well-formed and then checks if there are any pending requests for
1602  * this content and possibly passes it on (to local clients or other
1603  * peers).  Does NOT perform migration (content caching at this peer).
1604  *
1605  * @param cp the other peer involved (sender or receiver, NULL
1606  *        for loopback messages where we are both sender and receiver)
1607  * @param message the actual message
1608  * @return GNUNET_OK if the message was well-formed,
1609  *         GNUNET_SYSERR if the message was malformed (close connection,
1610  *         do not cache under any circumstances)
1611  */
1612 int
1613 GSF_handle_p2p_content_ (struct GSF_ConnectedPeer *cp,
1614                          const struct GNUNET_MessageHeader *message)
1615 {
1616   const struct PutMessage *put;
1617   uint16_t msize;
1618   size_t dsize;
1619   enum GNUNET_BLOCK_Type type;
1620   struct GNUNET_TIME_Absolute expiration;
1621   struct GNUNET_HashCode query;
1622   struct ProcessReplyClosure prq;
1623   struct GNUNET_TIME_Relative block_time;
1624   double putl;
1625   struct PutMigrationContext *pmc;
1626
1627   msize = ntohs (message->size);
1628   if (msize < sizeof (struct PutMessage))
1629   {
1630     GNUNET_break_op (0);
1631     return GNUNET_SYSERR;
1632   }
1633   put = (const struct PutMessage *) message;
1634   dsize = msize - sizeof (struct PutMessage);
1635   type = ntohl (put->type);
1636   expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
1637   /* do not allow migrated content to live longer than 1 year */
1638   expiration = GNUNET_TIME_absolute_min (GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_YEARS),
1639                                          expiration);
1640   if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
1641     return GNUNET_SYSERR;
1642   if (GNUNET_OK !=
1643       GNUNET_BLOCK_get_key (GSF_block_ctx, type, &put[1], dsize, &query))
1644   {
1645     GNUNET_break_op (0);
1646     return GNUNET_SYSERR;
1647   }
1648   GNUNET_STATISTICS_update (GSF_stats,
1649                             gettext_noop ("# GAP PUT messages received"), 1,
1650                             GNUNET_NO);
1651   /* now, lookup 'query' */
1652   prq.data = (const void *) &put[1];
1653   prq.sender = cp;
1654   prq.size = dsize;
1655   prq.type = type;
1656   prq.expiration = expiration;
1657   prq.priority = 0;
1658   prq.anonymity_level = UINT32_MAX;
1659   prq.request_found = GNUNET_NO;
1660   GNUNET_CONTAINER_multihashmap_get_multiple (pr_map, &query, &process_reply,
1661                                               &prq);
1662   if (NULL != cp)
1663   {
1664     GSF_connected_peer_change_preference_ (cp,
1665                                            CONTENT_BANDWIDTH_VALUE +
1666                                            1000 * prq.priority);
1667     GSF_get_peer_performance_data_ (cp)->respect += prq.priority;
1668   }
1669   if ((GNUNET_YES == active_to_migration) &&
1670       (NULL != cp) &&
1671       (GNUNET_NO == test_put_load_too_high (prq.priority)))
1672   {
1673     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1674                 "Replicating result for query `%s' with priority %u\n",
1675                 GNUNET_h2s (&query), prq.priority);
1676     pmc = GNUNET_malloc (sizeof (struct PutMigrationContext));
1677     pmc->start = GNUNET_TIME_absolute_get ();
1678     pmc->requested = prq.request_found;
1679     GNUNET_assert (0 != GSF_get_peer_performance_data_ (cp)->pid);
1680     GNUNET_PEER_resolve (GSF_get_peer_performance_data_ (cp)->pid,
1681                          &pmc->origin);
1682     if (NULL ==
1683         GNUNET_DATASTORE_put (GSF_dsh, 0, &query, dsize, &put[1], type,
1684                               prq.priority, 1 /* anonymity */ ,
1685                               0 /* replication */ ,
1686                               expiration, 1 + prq.priority, MAX_DATASTORE_QUEUE,
1687                               GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1688                               &put_migration_continuation, pmc))
1689     {
1690       put_migration_continuation (pmc, GNUNET_SYSERR, GNUNET_TIME_UNIT_ZERO_ABS, NULL);
1691     }
1692   }
1693   else if (NULL != cp)
1694   {
1695     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1696                 "Choosing not to keep content `%s' (%d/%d)\n",
1697                 GNUNET_h2s (&query), active_to_migration,
1698                 test_put_load_too_high (prq.priority));
1699   }
1700   putl = GNUNET_LOAD_get_load (datastore_put_load);
1701   if ( (NULL != cp) &&
1702        (GNUNET_NO == prq.request_found) &&
1703        ( (GNUNET_YES != active_to_migration) ||
1704          (putl > 2.5 * (1 + prq.priority)) ) )
1705   {
1706     if (GNUNET_YES != active_to_migration)
1707       putl = 1.0 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 5);
1708     block_time =
1709         GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1710                                        5000 +
1711                                        GNUNET_CRYPTO_random_u32
1712                                        (GNUNET_CRYPTO_QUALITY_WEAK,
1713                                         (unsigned int) (60000 * putl * putl)));
1714     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1715                 "Asking to stop migration for %s because of load %f and events %d/%d\n",
1716                 GNUNET_STRINGS_relative_time_to_string (block_time,
1717                                                         GNUNET_YES),
1718                 putl,
1719                 active_to_migration,
1720                 (GNUNET_NO == prq.request_found));
1721     GSF_block_peer_migration_ (cp, GNUNET_TIME_relative_to_absolute (block_time));
1722   }
1723   return GNUNET_OK;
1724 }
1725
1726
1727 /**
1728  * Setup the subsystem.
1729  */
1730 void
1731 GSF_pending_request_init_ ()
1732 {
1733   if (GNUNET_OK !=
1734       GNUNET_CONFIGURATION_get_value_number (GSF_cfg, "fs",
1735                                              "MAX_PENDING_REQUESTS",
1736                                              &max_pending_requests))
1737   {
1738     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_INFO,
1739                                "fs", "MAX_PENDING_REQUESTS");
1740   }
1741   active_to_migration =
1742       GNUNET_CONFIGURATION_get_value_yesno (GSF_cfg, "FS", "CONTENT_CACHING");
1743   datastore_put_load = GNUNET_LOAD_value_init (DATASTORE_LOAD_AUTODECLINE);
1744   pr_map = GNUNET_CONTAINER_multihashmap_create (32 * 1024, GNUNET_YES);
1745   requests_by_expiration_heap =
1746       GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1747 }
1748
1749
1750 /**
1751  * Shutdown the subsystem.
1752  */
1753 void
1754 GSF_pending_request_done_ ()
1755 {
1756   GNUNET_CONTAINER_multihashmap_iterate (pr_map, &clean_request, NULL);
1757   GNUNET_CONTAINER_multihashmap_destroy (pr_map);
1758   pr_map = NULL;
1759   GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
1760   requests_by_expiration_heap = NULL;
1761   GNUNET_LOAD_value_free (datastore_put_load);
1762   datastore_put_load = NULL;
1763 }
1764
1765
1766 /* end of gnunet-service-fs_pr.c */