adding single location for no_forcestart configuration list
[oweals/gnunet.git] / src / fs / fs_search.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001-2014 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 Tem ple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20 /**
21  * @file fs/fs_search.c
22  * @brief Helper functions for searching.
23  * @author Christian Grothoff
24  */
25 #include "platform.h"
26 #include "gnunet_constants.h"
27 #include "gnunet_fs_service.h"
28 #include "gnunet_protocols.h"
29 #include "fs_api.h"
30 #include "fs_publish_ublock.h"
31
32
33 /**
34  * Number of availability trials we perform per search result.
35  */
36 #define AVAILABILITY_TRIALS_MAX 8
37
38 /**
39  * Fill in all of the generic fields for a search event and
40  * call the callback.
41  *
42  * @param pi structure to fill in
43  * @param h file-sharing handle
44  * @param sc overall search context
45  * @return value returned by the callback
46  */
47 void *
48 GNUNET_FS_search_make_status_ (struct GNUNET_FS_ProgressInfo *pi,
49                                struct GNUNET_FS_Handle *h,
50                                struct GNUNET_FS_SearchContext *sc)
51 {
52   void *ret;
53
54   pi->value.search.sc = sc;
55   pi->value.search.cctx = (NULL != sc) ? sc->client_info : NULL;
56   pi->value.search.pctx =
57     ((NULL == sc) || (NULL == sc->psearch_result))
58     ? NULL
59     : sc->psearch_result->client_info;
60   pi->value.search.query = (NULL != sc) ? sc->uri : NULL;
61   pi->value.search.duration = (NULL != sc)
62     ? GNUNET_TIME_absolute_get_duration (sc->start_time)
63     : GNUNET_TIME_UNIT_ZERO;
64   pi->value.search.anonymity = (NULL != sc) ? sc->anonymity : 0;
65   pi->fsh = h;
66   ret = h->upcb (h->upcb_cls, pi);
67   return ret;
68 }
69
70
71 /**
72  * Check if the given result is identical to the given URI.
73  *
74  * @param cls points to the URI we check against
75  * @param key not used
76  * @param value a `struct GNUNET_FS_SearchResult` who's URI we
77  *        should compare with
78  * @return #GNUNET_SYSERR if the result is present,
79  *         #GNUNET_OK otherwise
80  */
81 static int
82 test_result_present (void *cls,
83                      const struct GNUNET_HashCode * key,
84                      void *value)
85 {
86   const struct GNUNET_FS_Uri *uri = cls;
87   struct GNUNET_FS_SearchResult *sr = value;
88
89   if (GNUNET_FS_uri_test_equal (uri, sr->uri))
90     return GNUNET_SYSERR;
91   return GNUNET_OK;
92 }
93
94
95 /**
96  * We've found a new CHK result.  Let the client
97  * know about it.
98  *
99  * @param sc the search context
100  * @param sr the specific result
101  */
102 static void
103 notify_client_chk_result (struct GNUNET_FS_SearchContext *sc,
104                           struct GNUNET_FS_SearchResult *sr)
105 {
106   struct GNUNET_FS_ProgressInfo pi;
107
108   pi.status = GNUNET_FS_STATUS_SEARCH_RESULT;
109   pi.value.search.specifics.result.meta = sr->meta;
110   pi.value.search.specifics.result.uri = sr->uri;
111   pi.value.search.specifics.result.result = sr;
112   pi.value.search.specifics.result.applicability_rank = sr->optional_support;
113   sr->client_info = GNUNET_FS_search_make_status_ (&pi, sc->h, sc);
114 }
115
116
117 /**
118  * We've found new information about an existing CHK result.  Let the
119  * client know about it.
120  *
121  * @param sc the search context
122  * @param sr the specific result
123  */
124 static void
125 notify_client_chk_update (struct GNUNET_FS_SearchContext *sc,
126                           struct GNUNET_FS_SearchResult *sr)
127 {
128   struct GNUNET_FS_ProgressInfo pi;
129
130   pi.status = GNUNET_FS_STATUS_SEARCH_UPDATE;
131   pi.value.search.specifics.update.cctx = sr->client_info;
132   pi.value.search.specifics.update.meta = sr->meta;
133   pi.value.search.specifics.update.uri = sr->uri;
134   pi.value.search.specifics.update.availability_rank =
135       2 * sr->availability_success - sr->availability_trials;
136   pi.value.search.specifics.update.availability_certainty =
137       sr->availability_trials;
138   pi.value.search.specifics.update.applicability_rank = sr->optional_support;
139   pi.value.search.specifics.update.current_probe_time
140     = GNUNET_TIME_absolute_get_duration (sr->probe_active_time);
141   sr->client_info = GNUNET_FS_search_make_status_ (&pi, sc->h, sc);
142 }
143
144
145 /**
146  * Context for "get_result_present".
147  */
148 struct GetResultContext
149 {
150   /**
151    * The URI we're looking for.
152    */
153   const struct GNUNET_FS_Uri *uri;
154
155   /**
156    * Where to store a pointer to the search
157    * result struct if we found a match.
158    */
159   struct GNUNET_FS_SearchResult *sr;
160 };
161
162
163 /**
164  * Check if the given result is identical to the given URI and if so
165  * return it.
166  *
167  * @param cls a `struct GetResultContext`
168  * @param key not used
169  * @param value a `struct GNUNET_FS_SearchResult` who's URI we
170  *        should compare with
171  * @return #GNUNET_OK
172  */
173 static int
174 get_result_present (void *cls, const struct GNUNET_HashCode * key, void *value)
175 {
176   struct GetResultContext *grc = cls;
177   struct GNUNET_FS_SearchResult *sr = value;
178
179   if (GNUNET_FS_uri_test_equal (grc->uri, sr->uri))
180     grc->sr = sr;
181   return GNUNET_OK;
182 }
183
184
185 /**
186  * Signal result of last probe to client and then schedule next
187  * probe.
188  *
189  * @param sr search result to signal for
190  */
191 static void
192 signal_probe_result (struct GNUNET_FS_SearchResult *sr)
193 {
194   struct GNUNET_FS_ProgressInfo pi;
195
196   pi.status = GNUNET_FS_STATUS_SEARCH_UPDATE;
197   pi.value.search.specifics.update.cctx = sr->client_info;
198   pi.value.search.specifics.update.meta = sr->meta;
199   pi.value.search.specifics.update.uri = sr->uri;
200   pi.value.search.specifics.update.availability_rank
201     = 2 * sr->availability_success - sr->availability_trials;
202   pi.value.search.specifics.update.availability_certainty
203     = sr->availability_trials;
204   pi.value.search.specifics.update.applicability_rank = sr->optional_support;
205   pi.value.search.specifics.update.current_probe_time
206     = GNUNET_TIME_absolute_get_duration (sr->probe_active_time);
207   sr->client_info = GNUNET_FS_search_make_status_ (&pi, sr->h, sr->sc);
208   GNUNET_FS_search_start_probe_ (sr);
209 }
210
211
212 /**
213  * Handle the case where we have failed to receive a response for our probe.
214  *
215  * @param cls our `struct GNUNET_FS_SearchResult *`
216  * @param tc scheduler context
217  */
218 static void
219 probe_failure_handler (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
220 {
221   struct GNUNET_FS_SearchResult *sr = cls;
222
223   sr->probe_cancel_task = GNUNET_SCHEDULER_NO_TASK;
224   sr->availability_trials++;
225   GNUNET_FS_download_stop (sr->probe_ctx, GNUNET_YES);
226   sr->probe_ctx = NULL;
227   if (GNUNET_SCHEDULER_NO_TASK != sr->probe_ping_task)
228   {
229     GNUNET_SCHEDULER_cancel (sr->probe_ping_task);
230     sr->probe_ping_task = GNUNET_SCHEDULER_NO_TASK;
231   }
232   GNUNET_FS_search_result_sync_ (sr);
233   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
234               "Probe #%u for search result %p failed\n",
235               sr->availability_trials,
236               sr);
237   signal_probe_result (sr);
238 }
239
240
241 /**
242  * Handle the case where we have gotten a response for our probe.
243  *
244  * @param cls our `struct GNUNET_FS_SearchResult *`
245  * @param tc scheduler context
246  */
247 static void
248 probe_success_handler (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
249 {
250   struct GNUNET_FS_SearchResult *sr = cls;
251
252   sr->probe_cancel_task = GNUNET_SCHEDULER_NO_TASK;
253   sr->availability_trials++;
254   sr->availability_success++;
255   GNUNET_FS_download_stop (sr->probe_ctx, GNUNET_YES);
256   sr->probe_ctx = NULL;
257   if (GNUNET_SCHEDULER_NO_TASK != sr->probe_ping_task)
258   {
259     GNUNET_SCHEDULER_cancel (sr->probe_ping_task);
260     sr->probe_ping_task = GNUNET_SCHEDULER_NO_TASK;
261   }
262   GNUNET_FS_search_result_sync_ (sr);
263   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
264               "Probe #%u for search result %p succeeded\n",
265               sr->availability_trials,
266               sr);
267   signal_probe_result (sr);
268 }
269
270
271 /**
272  * Notification of FS that a search probe has made progress.
273  * This function is used INSTEAD of the client's event handler
274  * for downloads where the #GNUNET_FS_DOWNLOAD_IS_PROBE flag is set.
275  *
276  * @param cls closure, always NULL (!), actual closure
277  *        is in the client-context of the info struct
278  * @param info details about the event, specifying the event type
279  *        and various bits about the event
280  * @return client-context (for the next progress call
281  *         for this operation; should be set to NULL for
282  *         SUSPEND and STOPPED events).  The value returned
283  *         will be passed to future callbacks in the respective
284  *         field in the `struct GNUNET_FS_ProgressInfo`.
285  */
286 void *
287 GNUNET_FS_search_probe_progress_ (void *cls,
288                                   const struct GNUNET_FS_ProgressInfo *info)
289 {
290   struct GNUNET_FS_SearchResult *sr = info->value.download.cctx;
291   struct GNUNET_TIME_Relative dur;
292
293   switch (info->status)
294   {
295   case GNUNET_FS_STATUS_DOWNLOAD_START:
296     /* ignore */
297     break;
298   case GNUNET_FS_STATUS_DOWNLOAD_RESUME:
299     /* probes should never be resumed */
300     GNUNET_assert (0);
301     break;
302   case GNUNET_FS_STATUS_DOWNLOAD_SUSPEND:
303     /* probes should never be suspended */
304     GNUNET_break (0);
305     break;
306   case GNUNET_FS_STATUS_DOWNLOAD_PROGRESS:
307     /* ignore */
308     break;
309   case GNUNET_FS_STATUS_DOWNLOAD_ERROR:
310     if (GNUNET_SCHEDULER_NO_TASK != sr->probe_cancel_task)
311     {
312       GNUNET_SCHEDULER_cancel (sr->probe_cancel_task);
313       sr->probe_cancel_task = GNUNET_SCHEDULER_NO_TASK;
314     }
315     sr->probe_cancel_task =
316         GNUNET_SCHEDULER_add_delayed (sr->remaining_probe_time,
317                                       &probe_failure_handler, sr);
318     break;
319   case GNUNET_FS_STATUS_DOWNLOAD_COMPLETED:
320     if (GNUNET_SCHEDULER_NO_TASK != sr->probe_cancel_task)
321     {
322       GNUNET_SCHEDULER_cancel (sr->probe_cancel_task);
323       sr->probe_cancel_task = GNUNET_SCHEDULER_NO_TASK;
324     }
325     sr->probe_cancel_task =
326         GNUNET_SCHEDULER_add_now (&probe_success_handler, sr);
327     break;
328   case GNUNET_FS_STATUS_DOWNLOAD_STOPPED:
329     if (GNUNET_SCHEDULER_NO_TASK != sr->probe_cancel_task)
330     {
331       GNUNET_SCHEDULER_cancel (sr->probe_cancel_task);
332       sr->probe_cancel_task = GNUNET_SCHEDULER_NO_TASK;
333     }
334     sr = NULL;
335     break;
336   case GNUNET_FS_STATUS_DOWNLOAD_ACTIVE:
337     if (GNUNET_SCHEDULER_NO_TASK == sr->probe_cancel_task)
338     {
339       sr->probe_active_time = GNUNET_TIME_absolute_get ();
340       sr->probe_cancel_task =
341         GNUNET_SCHEDULER_add_delayed (sr->remaining_probe_time,
342                                       &probe_failure_handler, sr);
343     }
344     break;
345   case GNUNET_FS_STATUS_DOWNLOAD_INACTIVE:
346     if (GNUNET_SCHEDULER_NO_TASK != sr->probe_cancel_task)
347     {
348       GNUNET_SCHEDULER_cancel (sr->probe_cancel_task);
349       sr->probe_cancel_task = GNUNET_SCHEDULER_NO_TASK;
350     }
351     dur = GNUNET_TIME_absolute_get_duration (sr->probe_active_time);
352     sr->remaining_probe_time =
353         GNUNET_TIME_relative_subtract (sr->remaining_probe_time, dur);
354     if (0 == sr->remaining_probe_time.rel_value_us)
355       sr->probe_cancel_task =
356         GNUNET_SCHEDULER_add_now (&probe_failure_handler, sr);
357     GNUNET_FS_search_result_sync_ (sr);
358     break;
359   default:
360     GNUNET_break (0);
361     return NULL;
362   }
363   return sr;
364 }
365
366
367 /**
368  * Task run periodically to remind clients that a probe is active.
369  *
370  * @param cls the 'struct GNUNET_FS_SearchResult' that we are probing for
371  * @param tc scheduler context
372  */
373 static void
374 probe_ping_task (void *cls,
375                  const struct GNUNET_SCHEDULER_TaskContext *tc)
376 {
377   struct GNUNET_FS_SearchResult *sr = cls;
378
379   signal_probe_result (sr);
380   sr->probe_ping_task
381     = GNUNET_SCHEDULER_add_delayed (GNUNET_FS_PROBE_UPDATE_FREQUENCY,
382                                     &probe_ping_task,
383                                     sr);
384 }
385
386
387 /**
388  * Start download probes for the given search result.
389  *
390  * @param sr the search result
391  */
392 void
393 GNUNET_FS_search_start_probe_ (struct GNUNET_FS_SearchResult *sr)
394 {
395   uint64_t off;
396   uint64_t len;
397
398   if (NULL != sr->probe_ctx)
399     return;
400   if (NULL != sr->download)
401     return;
402   if (0 == (sr->h->flags & GNUNET_FS_FLAGS_DO_PROBES))
403     return;
404   if (sr->availability_trials > AVAILABILITY_TRIALS_MAX)
405     return;
406   if ( (GNUNET_FS_URI_CHK != sr->uri->type) && (GNUNET_FS_URI_LOC != sr->uri->type))
407     return;
408   len = GNUNET_FS_uri_chk_get_file_size (sr->uri);
409   if (0 == len)
410     return;
411   if ((len <= DBLOCK_SIZE) && (sr->availability_success > 0))
412     return;
413   off = len / DBLOCK_SIZE;
414   if (off > 0)
415     off = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, off);
416   off *= DBLOCK_SIZE;
417   if (len - off < DBLOCK_SIZE)
418     len = len - off;
419   else
420     len = DBLOCK_SIZE;
421   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
422               "Starting probe #%u (at offset %llu) for search result %p\n",
423               sr->availability_trials + 1,
424               (unsigned long long) off,
425               sr);
426   sr->remaining_probe_time =
427       GNUNET_TIME_relative_multiply (sr->h->avg_block_latency,
428                                      2 * (1 + sr->availability_trials));
429   sr->probe_ctx =
430       GNUNET_FS_download_start (sr->h, sr->uri, sr->meta, NULL, NULL, off,
431                                 len, sr->anonymity,
432                                 GNUNET_FS_DOWNLOAD_NO_TEMPORARIES |
433                                 GNUNET_FS_DOWNLOAD_IS_PROBE, sr, NULL);
434   sr->probe_ping_task
435     = GNUNET_SCHEDULER_add_now (&probe_ping_task,
436                                 sr);
437 }
438
439
440 /**
441  * Start download probes for the given search result.
442  *
443  * @param h file-sharing handle to use for the operation
444  * @param uri URI to probe
445  * @param meta meta data associated with the URI
446  * @param client_info client info pointer to use for associated events
447  * @param anonymity anonymity level to use for the probes
448  * @return the search result handle to access the probe activity
449  */
450 struct GNUNET_FS_SearchResult *
451 GNUNET_FS_probe (struct GNUNET_FS_Handle *h,
452                  const struct GNUNET_FS_Uri *uri,
453                  const struct GNUNET_CONTAINER_MetaData *meta,
454                  void *client_info,
455                  uint32_t anonymity)
456 {
457   struct GNUNET_FS_SearchResult *sr;
458
459   GNUNET_assert (NULL != h);
460   sr = GNUNET_new (struct GNUNET_FS_SearchResult);
461   sr->h = h;
462   sr->uri = GNUNET_FS_uri_dup (uri);
463   sr->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
464   sr->client_info = client_info;
465   sr->anonymity = anonymity;
466   GNUNET_FS_search_start_probe_ (sr);
467   return sr;
468 }
469
470
471 /**
472  * Stop probing activity associated with a search result.
473  *
474  * @param sr search result
475  */
476 static void
477 GNUNET_FS_search_stop_probe_ (struct GNUNET_FS_SearchResult *sr)
478 {
479   if (NULL != sr->probe_ctx)
480   {
481     GNUNET_FS_download_stop (sr->probe_ctx, GNUNET_YES);
482     sr->probe_ctx = NULL;
483   }
484   if (GNUNET_SCHEDULER_NO_TASK != sr->probe_ping_task)
485   {
486     GNUNET_SCHEDULER_cancel (sr->probe_ping_task);
487     sr->probe_ping_task = GNUNET_SCHEDULER_NO_TASK;
488   }
489   if (GNUNET_SCHEDULER_NO_TASK != sr->probe_cancel_task)
490   {
491     GNUNET_SCHEDULER_cancel (sr->probe_cancel_task);
492     sr->probe_cancel_task = GNUNET_SCHEDULER_NO_TASK;
493   }
494 }
495
496
497 /**
498  * Stop probe activity.  Must ONLY be used on values
499  * returned from #GNUNET_FS_probe.
500  *
501  * @param sr search result to stop probing for (freed)
502  * @return the value of the 'client_info' pointer
503  */
504 void *
505 GNUNET_FS_probe_stop (struct GNUNET_FS_SearchResult *sr)
506 {
507   void *client_info;
508
509   GNUNET_assert (NULL == sr->sc);
510   GNUNET_FS_search_stop_probe_ (sr);
511   GNUNET_FS_uri_destroy (sr->uri);
512   GNUNET_CONTAINER_meta_data_destroy (sr->meta);
513   client_info = sr->client_info;
514   GNUNET_free (sr);
515   return client_info;
516 }
517
518
519 /**
520  * We have received a KSK result.  Check how it fits in with the
521  * overall query and notify the client accordingly.
522  *
523  * @param sc context for the overall query
524  * @param ent entry for the specific keyword
525  * @param uri the URI that was found
526  * @param meta metadata associated with the URI
527  *        under the @a ent keyword
528  */
529 static void
530 process_ksk_result (struct GNUNET_FS_SearchContext *sc,
531                     struct SearchRequestEntry *ent,
532                     const struct GNUNET_FS_Uri *uri,
533                     const struct GNUNET_CONTAINER_MetaData *meta)
534 {
535   struct GNUNET_HashCode key;
536   struct GNUNET_FS_SearchResult *sr;
537   struct GetResultContext grc;
538   int is_new;
539   unsigned int koff;
540
541   /* check if new */
542   GNUNET_assert (NULL != sc);
543   GNUNET_FS_uri_to_key (uri, &key);
544   if (GNUNET_SYSERR ==
545       GNUNET_CONTAINER_multihashmap_get_multiple (ent->results,
546                                                   &key,
547                                                   &test_result_present,
548                                                   (void *) uri))
549     return;                     /* duplicate result */
550   /* try to find search result in master map */
551   grc.sr = NULL;
552   grc.uri = uri;
553   GNUNET_CONTAINER_multihashmap_get_multiple (sc->master_result_map,
554                                               &key,
555                                               &get_result_present, &grc);
556   sr = grc.sr;
557   is_new = (NULL == sr) || (sr->mandatory_missing > 0);
558   if (NULL == sr)
559   {
560     sr = GNUNET_new (struct GNUNET_FS_SearchResult);
561     sr->h = sc->h;
562     sr->sc = sc;
563     sr->anonymity = sc->anonymity;
564     sr->uri = GNUNET_FS_uri_dup (uri);
565     sr->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
566     sr->mandatory_missing = sc->mandatory_count;
567     sr->key = key;
568     sr->keyword_bitmap = GNUNET_malloc ((sc->uri->data.ksk.keywordCount + 7) / 8); /* round up, count bits */
569     GNUNET_CONTAINER_multihashmap_put (sc->master_result_map, &key, sr,
570                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
571   }
572   else
573   {
574     GNUNET_CONTAINER_meta_data_merge (sr->meta, meta);
575   }
576   GNUNET_break (GNUNET_OK ==
577                 GNUNET_CONTAINER_multihashmap_put (ent->results,
578                                                    &sr->key,
579                                                    sr,
580                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
581
582   koff = ent - sc->requests;
583   GNUNET_assert ( (ent >= sc->requests) &&
584                   (koff < sc->uri->data.ksk.keywordCount));
585   sr->keyword_bitmap[koff / 8] |= (1 << (koff % 8));
586   /* check if mandatory satisfied */
587   if (1 <= GNUNET_CONTAINER_multihashmap_size (ent->results))
588   {
589     if (ent->mandatory)
590     {
591       GNUNET_break (sr->mandatory_missing > 0);
592       sr->mandatory_missing--;
593     }
594     else
595     {
596       sr->optional_support++;
597     }
598   }
599   if (0 != sr->mandatory_missing)
600   {
601     GNUNET_break (NULL == sr->client_info);
602     return;
603   }
604   if (is_new)
605     notify_client_chk_result (sc, sr);
606   else
607     notify_client_chk_update (sc, sr);
608   GNUNET_FS_search_result_sync_ (sr);
609   GNUNET_FS_search_start_probe_ (sr);
610 }
611
612
613 /**
614  * Start search for content, internal API.
615  *
616  * @param h handle to the file sharing subsystem
617  * @param uri specifies the search parameters; can be
618  *        a KSK URI or an SKS URI.
619  * @param anonymity desired level of anonymity
620  * @param options options for the search
621  * @param cctx client context
622  * @param psearch parent search result (for namespace update searches)
623  * @return context that can be used to control the search
624  */
625 static struct GNUNET_FS_SearchContext *
626 search_start (struct GNUNET_FS_Handle *h, const struct GNUNET_FS_Uri *uri,
627               uint32_t anonymity, enum GNUNET_FS_SearchOptions options,
628               void *cctx, struct GNUNET_FS_SearchResult *psearch);
629
630
631 /**
632  * We have received an SKS result.  Start searching for updates and
633  * notify the client if it is a new result.
634  *
635  * @param sc context for the overall query
636  * @param id_update identifier for updates, NULL for none
637  * @param uri the URI that was found
638  * @param meta metadata associated with the URI
639   */
640 static void
641 process_sks_result (struct GNUNET_FS_SearchContext *sc,
642                     const char *id_update,
643                     const struct GNUNET_FS_Uri *uri,
644                     const struct GNUNET_CONTAINER_MetaData *meta)
645 {
646   struct GNUNET_FS_Uri uu;
647   struct GNUNET_HashCode key;
648   struct GNUNET_FS_SearchResult *sr;
649
650   /* check if new */
651   GNUNET_assert (NULL != sc);
652   GNUNET_FS_uri_to_key (uri, &key);
653   GNUNET_CRYPTO_hash_xor (&uri->data.chk.chk.key, &uri->data.chk.chk.query,
654                           &key);
655   if (GNUNET_SYSERR ==
656       GNUNET_CONTAINER_multihashmap_get_multiple (sc->master_result_map, &key,
657                                                   &test_result_present,
658                                                   (void *) uri))
659     return;                     /* duplicate result */
660   sr = GNUNET_new (struct GNUNET_FS_SearchResult);
661   sr->h = sc->h;
662   sr->sc = sc;
663   sr->anonymity = sc->anonymity;
664   sr->uri = GNUNET_FS_uri_dup (uri);
665   sr->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
666   sr->key = key;
667   GNUNET_CONTAINER_multihashmap_put (sc->master_result_map, &key, sr,
668                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
669   GNUNET_FS_search_result_sync_ (sr);
670   GNUNET_FS_search_start_probe_ (sr);
671   /* notify client */
672   if (0 == sr->mandatory_missing)
673     notify_client_chk_result (sc, sr);
674   else
675     GNUNET_break (NULL == sr->client_info);
676   /* search for updates */
677   if (0 == strlen (id_update))
678     return;                     /* no updates */
679   uu.type = GNUNET_FS_URI_SKS;
680   uu.data.sks.ns = sc->uri->data.sks.ns;
681   uu.data.sks.identifier = GNUNET_strdup (id_update);
682   (void) search_start (sc->h, &uu, sc->anonymity, sc->options, NULL, sr);
683   GNUNET_free (uu.data.sks.identifier);
684 }
685
686
687 /**
688  * Decrypt a ublock using a 'keyword' as the passphrase.  Given the
689  * KSK public key derived from the keyword, this function looks up
690  * the original keyword in the search context and decrypts the
691  * given ciphertext block.
692  *
693  * @param sc search context with the keywords
694  * @param dpub derived public key used for the search
695  * @param edata encrypted data
696  * @param edata_size number of bytes in @a edata (and @a data)
697  * @param data where to store the plaintext
698  * @return keyword index on success, #GNUNET_SYSERR on error (no such
699  *         keyword, internal error)
700  */
701 static int
702 decrypt_block_with_keyword (const struct GNUNET_FS_SearchContext *sc,
703                             const struct GNUNET_CRYPTO_EcdsaPublicKey *dpub,
704                             const void *edata,
705                             size_t edata_size,
706                             char *data)
707 {
708   const struct GNUNET_CRYPTO_EcdsaPrivateKey *anon;
709   struct GNUNET_CRYPTO_EcdsaPublicKey anon_pub;
710   unsigned int i;
711
712   /* find key */
713   for (i = 0; i < sc->uri->data.ksk.keywordCount; i++)
714     if (0 == memcmp (dpub,
715                      &sc->requests[i].dpub,
716                      sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey)))
717       break;
718   if (i == sc->uri->data.ksk.keywordCount)
719   {
720     /* oops, does not match any of our keywords!? */
721     GNUNET_break (0);
722     return GNUNET_SYSERR;
723   }
724   /* decrypt */
725   anon = GNUNET_CRYPTO_ecdsa_key_get_anonymous ();
726   GNUNET_CRYPTO_ecdsa_key_get_public (anon, &anon_pub);
727   GNUNET_FS_ublock_decrypt_ (edata, edata_size,
728                              &anon_pub,
729                              sc->requests[i].keyword,
730                              data);
731   return i;
732 }
733
734
735 /**
736  * Process a keyword search result.  The actual type of block is
737  * a UBlock; we know it is a keyword search result because that's
738  * what we were searching for.
739  *
740  * @param sc our search context
741  * @param ub the ublock with the keyword search result
742  * @param size size of @a ub
743  */
744 static void
745 process_kblock (struct GNUNET_FS_SearchContext *sc,
746                 const struct UBlock *ub,
747                 size_t size)
748 {
749   size_t j;
750   char pt[size - sizeof (struct UBlock)];
751   const char *eos;
752   struct GNUNET_CONTAINER_MetaData *meta;
753   struct GNUNET_FS_Uri *uri;
754   char *emsg;
755   int i;
756
757   if (-1 == (i = decrypt_block_with_keyword (sc,
758                                              &ub->verification_key,
759                                              &ub[1],
760                                              size - sizeof (struct UBlock),
761                                              pt)))
762     return;
763   /* parse; pt[0] is just '\0', so we skip over that */
764   eos = memchr (&pt[1], '\0', sizeof (pt) - 1);
765   if (NULL == eos)
766   {
767     GNUNET_break_op (0);
768     return;
769   }
770   if (NULL == (uri = GNUNET_FS_uri_parse (&pt[1], &emsg)))
771   {
772     if (GNUNET_FS_VERSION > 0x00090400)
773     {
774       /* we broke this in 0x00090300, so don't bitch
775          too loudly just one version up... */
776       GNUNET_break_op (0);        /* ublock malformed */
777       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
778                   _("Failed to parse URI `%s': %s\n"),
779                   &pt[1],
780                   emsg);
781     }
782     GNUNET_free_non_null (emsg);
783     return;
784   }
785   j = eos - pt + 1;
786   if (sizeof (pt) == j)
787     meta = GNUNET_CONTAINER_meta_data_create ();
788   else
789     meta = GNUNET_CONTAINER_meta_data_deserialize (&pt[j], sizeof (pt) - j);
790   if (NULL == meta)
791   {
792     GNUNET_break_op (0);        /* ublock malformed */
793     GNUNET_FS_uri_destroy (uri);
794     return;
795   }
796   process_ksk_result (sc,
797                       &sc->requests[i],
798                       uri,
799                       meta);
800
801   /* clean up */
802   GNUNET_CONTAINER_meta_data_destroy (meta);
803   GNUNET_FS_uri_destroy (uri);
804 }
805
806
807 /**
808  * Process a namespace-search result.  The actual type of block is
809  * a UBlock; we know it is a namespace search result because that's
810  * what we were searching for.
811  *
812  * @param sc our search context
813  * @param ub the ublock with a namespace result
814  * @param size size of @a ub
815  */
816 static void
817 process_sblock (struct GNUNET_FS_SearchContext *sc,
818                 const struct UBlock *ub,
819                 size_t size)
820 {
821   size_t len = size - sizeof (struct UBlock);
822   char pt[len];
823   struct GNUNET_FS_Uri *uri;
824   struct GNUNET_CONTAINER_MetaData *meta;
825   const char *id;
826   const char *uris;
827   size_t off;
828   char *emsg;
829
830   GNUNET_FS_ublock_decrypt_ (&ub[1], len,
831                              &sc->uri->data.sks.ns,
832                              sc->uri->data.sks.identifier,
833                              pt);
834   /* parse */
835   if (0 == (off = GNUNET_STRINGS_buffer_tokenize (pt, len, 2, &id, &uris)))
836   {
837     GNUNET_break_op (0);        /* ublock malformed */
838     return;
839   }
840   if (NULL == (meta = GNUNET_CONTAINER_meta_data_deserialize (&pt[off], len - off)))
841   {
842     GNUNET_break_op (0);        /* ublock malformed */
843     return;
844   }
845   if (NULL == (uri = GNUNET_FS_uri_parse (uris, &emsg)))
846   {
847     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
848                 _("Failed to parse URI `%s': %s\n"),
849                 uris, emsg);
850     GNUNET_break_op (0);        /* ublock malformed */
851     GNUNET_free_non_null (emsg);
852     GNUNET_CONTAINER_meta_data_destroy (meta);
853     return;
854   }
855   /* process */
856   process_sks_result (sc, id, uri, meta);
857   /* clean up */
858   GNUNET_FS_uri_destroy (uri);
859   GNUNET_CONTAINER_meta_data_destroy (meta);
860 }
861
862
863 /**
864  * Process a search result.
865  *
866  * @param sc our search context
867  * @param type type of the result
868  * @param expiration when it will expire
869  * @param data the (encrypted) response
870  * @param size size of @a data
871  */
872 static void
873 process_result (struct GNUNET_FS_SearchContext *sc,
874                 enum GNUNET_BLOCK_Type type,
875                 struct GNUNET_TIME_Absolute expiration,
876                 const void *data,
877                 size_t size)
878 {
879   if (GNUNET_TIME_absolute_get_duration (expiration).rel_value_us > 0)
880   {
881     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
882                 "Result received has already expired.\n");
883     return;                     /* result expired */
884   }
885   switch (type)
886   {
887   case GNUNET_BLOCK_TYPE_FS_UBLOCK:
888     if (GNUNET_FS_URI_SKS == sc->uri->type)
889       process_sblock (sc, data, size);
890     else
891       process_kblock (sc, data, size);
892     break;
893   case GNUNET_BLOCK_TYPE_ANY:
894     GNUNET_break (0);
895     break;
896   case GNUNET_BLOCK_TYPE_FS_DBLOCK:
897     GNUNET_break (0);
898     break;
899   case GNUNET_BLOCK_TYPE_FS_ONDEMAND:
900     GNUNET_break (0);
901     break;
902   case GNUNET_BLOCK_TYPE_FS_IBLOCK:
903     GNUNET_break (0);
904     break;
905   default:
906     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
907                 _("Got result with unknown block type `%d', ignoring"), type);
908     break;
909   }
910 }
911
912
913 /**
914  * Shutdown any existing connection to the FS
915  * service and try to establish a fresh one
916  * (and then re-transmit our search request).
917  *
918  * @param sc the search to reconnec
919  */
920 static void
921 try_reconnect (struct GNUNET_FS_SearchContext *sc);
922
923
924 /**
925  * Type of a function to call when we receive a message
926  * from the service.
927  *
928  * @param cls closure
929  * @param msg message received, NULL on timeout or fatal error
930  */
931 static void
932 receive_results (void *cls, const struct GNUNET_MessageHeader *msg)
933 {
934   struct GNUNET_FS_SearchContext *sc = cls;
935   const struct ClientPutMessage *cm;
936   uint16_t msize;
937
938   if ((NULL == msg) || (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_FS_PUT) ||
939       (ntohs (msg->size) <= sizeof (struct ClientPutMessage)))
940   {
941     try_reconnect (sc);
942     return;
943   }
944   msize = ntohs (msg->size);
945   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
946               "Receiving %u bytes of result from fs service\n", msize);
947   cm = (const struct ClientPutMessage *) msg;
948   process_result (sc, ntohl (cm->type),
949                   GNUNET_TIME_absolute_ntoh (cm->expiration), &cm[1],
950                   msize - sizeof (struct ClientPutMessage));
951   /* continue receiving */
952   GNUNET_CLIENT_receive (sc->client, &receive_results, sc,
953                          GNUNET_TIME_UNIT_FOREVER_REL);
954 }
955
956
957 /**
958  * Schedule the transmission of the (next) search request
959  * to the service.
960  *
961  * @param sc context for the search
962  */
963 static void
964 schedule_transmit_search_request (struct GNUNET_FS_SearchContext *sc);
965
966
967 /**
968  * Closure for 'build_result_set'.
969  */
970 struct MessageBuilderContext
971 {
972   /**
973    * How many entries can we store to xoff.
974    */
975   unsigned int put_cnt;
976
977   /**
978    * How many entries should we skip.
979    */
980   unsigned int skip_cnt;
981
982   /**
983    * Where to store the keys.
984    */
985   struct GNUNET_HashCode *xoff;
986
987   /**
988    * Search context we are iterating for.
989    */
990   struct GNUNET_FS_SearchContext *sc;
991
992   /**
993    * Keyword offset the search result must match (0 for SKS)
994    */
995   unsigned int keyword_offset;
996 };
997
998
999 /**
1000  * Iterating over the known results, pick those matching the given
1001  * result range and store their keys at 'xoff'.
1002  *
1003  * @param cls the `struct MessageBuilderContext`
1004  * @param key key for a result
1005  * @param value the search result
1006  * @return #GNUNET_OK to continue iterating
1007  */
1008 static int
1009 build_result_set (void *cls,
1010                   const struct GNUNET_HashCode *key,
1011                   void *value)
1012 {
1013   struct MessageBuilderContext *mbc = cls;
1014   struct GNUNET_FS_SearchResult *sr = value;
1015
1016   if ( (NULL != sr->keyword_bitmap) &&
1017        (0 == (sr->keyword_bitmap[mbc->keyword_offset / 8] & (1 << (mbc->keyword_offset % 8)))) )
1018     return GNUNET_OK; /* have no match for this keyword yet */
1019   if (mbc->skip_cnt > 0)
1020   {
1021     mbc->skip_cnt--;
1022     return GNUNET_OK;
1023   }
1024   if (0 == mbc->put_cnt)
1025     return GNUNET_SYSERR;
1026   mbc->sc->search_request_map_offset++;
1027   mbc->xoff[--mbc->put_cnt] = *key;
1028
1029   return GNUNET_OK;
1030 }
1031
1032
1033 /**
1034  * Iterating over the known results, count those matching the given
1035  * result range and increment put count for each.
1036  *
1037  * @param cls the `struct MessageBuilderContext`
1038  * @param key key for a result
1039  * @param value the search result
1040  * @return #GNUNET_OK to continue iterating
1041  */
1042 static int
1043 find_result_set (void *cls,
1044                  const struct GNUNET_HashCode *key,
1045                  void *value)
1046 {
1047   struct MessageBuilderContext *mbc = cls;
1048   struct GNUNET_FS_SearchResult *sr = value;
1049
1050   if ( (NULL != sr->keyword_bitmap) &&
1051        (0 == (sr->keyword_bitmap[mbc->keyword_offset / 8] & (1 << (mbc->keyword_offset % 8)))) )
1052     return GNUNET_OK; /* have no match for this keyword yet */
1053   mbc->put_cnt++;
1054   return GNUNET_OK;
1055 }
1056
1057
1058 /**
1059  * We're ready to transmit the search request to the file-sharing
1060  * service.  Do it.  If the request is too large to fit into a single
1061  * message, transmit in increments.
1062  *
1063  * @param cls closure
1064  * @param size number of bytes available in @a buf
1065  * @param buf where the callee should write the message
1066  * @return number of bytes written to @a buf
1067  */
1068 static size_t
1069 transmit_search_request (void *cls, size_t size, void *buf)
1070 {
1071   struct GNUNET_FS_SearchContext *sc = cls;
1072   struct MessageBuilderContext mbc;
1073   size_t msize;
1074   struct SearchMessage *sm;
1075   struct GNUNET_CRYPTO_EcdsaPublicKey dpub;
1076   unsigned int total_seen_results; /* total number of result hashes to send */
1077   unsigned int message_size_limit;
1078   uint32_t options;
1079
1080   if (NULL == buf)
1081   {
1082     try_reconnect (sc);
1083     return 0;
1084   }
1085   mbc.sc = sc;
1086   mbc.skip_cnt = sc->search_request_map_offset;
1087   sm = buf;
1088   sm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_START_SEARCH);
1089   mbc.xoff = (struct GNUNET_HashCode *) &sm[1];
1090   options = SEARCH_MESSAGE_OPTION_NONE;
1091   if (0 != (sc->options & GNUNET_FS_SEARCH_OPTION_LOOPBACK_ONLY))
1092     options |= SEARCH_MESSAGE_OPTION_LOOPBACK_ONLY;
1093   if (GNUNET_FS_uri_test_ksk (sc->uri))
1094   {
1095     msize = sizeof (struct SearchMessage);
1096     GNUNET_assert (size >= msize);
1097     mbc.keyword_offset = sc->keyword_offset;
1098     /* calculate total number of known results (in put_cnt => total_seen_results) */
1099     mbc.put_cnt = 0;
1100     GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1101                                            &find_result_set, &mbc);
1102     total_seen_results = mbc.put_cnt;
1103     /* calculate how many results we can send in this message */
1104     message_size_limit = (size - msize) / sizeof (struct GNUNET_HashCode);
1105     mbc.put_cnt = GNUNET_MIN (message_size_limit,
1106                               total_seen_results - mbc.skip_cnt);
1107     if (sc->search_request_map_offset < total_seen_results)
1108       GNUNET_assert (mbc.put_cnt > 0);
1109
1110     /* now build message */
1111     msize += sizeof (struct GNUNET_HashCode) * mbc.put_cnt;
1112     sm->header.size = htons (msize);
1113     sm->type = htonl (GNUNET_BLOCK_TYPE_FS_UBLOCK);
1114     sm->anonymity_level = htonl (sc->anonymity);
1115     memset (&sm->target, 0, sizeof (struct GNUNET_PeerIdentity));
1116     sm->query = sc->requests[sc->keyword_offset].uquery;
1117     GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1118                                            &build_result_set, &mbc);
1119     GNUNET_assert (0 == mbc.put_cnt);
1120     GNUNET_assert (total_seen_results >= sc->search_request_map_offset);
1121     if (total_seen_results != sc->search_request_map_offset)
1122     {
1123       /* more requesting to be done... */
1124       sm->options = htonl (options | SEARCH_MESSAGE_OPTION_CONTINUED);
1125       schedule_transmit_search_request (sc);
1126       return msize;
1127     }
1128     sm->options = htonl (options);
1129     sc->keyword_offset++;
1130     sc->search_request_map_offset = 0;
1131     if (sc->uri->data.ksk.keywordCount != sc->keyword_offset)
1132     {
1133       /* more requesting to be done... */
1134       schedule_transmit_search_request (sc);
1135       return msize;
1136     }
1137   }
1138   else
1139   {
1140     GNUNET_assert (GNUNET_FS_uri_test_sks (sc->uri));
1141     msize = sizeof (struct SearchMessage);
1142     GNUNET_assert (size >= msize);
1143     sm->type = htonl (GNUNET_BLOCK_TYPE_FS_UBLOCK);
1144     sm->anonymity_level = htonl (sc->anonymity);
1145     memset (&sm->target, 0, sizeof (struct GNUNET_PeerIdentity));
1146     GNUNET_CRYPTO_ecdsa_public_key_derive (&sc->uri->data.sks.ns,
1147                                          sc->uri->data.sks.identifier,
1148                                          "fs-ublock",
1149                                          &dpub);
1150     GNUNET_CRYPTO_hash (&dpub,
1151                         sizeof (dpub),
1152                         &sm->query);
1153     message_size_limit = (size - msize) / sizeof (struct GNUNET_HashCode);
1154     total_seen_results = GNUNET_CONTAINER_multihashmap_size (sc->master_result_map);
1155     mbc.put_cnt = GNUNET_MIN (message_size_limit,
1156                               total_seen_results - mbc.skip_cnt);
1157     mbc.keyword_offset = 0;
1158     if (sc->search_request_map_offset < total_seen_results)
1159       GNUNET_assert (mbc.put_cnt > 0);
1160     msize += sizeof (struct GNUNET_HashCode) * mbc.put_cnt;
1161     GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1162                                            &build_result_set, &mbc);
1163     sm->header.size = htons (msize);
1164     GNUNET_assert (total_seen_results >= sc->search_request_map_offset);
1165     if (total_seen_results != sc->search_request_map_offset)
1166     {
1167       /* more requesting to be done... */
1168       sm->options = htonl (options | SEARCH_MESSAGE_OPTION_CONTINUED);
1169       schedule_transmit_search_request (sc);
1170       return msize;
1171     }
1172     sm->options = htonl (options);
1173   }
1174   GNUNET_CLIENT_receive (sc->client,
1175                          &receive_results, sc,
1176                          GNUNET_TIME_UNIT_FOREVER_REL);
1177   return msize;
1178 }
1179
1180
1181 /**
1182  * Schedule the transmission of the (next) search request
1183  * to the service.
1184  *
1185  * @param sc context for the search
1186  */
1187 static void
1188 schedule_transmit_search_request (struct GNUNET_FS_SearchContext *sc)
1189 {
1190   size_t size;
1191   unsigned int left;
1192   unsigned int fit;
1193   unsigned int request;
1194
1195   size = sizeof (struct SearchMessage);
1196   left =
1197       GNUNET_CONTAINER_multihashmap_size (sc->master_result_map) -
1198       sc->search_request_map_offset;
1199   fit = (GNUNET_SERVER_MAX_MESSAGE_SIZE - 1 - size) / sizeof (struct GNUNET_HashCode);
1200   request = GNUNET_MIN (fit, left);
1201   size += sizeof (struct GNUNET_HashCode) * request;
1202   GNUNET_CLIENT_notify_transmit_ready (sc->client, size,
1203                                        GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1204                                        GNUNET_NO,
1205                                        &transmit_search_request, sc);
1206 }
1207
1208
1209 /**
1210  * Reconnect to the FS service and transmit
1211  * our queries NOW.
1212  *
1213  * @param cls our search context
1214  * @param tc unused
1215  */
1216 static void
1217 do_reconnect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1218 {
1219   struct GNUNET_FS_SearchContext *sc = cls;
1220   struct GNUNET_CLIENT_Connection *client;
1221
1222   sc->task = GNUNET_SCHEDULER_NO_TASK;
1223   client = GNUNET_CLIENT_connect ("fs", sc->h->cfg);
1224   if (NULL == client)
1225   {
1226     try_reconnect (sc);
1227     return;
1228   }
1229   sc->client = client;
1230   sc->search_request_map_offset = 0;
1231   sc->keyword_offset = 0;
1232   schedule_transmit_search_request (sc);
1233 }
1234
1235
1236 /**
1237  * Shutdown any existing connection to the FS
1238  * service and try to establish a fresh one
1239  * (and then re-transmit our search request).
1240  *
1241  * @param sc the search to reconnec
1242  */
1243 static void
1244 try_reconnect (struct GNUNET_FS_SearchContext *sc)
1245 {
1246   if (NULL != sc->client)
1247   {
1248     GNUNET_CLIENT_disconnect (sc->client);
1249     sc->client = NULL;
1250   }
1251   sc->reconnect_backoff = GNUNET_TIME_STD_BACKOFF (sc->reconnect_backoff);
1252   sc->task =
1253       GNUNET_SCHEDULER_add_delayed (sc->reconnect_backoff,
1254                                     &do_reconnect,
1255                                     sc);
1256 }
1257
1258
1259 /**
1260  * Start search for content, internal API.
1261  *
1262  * @param h handle to the file sharing subsystem
1263  * @param uri specifies the search parameters; can be
1264  *        a KSK URI or an SKS URI.
1265  * @param anonymity desired level of anonymity
1266  * @param options options for the search
1267  * @param cctx initial value for the client context
1268  * @param psearch parent search result (for namespace update searches)
1269  * @return context that can be used to control the search
1270  */
1271 static struct GNUNET_FS_SearchContext *
1272 search_start (struct GNUNET_FS_Handle *h,
1273               const struct GNUNET_FS_Uri *uri,
1274               uint32_t anonymity,
1275               enum GNUNET_FS_SearchOptions options,
1276               void *cctx,
1277               struct GNUNET_FS_SearchResult *psearch)
1278 {
1279   struct GNUNET_FS_SearchContext *sc;
1280   struct GNUNET_FS_ProgressInfo pi;
1281
1282   sc = GNUNET_new (struct GNUNET_FS_SearchContext);
1283   sc->h = h;
1284   sc->options = options;
1285   sc->uri = GNUNET_FS_uri_dup (uri);
1286   sc->anonymity = anonymity;
1287   sc->start_time = GNUNET_TIME_absolute_get ();
1288   if (NULL != psearch)
1289   {
1290     sc->psearch_result = psearch;
1291     psearch->update_search = sc;
1292   }
1293   sc->master_result_map = GNUNET_CONTAINER_multihashmap_create (16, GNUNET_NO);
1294   sc->client_info = cctx;
1295   if (GNUNET_OK != GNUNET_FS_search_start_searching_ (sc))
1296   {
1297     GNUNET_FS_uri_destroy (sc->uri);
1298     GNUNET_CONTAINER_multihashmap_destroy (sc->master_result_map);
1299     GNUNET_free (sc);
1300     return NULL;
1301   }
1302   GNUNET_FS_search_sync_ (sc);
1303   pi.status = GNUNET_FS_STATUS_SEARCH_START;
1304   sc->client_info = GNUNET_FS_search_make_status_ (&pi, sc->h, sc);
1305   return sc;
1306 }
1307
1308
1309 /**
1310  * Update the 'results' map for the individual keywords with the
1311  * results from the 'global' result set.
1312  *
1313  * @param cls closure, the `struct GNUNET_FS_SearchContext *`
1314  * @param key current key code
1315  * @param value value in the hash map, the `struct GNUNET_FS_SearchResult *`
1316  * @return #GNUNET_YES (we should continue to iterate)
1317  */
1318 static int
1319 update_sre_result_maps (void *cls,
1320                         const struct GNUNET_HashCode *key,
1321                         void *value)
1322 {
1323   struct GNUNET_FS_SearchContext *sc = cls;
1324   struct GNUNET_FS_SearchResult *sr = value;
1325   unsigned int i;
1326
1327   for (i = 0; i < sc->uri->data.ksk.keywordCount; i++)
1328     if (0 != (sr->keyword_bitmap[i / 8] & (1 << (i % 8))))
1329       GNUNET_break (GNUNET_OK ==
1330                     GNUNET_CONTAINER_multihashmap_put (sc->requests[i].results,
1331                                                        &sr->key,
1332                                                        sr,
1333                                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1334
1335   return GNUNET_YES;
1336 }
1337
1338
1339 /**
1340  * Build the request and actually initiate the search using the
1341  * GNUnet FS service.
1342  *
1343  * @param sc search context
1344  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1345  */
1346 int
1347 GNUNET_FS_search_start_searching_ (struct GNUNET_FS_SearchContext *sc)
1348 {
1349   unsigned int i;
1350   const char *keyword;
1351   const struct GNUNET_CRYPTO_EcdsaPrivateKey *anon;
1352   struct GNUNET_CRYPTO_EcdsaPublicKey anon_pub;
1353   struct SearchRequestEntry *sre;
1354
1355   GNUNET_assert (NULL == sc->client);
1356   if (GNUNET_FS_uri_test_ksk (sc->uri))
1357   {
1358     GNUNET_assert (0 != sc->uri->data.ksk.keywordCount);
1359     anon = GNUNET_CRYPTO_ecdsa_key_get_anonymous ();
1360     GNUNET_CRYPTO_ecdsa_key_get_public (anon, &anon_pub);
1361     sc->requests =
1362         GNUNET_malloc (sizeof (struct SearchRequestEntry) *
1363                        sc->uri->data.ksk.keywordCount);
1364     for (i = 0; i < sc->uri->data.ksk.keywordCount; i++)
1365     {
1366       keyword = &sc->uri->data.ksk.keywords[i][1];
1367       sre = &sc->requests[i];
1368       sre->keyword = GNUNET_strdup (keyword);
1369       GNUNET_CRYPTO_ecdsa_public_key_derive (&anon_pub,
1370                                              keyword,
1371                                              "fs-ublock",
1372                                              &sre->dpub);
1373       GNUNET_CRYPTO_hash (&sre->dpub,
1374                           sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey),
1375                           &sre->uquery);
1376       sre->mandatory = (sc->uri->data.ksk.keywords[i][0] == '+');
1377       if (sre->mandatory)
1378         sc->mandatory_count++;
1379       sre->results = GNUNET_CONTAINER_multihashmap_create (4, GNUNET_NO);
1380     }
1381     GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1382                                            &update_sre_result_maps,
1383                                            sc);
1384   }
1385   sc->client = GNUNET_CLIENT_connect ("fs", sc->h->cfg);
1386   if (NULL == sc->client)
1387     return GNUNET_SYSERR;
1388   sc->search_request_map_offset = 0;
1389   schedule_transmit_search_request (sc);
1390   return GNUNET_OK;
1391 }
1392
1393
1394 /**
1395  * Freeze probes for the given search result.
1396  *
1397  * @param cls the global FS handle
1398  * @param key the key for the search result (unused)
1399  * @param value the search result to free
1400  * @return #GNUNET_OK
1401  */
1402 static int
1403 search_result_freeze_probes (void *cls,
1404                              const struct GNUNET_HashCode *key,
1405                              void *value)
1406 {
1407   struct GNUNET_FS_SearchResult *sr = value;
1408
1409   if (NULL != sr->probe_ctx)
1410   {
1411     GNUNET_FS_download_stop (sr->probe_ctx, GNUNET_YES);
1412     sr->probe_ctx = NULL;
1413   }
1414   if (GNUNET_SCHEDULER_NO_TASK != sr->probe_ping_task)
1415   {
1416     GNUNET_SCHEDULER_cancel (sr->probe_ping_task);
1417     sr->probe_ping_task = GNUNET_SCHEDULER_NO_TASK;
1418   }
1419   if (GNUNET_SCHEDULER_NO_TASK != sr->probe_cancel_task)
1420   {
1421     GNUNET_SCHEDULER_cancel (sr->probe_cancel_task);
1422     sr->probe_cancel_task = GNUNET_SCHEDULER_NO_TASK;
1423   }
1424   if (NULL != sr->update_search)
1425     GNUNET_FS_search_pause (sr->update_search);
1426   return GNUNET_OK;
1427 }
1428
1429
1430 /**
1431  * Resume probes for the given search result.
1432  *
1433  * @param cls the global FS handle
1434  * @param key the key for the search result (unused)
1435  * @param value the search result to free
1436  * @return #GNUNET_OK
1437  */
1438 static int
1439 search_result_resume_probes (void *cls,
1440                              const struct GNUNET_HashCode * key,
1441                              void *value)
1442 {
1443   struct GNUNET_FS_SearchResult *sr = value;
1444
1445   GNUNET_FS_search_start_probe_ (sr);
1446   if (NULL != sr->update_search)
1447     GNUNET_FS_search_continue (sr->update_search);
1448   return GNUNET_OK;
1449 }
1450
1451
1452 /**
1453  * Signal suspend and free the given search result.
1454  *
1455  * @param cls the global FS handle
1456  * @param key the key for the search result (unused)
1457  * @param value the search result to free
1458  * @return #GNUNET_OK
1459  */
1460 static int
1461 search_result_suspend (void *cls,
1462                        const struct GNUNET_HashCode *key,
1463                        void *value)
1464 {
1465   struct GNUNET_FS_SearchContext *sc = cls;
1466   struct GNUNET_FS_SearchResult *sr = value;
1467   struct GNUNET_FS_ProgressInfo pi;
1468
1469   if (NULL != sr->download)
1470   {
1471     GNUNET_FS_download_signal_suspend_ (sr->download);
1472     sr->download = NULL;
1473   }
1474   if (NULL != sr->update_search)
1475   {
1476     GNUNET_FS_search_signal_suspend_ (sr->update_search);
1477     sr->update_search = NULL;
1478   }
1479   GNUNET_FS_search_stop_probe_ (sr);
1480   if (0 == sr->mandatory_missing)
1481   {
1482     /* client is aware of search result, notify about suspension event */
1483     pi.status = GNUNET_FS_STATUS_SEARCH_RESULT_SUSPEND;
1484     pi.value.search.specifics.result_suspend.cctx = sr->client_info;
1485     pi.value.search.specifics.result_suspend.meta = sr->meta;
1486     pi.value.search.specifics.result_suspend.uri = sr->uri;
1487     sr->client_info = GNUNET_FS_search_make_status_ (&pi, sc->h, sc);
1488   }
1489   GNUNET_break (NULL == sr->client_info);
1490   GNUNET_free_non_null (sr->serialization);
1491   GNUNET_FS_uri_destroy (sr->uri);
1492   GNUNET_CONTAINER_meta_data_destroy (sr->meta);
1493   GNUNET_free_non_null (sr->keyword_bitmap);
1494   GNUNET_free (sr);
1495   return GNUNET_OK;
1496 }
1497
1498
1499 /**
1500  * Create SUSPEND event for the given search operation
1501  * and then clean up our state (without stop signal).
1502  *
1503  * @param cls the `struct GNUNET_FS_SearchContext` to signal for
1504  */
1505 void
1506 GNUNET_FS_search_signal_suspend_ (void *cls)
1507 {
1508   struct GNUNET_FS_SearchContext *sc = cls;
1509   struct GNUNET_FS_ProgressInfo pi;
1510   unsigned int i;
1511
1512   GNUNET_FS_end_top (sc->h, sc->top);
1513   GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1514                                          &search_result_suspend, sc);
1515   pi.status = GNUNET_FS_STATUS_SEARCH_SUSPEND;
1516   sc->client_info = GNUNET_FS_search_make_status_ (&pi, sc->h, sc);
1517   GNUNET_break (NULL == sc->client_info);
1518   if (sc->task != GNUNET_SCHEDULER_NO_TASK)
1519   {
1520     GNUNET_SCHEDULER_cancel (sc->task);
1521     sc->task = GNUNET_SCHEDULER_NO_TASK;
1522   }
1523   if (NULL != sc->client)
1524   {
1525     GNUNET_CLIENT_disconnect (sc->client);
1526     sc->client = NULL;
1527   }
1528   GNUNET_CONTAINER_multihashmap_destroy (sc->master_result_map);
1529   if (NULL != sc->requests)
1530   {
1531     GNUNET_assert (GNUNET_FS_uri_test_ksk (sc->uri));
1532     for (i = 0; i < sc->uri->data.ksk.keywordCount; i++)
1533     {
1534       GNUNET_CONTAINER_multihashmap_destroy (sc->requests[i].results);
1535       GNUNET_free (sc->requests[i].keyword);
1536     }
1537   }
1538   GNUNET_free_non_null (sc->requests);
1539   GNUNET_free_non_null (sc->emsg);
1540   GNUNET_FS_uri_destroy (sc->uri);
1541   GNUNET_free_non_null (sc->serialization);
1542   GNUNET_free (sc);
1543 }
1544
1545
1546 /**
1547  * Start search for content.
1548  *
1549  * @param h handle to the file sharing subsystem
1550  * @param uri specifies the search parameters; can be
1551  *        a KSK URI or an SKS URI.
1552  * @param anonymity desired level of anonymity
1553  * @param options options for the search
1554  * @param cctx initial value for the client context
1555  * @return context that can be used to control the search
1556  */
1557 struct GNUNET_FS_SearchContext *
1558 GNUNET_FS_search_start (struct GNUNET_FS_Handle *h,
1559                         const struct GNUNET_FS_Uri *uri, uint32_t anonymity,
1560                         enum GNUNET_FS_SearchOptions options, void *cctx)
1561 {
1562   struct GNUNET_FS_SearchContext *ret;
1563
1564   ret = search_start (h, uri, anonymity, options, cctx, NULL);
1565   if (NULL == ret)
1566     return NULL;
1567   ret->top = GNUNET_FS_make_top (h, &GNUNET_FS_search_signal_suspend_, ret);
1568   return ret;
1569 }
1570
1571
1572 /**
1573  * Pause search.
1574  *
1575  * @param sc context for the search that should be paused
1576  */
1577 void
1578 GNUNET_FS_search_pause (struct GNUNET_FS_SearchContext *sc)
1579 {
1580   struct GNUNET_FS_ProgressInfo pi;
1581
1582   if (GNUNET_SCHEDULER_NO_TASK != sc->task)
1583   {
1584     GNUNET_SCHEDULER_cancel (sc->task);
1585     sc->task = GNUNET_SCHEDULER_NO_TASK;
1586   }
1587   if (NULL != sc->client)
1588     GNUNET_CLIENT_disconnect (sc->client);
1589   sc->client = NULL;
1590   GNUNET_FS_search_sync_ (sc);
1591   GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1592                                          &search_result_freeze_probes, sc);
1593   pi.status = GNUNET_FS_STATUS_SEARCH_PAUSED;
1594   sc->client_info = GNUNET_FS_search_make_status_ (&pi, sc->h, sc);
1595 }
1596
1597
1598 /**
1599  * Continue paused search.
1600  *
1601  * @param sc context for the search that should be resumed
1602  */
1603 void
1604 GNUNET_FS_search_continue (struct GNUNET_FS_SearchContext *sc)
1605 {
1606   struct GNUNET_FS_ProgressInfo pi;
1607
1608   GNUNET_assert (NULL == sc->client);
1609   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == sc->task);
1610   do_reconnect (sc, NULL);
1611   GNUNET_FS_search_sync_ (sc);
1612   pi.status = GNUNET_FS_STATUS_SEARCH_CONTINUED;
1613   sc->client_info = GNUNET_FS_search_make_status_ (&pi, sc->h, sc);
1614   GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1615                                          &search_result_resume_probes, sc);
1616 }
1617
1618
1619 /**
1620  * Signal stop for the given search result.
1621  *
1622  * @param cls the global FS handle
1623  * @param key the key for the search result (unused)
1624  * @param value the search result to free
1625  * @return #GNUNET_OK
1626  */
1627 static int
1628 search_result_stop (void *cls,
1629                     const struct GNUNET_HashCode *key,
1630                     void *value)
1631 {
1632   struct GNUNET_FS_SearchContext *sc = cls;
1633   struct GNUNET_FS_SearchResult *sr = value;
1634   struct GNUNET_FS_ProgressInfo pi;
1635
1636   GNUNET_FS_search_stop_probe_ (sr);
1637   if (NULL != sr->download)
1638   {
1639     sr->download->search = NULL;
1640     sr->download->top =
1641         GNUNET_FS_make_top (sr->download->h,
1642                             &GNUNET_FS_download_signal_suspend_,
1643                             sr->download);
1644     if (NULL != sr->download->serialization)
1645     {
1646       GNUNET_FS_remove_sync_file_ (sc->h,
1647                                    GNUNET_FS_SYNC_PATH_CHILD_DOWNLOAD,
1648                                    sr->download->serialization);
1649       GNUNET_free (sr->download->serialization);
1650       sr->download->serialization = NULL;
1651     }
1652     pi.status = GNUNET_FS_STATUS_DOWNLOAD_LOST_PARENT;
1653     GNUNET_FS_download_make_status_ (&pi, sr->download);
1654     GNUNET_FS_download_sync_ (sr->download);
1655     sr->download = NULL;
1656   }
1657   if (0 != sr->mandatory_missing)
1658   {
1659     /* client is unaware of search result as
1660        it does not match required keywords */
1661     GNUNET_break (NULL == sr->client_info);
1662     return GNUNET_OK;
1663   }
1664   pi.status = GNUNET_FS_STATUS_SEARCH_RESULT_STOPPED;
1665   pi.value.search.specifics.result_stopped.cctx = sr->client_info;
1666   pi.value.search.specifics.result_stopped.meta = sr->meta;
1667   pi.value.search.specifics.result_stopped.uri = sr->uri;
1668   sr->client_info = GNUNET_FS_search_make_status_ (&pi, sr->h, sc);
1669   return GNUNET_OK;
1670 }
1671
1672
1673 /**
1674  * Free the given search result.
1675  *
1676  * @param cls the global FS handle
1677  * @param key the key for the search result (unused)
1678  * @param value the search result to free
1679  * @return #GNUNET_OK
1680  */
1681 static int
1682 search_result_free (void *cls,
1683                     const struct GNUNET_HashCode *key,
1684                     void *value)
1685 {
1686   struct GNUNET_FS_SearchResult *sr = value;
1687
1688   if (NULL != sr->update_search)
1689   {
1690     GNUNET_FS_search_stop (sr->update_search);
1691     GNUNET_assert (NULL == sr->update_search);
1692   }
1693   GNUNET_break (NULL == sr->probe_ctx);
1694   GNUNET_break (GNUNET_SCHEDULER_NO_TASK == sr->probe_cancel_task);
1695   GNUNET_break (GNUNET_SCHEDULER_NO_TASK == sr->probe_ping_task);
1696   GNUNET_break (NULL == sr->client_info);
1697   GNUNET_free_non_null (sr->serialization);
1698   GNUNET_FS_uri_destroy (sr->uri);
1699   GNUNET_CONTAINER_meta_data_destroy (sr->meta);
1700   GNUNET_free_non_null (sr->keyword_bitmap);
1701   GNUNET_free (sr);
1702   return GNUNET_OK;
1703 }
1704
1705
1706 /**
1707  * Stop search for content.
1708  *
1709  * @param sc context for the search that should be stopped
1710  */
1711 void
1712 GNUNET_FS_search_stop (struct GNUNET_FS_SearchContext *sc)
1713 {
1714   struct GNUNET_FS_ProgressInfo pi;
1715   unsigned int i;
1716
1717   if (NULL != sc->top)
1718     GNUNET_FS_end_top (sc->h, sc->top);
1719   GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1720                                          &search_result_stop, sc);
1721   if (NULL != sc->psearch_result)
1722     sc->psearch_result->update_search = NULL;
1723   if (NULL != sc->serialization)
1724   {
1725     GNUNET_FS_remove_sync_file_ (sc->h,
1726                                  (sc->psearch_result !=
1727                                   NULL) ? GNUNET_FS_SYNC_PATH_CHILD_SEARCH :
1728                                  GNUNET_FS_SYNC_PATH_MASTER_SEARCH,
1729                                  sc->serialization);
1730     GNUNET_FS_remove_sync_dir_ (sc->h,
1731                                 (sc->psearch_result !=
1732                                  NULL) ? GNUNET_FS_SYNC_PATH_CHILD_SEARCH :
1733                                 GNUNET_FS_SYNC_PATH_MASTER_SEARCH,
1734                                 sc->serialization);
1735     GNUNET_free (sc->serialization);
1736   }
1737   pi.status = GNUNET_FS_STATUS_SEARCH_STOPPED;
1738   sc->client_info = GNUNET_FS_search_make_status_ (&pi, sc->h, sc);
1739   GNUNET_break (NULL == sc->client_info);
1740   if (GNUNET_SCHEDULER_NO_TASK != sc->task)
1741     GNUNET_SCHEDULER_cancel (sc->task);
1742   if (NULL != sc->client)
1743     GNUNET_CLIENT_disconnect (sc->client);
1744   GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1745                                          &search_result_free, sc);
1746   GNUNET_CONTAINER_multihashmap_destroy (sc->master_result_map);
1747   if (NULL != sc->requests)
1748   {
1749     GNUNET_assert (GNUNET_FS_uri_test_ksk (sc->uri));
1750     for (i = 0; i < sc->uri->data.ksk.keywordCount; i++)
1751       GNUNET_CONTAINER_multihashmap_destroy (sc->requests[i].results);
1752   }
1753   GNUNET_free_non_null (sc->requests);
1754   GNUNET_free_non_null (sc->emsg);
1755   GNUNET_FS_uri_destroy (sc->uri);
1756   GNUNET_free (sc);
1757 }
1758
1759 /* end of fs_search.c */