more information why nat tests fail
[oweals/gnunet.git] / src / fs / fs_search.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001-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 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, &key,
546                                                   &test_result_present,
547                                                   (void *) uri))
548     return;                     /* duplicate result */
549   /* try to find search result in master map */
550   grc.sr = NULL;
551   grc.uri = uri;
552   GNUNET_CONTAINER_multihashmap_get_multiple (sc->master_result_map, &key,
553                                               &get_result_present, &grc);
554   sr = grc.sr;
555   is_new = (NULL == sr) || (sr->mandatory_missing > 0);
556   if (NULL == sr)
557   {
558     sr = GNUNET_new (struct GNUNET_FS_SearchResult);
559     sr->h = sc->h;
560     sr->sc = sc;
561     sr->anonymity = sc->anonymity;
562     sr->uri = GNUNET_FS_uri_dup (uri);
563     sr->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
564     sr->mandatory_missing = sc->mandatory_count;
565     sr->key = key;
566     sr->keyword_bitmap = GNUNET_malloc ((sc->uri->data.ksk.keywordCount + 7) / 8); /* round up, count bits */
567     GNUNET_CONTAINER_multihashmap_put (sc->master_result_map, &key, sr,
568                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
569   }
570   else
571   {
572     GNUNET_CONTAINER_meta_data_merge (sr->meta, meta);
573   }
574   koff = ent - sc->requests;
575   GNUNET_assert ( (ent >= sc->requests) && (koff < sc->uri->data.ksk.keywordCount));
576   sr->keyword_bitmap[koff / 8] |= (1 << (koff % 8));
577   /* check if mandatory satisfied */
578   if (ent->mandatory)
579     sr->mandatory_missing--;
580   else
581     sr->optional_support++;
582   if (0 != sr->mandatory_missing)
583     return;
584   if (is_new)
585     notify_client_chk_result (sc, sr);
586   else
587     notify_client_chk_update (sc, sr);
588   GNUNET_FS_search_result_sync_ (sr);
589   GNUNET_FS_search_start_probe_ (sr);
590 }
591
592
593 /**
594  * Start search for content, internal API.
595  *
596  * @param h handle to the file sharing subsystem
597  * @param uri specifies the search parameters; can be
598  *        a KSK URI or an SKS URI.
599  * @param anonymity desired level of anonymity
600  * @param options options for the search
601  * @param cctx client context
602  * @param psearch parent search result (for namespace update searches)
603  * @return context that can be used to control the search
604  */
605 static struct GNUNET_FS_SearchContext *
606 search_start (struct GNUNET_FS_Handle *h, const struct GNUNET_FS_Uri *uri,
607               uint32_t anonymity, enum GNUNET_FS_SearchOptions options,
608               void *cctx, struct GNUNET_FS_SearchResult *psearch);
609
610
611 /**
612  * We have received an SKS result.  Start searching for updates and
613  * notify the client if it is a new result.
614  *
615  * @param sc context for the overall query
616  * @param id_update identifier for updates, NULL for none
617  * @param uri the URI that was found
618  * @param meta metadata associated with the URI
619   */
620 static void
621 process_sks_result (struct GNUNET_FS_SearchContext *sc,
622                     const char *id_update,
623                     const struct GNUNET_FS_Uri *uri,
624                     const struct GNUNET_CONTAINER_MetaData *meta)
625 {
626   struct GNUNET_FS_Uri uu;
627   struct GNUNET_HashCode key;
628   struct GNUNET_FS_SearchResult *sr;
629
630   /* check if new */
631   GNUNET_assert (NULL != sc);
632   GNUNET_FS_uri_to_key (uri, &key);
633   GNUNET_CRYPTO_hash_xor (&uri->data.chk.chk.key, &uri->data.chk.chk.query,
634                           &key);
635   if (GNUNET_SYSERR ==
636       GNUNET_CONTAINER_multihashmap_get_multiple (sc->master_result_map, &key,
637                                                   &test_result_present,
638                                                   (void *) uri))
639     return;                     /* duplicate result */
640   sr = GNUNET_new (struct GNUNET_FS_SearchResult);
641   sr->h = sc->h;
642   sr->sc = sc;
643   sr->anonymity = sc->anonymity;
644   sr->uri = GNUNET_FS_uri_dup (uri);
645   sr->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
646   sr->key = key;
647   GNUNET_CONTAINER_multihashmap_put (sc->master_result_map, &key, sr,
648                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
649   GNUNET_FS_search_result_sync_ (sr);
650   GNUNET_FS_search_start_probe_ (sr);
651   /* notify client */
652   notify_client_chk_result (sc, sr);
653   /* search for updates */
654   if (0 == strlen (id_update))
655     return;                     /* no updates */
656   uu.type = GNUNET_FS_URI_SKS;
657   uu.data.sks.ns = sc->uri->data.sks.ns;
658   uu.data.sks.identifier = GNUNET_strdup (id_update);
659   (void) search_start (sc->h, &uu, sc->anonymity, sc->options, NULL, sr);
660   GNUNET_free (uu.data.sks.identifier);
661 }
662
663
664 /**
665  * Decrypt a ublock using a 'keyword' as the passphrase.  Given the
666  * KSK public key derived from the keyword, this function looks up
667  * the original keyword in the search context and decrypts the
668  * given ciphertext block.
669  *
670  * @param sc search context with the keywords
671  * @param dpub derived public key used for the search
672  * @param edata encrypted data
673  * @param edata_size number of bytes in @a edata (and @a data)
674  * @param data where to store the plaintext
675  * @return keyword index on success, #GNUNET_SYSERR on error (no such
676  *         keyword, internal error)
677  */
678 static int
679 decrypt_block_with_keyword (const struct GNUNET_FS_SearchContext *sc,
680                             const struct GNUNET_CRYPTO_EcdsaPublicKey *dpub,
681                             const void *edata,
682                             size_t edata_size,
683                             char *data)
684 {
685   const struct GNUNET_CRYPTO_EcdsaPrivateKey *anon;
686   struct GNUNET_CRYPTO_EcdsaPublicKey anon_pub;
687   unsigned int i;
688
689   /* find key */
690   for (i = 0; i < sc->uri->data.ksk.keywordCount; i++)
691     if (0 == memcmp (dpub,
692                      &sc->requests[i].dpub,
693                      sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey)))
694       break;
695   if (i == sc->uri->data.ksk.keywordCount)
696   {
697     /* oops, does not match any of our keywords!? */
698     GNUNET_break (0);
699     return GNUNET_SYSERR;
700   }
701   /* decrypt */
702   anon = GNUNET_CRYPTO_ecdsa_key_get_anonymous ();
703   GNUNET_CRYPTO_ecdsa_key_get_public (anon, &anon_pub);
704   GNUNET_FS_ublock_decrypt_ (edata, edata_size,
705                              &anon_pub,
706                              sc->requests[i].keyword,
707                              data);
708   return i;
709 }
710
711
712 /**
713  * Process a keyword search result.  The actual type of block is
714  * a UBlock; we know it is a keyword search result because that's
715  * what we were searching for.
716  *
717  * @param sc our search context
718  * @param ub the ublock with the keyword search result
719  * @param size size of @a ub
720  */
721 static void
722 process_kblock (struct GNUNET_FS_SearchContext *sc,
723                 const struct UBlock *ub,
724                 size_t size)
725 {
726   size_t j;
727   char pt[size - sizeof (struct UBlock)];
728   const char *eos;
729   struct GNUNET_CONTAINER_MetaData *meta;
730   struct GNUNET_FS_Uri *uri;
731   char *emsg;
732   int i;
733
734   if (-1 == (i = decrypt_block_with_keyword (sc,
735                                              &ub->verification_key,
736                                              &ub[1],
737                                              size - sizeof (struct UBlock),
738                                              pt)))
739     return;
740   /* parse; pt[0] is just '\0', so we skip over that */
741   eos = memchr (&pt[1], '\0', sizeof (pt) - 1);
742   if (NULL == eos)
743   {
744     GNUNET_break_op (0);
745     return;
746   }
747   if (NULL == (uri = GNUNET_FS_uri_parse (&pt[1], &emsg)))
748   {
749     GNUNET_break_op (0);        /* ublock malformed */
750     GNUNET_free_non_null (emsg);
751     return;
752   }
753   j = eos - pt + 1;
754   if (sizeof (pt) == j)
755     meta = GNUNET_CONTAINER_meta_data_create ();
756   else
757     meta = GNUNET_CONTAINER_meta_data_deserialize (&pt[j], sizeof (pt) - j);
758   if (NULL == meta)
759   {
760     GNUNET_break_op (0);        /* ublock malformed */
761     GNUNET_FS_uri_destroy (uri);
762     return;
763   }
764   process_ksk_result (sc, &sc->requests[i], uri, meta);
765
766   /* clean up */
767   GNUNET_CONTAINER_meta_data_destroy (meta);
768   GNUNET_FS_uri_destroy (uri);
769 }
770
771
772 /**
773  * Process a namespace-search result.  The actual type of block is
774  * a UBlock; we know it is a namespace search result because that's
775  * what we were searching for.
776  *
777  * @param sc our search context
778  * @param ub the ublock with a namespace result
779  * @param size size of @a ub
780  */
781 static void
782 process_sblock (struct GNUNET_FS_SearchContext *sc,
783                 const struct UBlock *ub,
784                 size_t size)
785 {
786   size_t len = size - sizeof (struct UBlock);
787   char pt[len];
788   struct GNUNET_FS_Uri *uri;
789   struct GNUNET_CONTAINER_MetaData *meta;
790   const char *id;
791   const char *uris;
792   size_t off;
793   char *emsg;
794
795   GNUNET_FS_ublock_decrypt_ (&ub[1], len,
796                              &sc->uri->data.sks.ns,
797                              sc->uri->data.sks.identifier,
798                              pt);
799   /* parse */
800   if (0 == (off = GNUNET_STRINGS_buffer_tokenize (pt, len, 2, &id, &uris)))
801   {
802     GNUNET_break_op (0);        /* ublock malformed */
803     return;
804   }
805   if (NULL == (meta = GNUNET_CONTAINER_meta_data_deserialize (&pt[off], len - off)))
806   {
807     GNUNET_break_op (0);        /* ublock malformed */
808     return;
809   }
810   if (NULL == (uri = GNUNET_FS_uri_parse (uris, &emsg)))
811   {
812     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
813                 _("Failed to parse URI `%s': %s\n"),
814                 uris, emsg);
815     GNUNET_break_op (0);        /* ublock malformed */
816     GNUNET_free_non_null (emsg);
817     GNUNET_CONTAINER_meta_data_destroy (meta);
818     return;
819   }
820   /* process */
821   process_sks_result (sc, id, uri, meta);
822   /* clean up */
823   GNUNET_FS_uri_destroy (uri);
824   GNUNET_CONTAINER_meta_data_destroy (meta);
825 }
826
827
828 /**
829  * Process a search result.
830  *
831  * @param sc our search context
832  * @param type type of the result
833  * @param expiration when it will expire
834  * @param data the (encrypted) response
835  * @param size size of @a data
836  */
837 static void
838 process_result (struct GNUNET_FS_SearchContext *sc,
839                 enum GNUNET_BLOCK_Type type,
840                 struct GNUNET_TIME_Absolute expiration,
841                 const void *data,
842                 size_t size)
843 {
844   if (GNUNET_TIME_absolute_get_duration (expiration).rel_value_us > 0)
845   {
846     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
847                 "Result received has already expired.\n");
848     return;                     /* result expired */
849   }
850   switch (type)
851   {
852   case GNUNET_BLOCK_TYPE_FS_UBLOCK:
853     if (GNUNET_FS_URI_SKS == sc->uri->type)
854       process_sblock (sc, data, size);
855     else
856       process_kblock (sc, data, size);
857     break;
858   case GNUNET_BLOCK_TYPE_ANY:
859     GNUNET_break (0);
860     break;
861   case GNUNET_BLOCK_TYPE_FS_DBLOCK:
862     GNUNET_break (0);
863     break;
864   case GNUNET_BLOCK_TYPE_FS_ONDEMAND:
865     GNUNET_break (0);
866     break;
867   case GNUNET_BLOCK_TYPE_FS_IBLOCK:
868     GNUNET_break (0);
869     break;
870   default:
871     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
872                 _("Got result with unknown block type `%d', ignoring"), type);
873     break;
874   }
875 }
876
877
878 /**
879  * Shutdown any existing connection to the FS
880  * service and try to establish a fresh one
881  * (and then re-transmit our search request).
882  *
883  * @param sc the search to reconnec
884  */
885 static void
886 try_reconnect (struct GNUNET_FS_SearchContext *sc);
887
888
889 /**
890  * Type of a function to call when we receive a message
891  * from the service.
892  *
893  * @param cls closure
894  * @param msg message received, NULL on timeout or fatal error
895  */
896 static void
897 receive_results (void *cls, const struct GNUNET_MessageHeader *msg)
898 {
899   struct GNUNET_FS_SearchContext *sc = cls;
900   const struct ClientPutMessage *cm;
901   uint16_t msize;
902
903   if ((NULL == msg) || (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_FS_PUT) ||
904       (ntohs (msg->size) <= sizeof (struct ClientPutMessage)))
905   {
906     try_reconnect (sc);
907     return;
908   }
909   msize = ntohs (msg->size);
910   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
911               "Receiving %u bytes of result from fs service\n", msize);
912   cm = (const struct ClientPutMessage *) msg;
913   process_result (sc, ntohl (cm->type),
914                   GNUNET_TIME_absolute_ntoh (cm->expiration), &cm[1],
915                   msize - sizeof (struct ClientPutMessage));
916   /* continue receiving */
917   GNUNET_CLIENT_receive (sc->client, &receive_results, sc,
918                          GNUNET_TIME_UNIT_FOREVER_REL);
919 }
920
921
922 /**
923  * Schedule the transmission of the (next) search request
924  * to the service.
925  *
926  * @param sc context for the search
927  */
928 static void
929 schedule_transmit_search_request (struct GNUNET_FS_SearchContext *sc);
930
931
932 /**
933  * Closure for 'build_result_set'.
934  */
935 struct MessageBuilderContext
936 {
937   /**
938    * How many entries can we store to xoff.
939    */
940   unsigned int put_cnt;
941
942   /**
943    * How many entries should we skip.
944    */
945   unsigned int skip_cnt;
946
947   /**
948    * Where to store the keys.
949    */
950   struct GNUNET_HashCode *xoff;
951
952   /**
953    * Search context we are iterating for.
954    */
955   struct GNUNET_FS_SearchContext *sc;
956
957   /**
958    * Keyword offset the search result must match (0 for SKS)
959    */
960   unsigned int keyword_offset;
961 };
962
963
964 /**
965  * Iterating over the known results, pick those matching the given
966  * result range and store their keys at 'xoff'.
967  *
968  * @param cls the `struct MessageBuilderContext`
969  * @param key key for a result
970  * @param value the search result
971  * @return #GNUNET_OK to continue iterating
972  */
973 static int
974 build_result_set (void *cls, const struct GNUNET_HashCode * key, void *value)
975 {
976   struct MessageBuilderContext *mbc = cls;
977   struct GNUNET_FS_SearchResult *sr = value;
978
979   if ( (NULL != sr->keyword_bitmap) &&
980        (0 == (sr->keyword_bitmap[mbc->keyword_offset / 8] & (1 << (mbc->keyword_offset % 8)))) )
981     return GNUNET_OK; /* have no match for this keyword yet */
982   if (mbc->skip_cnt > 0)
983   {
984     mbc->skip_cnt--;
985     return GNUNET_OK;
986   }
987   if (0 == mbc->put_cnt)
988     return GNUNET_SYSERR;
989   mbc->sc->search_request_map_offset++;
990   mbc->xoff[--mbc->put_cnt] = *key;
991
992   return GNUNET_OK;
993 }
994
995
996 /**
997  * Iterating over the known results, count those
998  * matching the given result range and increment
999  * put count for each.
1000  *
1001  * @param cls the `struct MessageBuilderContext`
1002  * @param key key for a result
1003  * @param value the search result
1004  * @return #GNUNET_OK to continue iterating
1005  */
1006 static int
1007 find_result_set (void *cls, const struct GNUNET_HashCode * key, void *value)
1008 {
1009   struct MessageBuilderContext *mbc = cls;
1010   struct GNUNET_FS_SearchResult *sr = value;
1011
1012   if ( (NULL != sr->keyword_bitmap) &&
1013        (0 == (sr->keyword_bitmap[mbc->keyword_offset / 8] & (1 << (mbc->keyword_offset % 8)))) )
1014     return GNUNET_OK; /* have no match for this keyword yet */
1015   mbc->put_cnt++;
1016   return GNUNET_OK;
1017 }
1018
1019
1020 /**
1021  * We're ready to transmit the search request to the
1022  * file-sharing service.  Do it.
1023  *
1024  * @param cls closure
1025  * @param size number of bytes available in @a buf
1026  * @param buf where the callee should write the message
1027  * @return number of bytes written to @a buf
1028  */
1029 static size_t
1030 transmit_search_request (void *cls, size_t size, void *buf)
1031 {
1032   struct GNUNET_FS_SearchContext *sc = cls;
1033   struct MessageBuilderContext mbc;
1034   size_t msize;
1035   struct SearchMessage *sm;
1036   struct GNUNET_CRYPTO_EcdsaPublicKey dpub;
1037   unsigned int sqms;
1038   uint32_t options;
1039
1040   if (NULL == buf)
1041   {
1042     try_reconnect (sc);
1043     return 0;
1044   }
1045   mbc.sc = sc;
1046   mbc.skip_cnt = sc->search_request_map_offset;
1047   sm = buf;
1048   sm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_START_SEARCH);
1049   mbc.xoff = (struct GNUNET_HashCode *) & sm[1];
1050   options = SEARCH_MESSAGE_OPTION_NONE;
1051   if (0 != (sc->options & GNUNET_FS_SEARCH_OPTION_LOOPBACK_ONLY))
1052     options |= SEARCH_MESSAGE_OPTION_LOOPBACK_ONLY;
1053   if (GNUNET_FS_uri_test_ksk (sc->uri))
1054   {
1055     msize = sizeof (struct SearchMessage);
1056     GNUNET_assert (size >= msize);
1057     mbc.keyword_offset = sc->keyword_offset;
1058     /* calculate total number of known results (in put_cnt => sqms) */
1059     mbc.put_cnt = 0;
1060     GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1061                                            &find_result_set, &mbc);
1062     sqms = mbc.put_cnt;
1063     /* calculate how many results we can send in this message */
1064     mbc.put_cnt = (size - msize) / sizeof (struct GNUNET_HashCode);
1065     mbc.put_cnt = GNUNET_MIN (mbc.put_cnt, sqms - mbc.skip_cnt);
1066     if (sc->search_request_map_offset < sqms)
1067       GNUNET_assert (mbc.put_cnt > 0);
1068
1069     /* now build message */
1070     msize += sizeof (struct GNUNET_HashCode) * mbc.put_cnt;
1071     sm->header.size = htons (msize);
1072     sm->type = htonl (GNUNET_BLOCK_TYPE_FS_UBLOCK);
1073     sm->anonymity_level = htonl (sc->anonymity);
1074     memset (&sm->target, 0, sizeof (struct GNUNET_PeerIdentity));
1075     sm->query = sc->requests[sc->keyword_offset].uquery;
1076     GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1077                                            &build_result_set, &mbc);
1078     GNUNET_assert (sqms >= sc->search_request_map_offset);
1079     if (sqms != sc->search_request_map_offset)
1080     {
1081       /* more requesting to be done... */
1082       sm->options = htonl (options | SEARCH_MESSAGE_OPTION_CONTINUED);
1083       schedule_transmit_search_request (sc);
1084       return msize;
1085     }
1086     sm->options = htonl (options);
1087     sc->keyword_offset++;
1088     if (sc->uri->data.ksk.keywordCount != sc->keyword_offset)
1089     {
1090       /* more requesting to be done... */
1091       schedule_transmit_search_request (sc);
1092       return msize;
1093     }
1094   }
1095   else
1096   {
1097     GNUNET_assert (GNUNET_FS_uri_test_sks (sc->uri));
1098     msize = sizeof (struct SearchMessage);
1099     GNUNET_assert (size >= msize);
1100     sm->type = htonl (GNUNET_BLOCK_TYPE_FS_UBLOCK);
1101     sm->anonymity_level = htonl (sc->anonymity);
1102     memset (&sm->target, 0, sizeof (struct GNUNET_PeerIdentity));
1103     GNUNET_CRYPTO_ecdsa_public_key_derive (&sc->uri->data.sks.ns,
1104                                          sc->uri->data.sks.identifier,
1105                                          "fs-ublock",
1106                                          &dpub);
1107     GNUNET_CRYPTO_hash (&dpub,
1108                         sizeof (dpub),
1109                         &sm->query);
1110     mbc.put_cnt = (size - msize) / sizeof (struct GNUNET_HashCode);
1111     sqms = GNUNET_CONTAINER_multihashmap_size (sc->master_result_map);
1112     mbc.put_cnt = GNUNET_MIN (mbc.put_cnt, sqms - mbc.skip_cnt);
1113     mbc.keyword_offset = 0;
1114     if (sc->search_request_map_offset < sqms)
1115       GNUNET_assert (mbc.put_cnt > 0);
1116     msize += sizeof (struct GNUNET_HashCode) * mbc.put_cnt;
1117     GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1118                                            &build_result_set, &mbc);
1119     sm->header.size = htons (msize);
1120     GNUNET_assert (sqms >= sc->search_request_map_offset);
1121     if (sqms != 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   }
1130   GNUNET_CLIENT_receive (sc->client, &receive_results, sc,
1131                          GNUNET_TIME_UNIT_FOREVER_REL);
1132   return msize;
1133 }
1134
1135
1136 /**
1137  * Schedule the transmission of the (next) search request
1138  * to the service.
1139  *
1140  * @param sc context for the search
1141  */
1142 static void
1143 schedule_transmit_search_request (struct GNUNET_FS_SearchContext *sc)
1144 {
1145   size_t size;
1146   unsigned int sqms;
1147   unsigned int fit;
1148
1149   size = sizeof (struct SearchMessage);
1150   sqms =
1151       GNUNET_CONTAINER_multihashmap_size (sc->master_result_map) -
1152       sc->search_request_map_offset;
1153   fit = (GNUNET_SERVER_MAX_MESSAGE_SIZE - 1 - size) / sizeof (struct GNUNET_HashCode);
1154   fit = GNUNET_MIN (fit, sqms);
1155   size += sizeof (struct GNUNET_HashCode) * fit;
1156   GNUNET_CLIENT_notify_transmit_ready (sc->client, size,
1157                                        GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1158                                        GNUNET_NO, &transmit_search_request, sc);
1159
1160 }
1161
1162
1163 /**
1164  * Reconnect to the FS service and transmit
1165  * our queries NOW.
1166  *
1167  * @param cls our search context
1168  * @param tc unused
1169  */
1170 static void
1171 do_reconnect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1172 {
1173   struct GNUNET_FS_SearchContext *sc = cls;
1174   struct GNUNET_CLIENT_Connection *client;
1175
1176   sc->task = GNUNET_SCHEDULER_NO_TASK;
1177   client = GNUNET_CLIENT_connect ("fs", sc->h->cfg);
1178   if (NULL == client)
1179   {
1180     try_reconnect (sc);
1181     return;
1182   }
1183   sc->client = client;
1184   sc->search_request_map_offset = 0;
1185   sc->keyword_offset = 0;
1186   schedule_transmit_search_request (sc);
1187 }
1188
1189
1190 /**
1191  * Shutdown any existing connection to the FS
1192  * service and try to establish a fresh one
1193  * (and then re-transmit our search request).
1194  *
1195  * @param sc the search to reconnec
1196  */
1197 static void
1198 try_reconnect (struct GNUNET_FS_SearchContext *sc)
1199 {
1200   if (NULL != sc->client)
1201   {
1202     GNUNET_CLIENT_disconnect (sc->client);
1203     sc->client = NULL;
1204   }
1205   sc->reconnect_backoff = GNUNET_TIME_STD_BACKOFF (sc->reconnect_backoff);
1206   sc->task =
1207       GNUNET_SCHEDULER_add_delayed (sc->reconnect_backoff,
1208                                     &do_reconnect,
1209                                     sc);
1210 }
1211
1212
1213 /**
1214  * Start search for content, internal API.
1215  *
1216  * @param h handle to the file sharing subsystem
1217  * @param uri specifies the search parameters; can be
1218  *        a KSK URI or an SKS URI.
1219  * @param anonymity desired level of anonymity
1220  * @param options options for the search
1221  * @param cctx initial value for the client context
1222  * @param psearch parent search result (for namespace update searches)
1223  * @return context that can be used to control the search
1224  */
1225 static struct GNUNET_FS_SearchContext *
1226 search_start (struct GNUNET_FS_Handle *h,
1227               const struct GNUNET_FS_Uri *uri,
1228               uint32_t anonymity,
1229               enum GNUNET_FS_SearchOptions options,
1230               void *cctx,
1231               struct GNUNET_FS_SearchResult *psearch)
1232 {
1233   struct GNUNET_FS_SearchContext *sc;
1234   struct GNUNET_FS_ProgressInfo pi;
1235
1236   sc = GNUNET_new (struct GNUNET_FS_SearchContext);
1237   sc->h = h;
1238   sc->options = options;
1239   sc->uri = GNUNET_FS_uri_dup (uri);
1240   sc->anonymity = anonymity;
1241   sc->start_time = GNUNET_TIME_absolute_get ();
1242   if (NULL != psearch)
1243   {
1244     sc->psearch_result = psearch;
1245     psearch->update_search = sc;
1246   }
1247   sc->master_result_map = GNUNET_CONTAINER_multihashmap_create (16, GNUNET_NO);
1248   sc->client_info = cctx;
1249   if (GNUNET_OK != GNUNET_FS_search_start_searching_ (sc))
1250   {
1251     GNUNET_FS_uri_destroy (sc->uri);
1252     GNUNET_CONTAINER_multihashmap_destroy (sc->master_result_map);
1253     GNUNET_free (sc);
1254     return NULL;
1255   }
1256   GNUNET_FS_search_sync_ (sc);
1257   pi.status = GNUNET_FS_STATUS_SEARCH_START;
1258   sc->client_info = GNUNET_FS_search_make_status_ (&pi, sc->h, sc);
1259   return sc;
1260 }
1261
1262
1263 /**
1264  * Build the request and actually initiate the search using the
1265  * GNUnet FS service.
1266  *
1267  * @param sc search context
1268  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1269  */
1270 int
1271 GNUNET_FS_search_start_searching_ (struct GNUNET_FS_SearchContext *sc)
1272 {
1273   unsigned int i;
1274   const char *keyword;
1275   const struct GNUNET_CRYPTO_EcdsaPrivateKey *anon;
1276   struct GNUNET_CRYPTO_EcdsaPublicKey anon_pub;
1277   struct SearchRequestEntry *sre;
1278
1279   GNUNET_assert (NULL == sc->client);
1280   if (GNUNET_FS_uri_test_ksk (sc->uri))
1281   {
1282     GNUNET_assert (0 != sc->uri->data.ksk.keywordCount);
1283     anon = GNUNET_CRYPTO_ecdsa_key_get_anonymous ();
1284     GNUNET_CRYPTO_ecdsa_key_get_public (anon, &anon_pub);
1285     sc->requests =
1286         GNUNET_malloc (sizeof (struct SearchRequestEntry) *
1287                        sc->uri->data.ksk.keywordCount);
1288     for (i = 0; i < sc->uri->data.ksk.keywordCount; i++)
1289     {
1290       keyword = &sc->uri->data.ksk.keywords[i][1];
1291       sre = &sc->requests[i];
1292       sre->keyword = GNUNET_strdup (keyword);
1293       GNUNET_CRYPTO_ecdsa_public_key_derive (&anon_pub,
1294                                            keyword,
1295                                            "fs-ublock",
1296                                            &sre->dpub);
1297       GNUNET_CRYPTO_hash (&sre->dpub,
1298                           sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey),
1299                           &sre->uquery);
1300       sre->mandatory = (sc->uri->data.ksk.keywords[i][0] == '+');
1301       if (sre->mandatory)
1302         sc->mandatory_count++;
1303       sre->results = GNUNET_CONTAINER_multihashmap_create (4, GNUNET_NO);
1304     }
1305   }
1306   sc->client = GNUNET_CLIENT_connect ("fs", sc->h->cfg);
1307   if (NULL == sc->client)
1308     return GNUNET_SYSERR;
1309   schedule_transmit_search_request (sc);
1310   return GNUNET_OK;
1311 }
1312
1313
1314 /**
1315  * Freeze probes for the given search result.
1316  *
1317  * @param cls the global FS handle
1318  * @param key the key for the search result (unused)
1319  * @param value the search result to free
1320  * @return #GNUNET_OK
1321  */
1322 static int
1323 search_result_freeze_probes (void *cls,
1324                              const struct GNUNET_HashCode *key,
1325                              void *value)
1326 {
1327   struct GNUNET_FS_SearchResult *sr = value;
1328
1329   if (NULL != sr->probe_ctx)
1330   {
1331     GNUNET_FS_download_stop (sr->probe_ctx, GNUNET_YES);
1332     sr->probe_ctx = NULL;
1333   }
1334   if (GNUNET_SCHEDULER_NO_TASK != sr->probe_ping_task)
1335   {
1336     GNUNET_SCHEDULER_cancel (sr->probe_ping_task);
1337     sr->probe_ping_task = GNUNET_SCHEDULER_NO_TASK;
1338   }
1339   if (GNUNET_SCHEDULER_NO_TASK != sr->probe_cancel_task)
1340   {
1341     GNUNET_SCHEDULER_cancel (sr->probe_cancel_task);
1342     sr->probe_cancel_task = GNUNET_SCHEDULER_NO_TASK;
1343   }
1344   if (NULL != sr->update_search)
1345     GNUNET_FS_search_pause (sr->update_search);
1346   return GNUNET_OK;
1347 }
1348
1349
1350 /**
1351  * Resume probes for the given search result.
1352  *
1353  * @param cls the global FS handle
1354  * @param key the key for the search result (unused)
1355  * @param value the search result to free
1356  * @return #GNUNET_OK
1357  */
1358 static int
1359 search_result_resume_probes (void *cls,
1360                              const struct GNUNET_HashCode * key,
1361                              void *value)
1362 {
1363   struct GNUNET_FS_SearchResult *sr = value;
1364
1365   GNUNET_FS_search_start_probe_ (sr);
1366   if (NULL != sr->update_search)
1367     GNUNET_FS_search_continue (sr->update_search);
1368   return GNUNET_OK;
1369 }
1370
1371
1372 /**
1373  * Signal suspend and free the given search result.
1374  *
1375  * @param cls the global FS handle
1376  * @param key the key for the search result (unused)
1377  * @param value the search result to free
1378  * @return #GNUNET_OK
1379  */
1380 static int
1381 search_result_suspend (void *cls,
1382                        const struct GNUNET_HashCode * key,
1383                        void *value)
1384 {
1385   struct GNUNET_FS_SearchContext *sc = cls;
1386   struct GNUNET_FS_SearchResult *sr = value;
1387   struct GNUNET_FS_ProgressInfo pi;
1388
1389   if (NULL != sr->download)
1390   {
1391     GNUNET_FS_download_signal_suspend_ (sr->download);
1392     sr->download = NULL;
1393   }
1394   if (NULL != sr->update_search)
1395   {
1396     GNUNET_FS_search_signal_suspend_ (sr->update_search);
1397     sr->update_search = NULL;
1398   }
1399   GNUNET_FS_search_stop_probe_ (sr);
1400   pi.status = GNUNET_FS_STATUS_SEARCH_RESULT_SUSPEND;
1401   pi.value.search.specifics.result_suspend.cctx = sr->client_info;
1402   pi.value.search.specifics.result_suspend.meta = sr->meta;
1403   pi.value.search.specifics.result_suspend.uri = sr->uri;
1404   sr->client_info = GNUNET_FS_search_make_status_ (&pi, sc->h, sc);
1405   GNUNET_break (NULL == sr->client_info);
1406   GNUNET_free_non_null (sr->serialization);
1407   GNUNET_FS_uri_destroy (sr->uri);
1408   GNUNET_CONTAINER_meta_data_destroy (sr->meta);
1409   GNUNET_free_non_null (sr->keyword_bitmap);
1410   GNUNET_free (sr);
1411   return GNUNET_OK;
1412 }
1413
1414
1415 /**
1416  * Create SUSPEND event for the given search operation
1417  * and then clean up our state (without stop signal).
1418  *
1419  * @param cls the `struct GNUNET_FS_SearchContext` to signal for
1420  */
1421 void
1422 GNUNET_FS_search_signal_suspend_ (void *cls)
1423 {
1424   struct GNUNET_FS_SearchContext *sc = cls;
1425   struct GNUNET_FS_ProgressInfo pi;
1426   unsigned int i;
1427
1428   GNUNET_FS_end_top (sc->h, sc->top);
1429   GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1430                                          &search_result_suspend, sc);
1431   pi.status = GNUNET_FS_STATUS_SEARCH_SUSPEND;
1432   sc->client_info = GNUNET_FS_search_make_status_ (&pi, sc->h, sc);
1433   GNUNET_break (NULL == sc->client_info);
1434   if (sc->task != GNUNET_SCHEDULER_NO_TASK)
1435   {
1436     GNUNET_SCHEDULER_cancel (sc->task);
1437     sc->task = GNUNET_SCHEDULER_NO_TASK;
1438   }
1439   if (NULL != sc->client)
1440   {
1441     GNUNET_CLIENT_disconnect (sc->client);
1442     sc->client = NULL;
1443   }
1444   GNUNET_CONTAINER_multihashmap_destroy (sc->master_result_map);
1445   if (NULL != sc->requests)
1446   {
1447     GNUNET_assert (GNUNET_FS_uri_test_ksk (sc->uri));
1448     for (i = 0; i < sc->uri->data.ksk.keywordCount; i++)
1449     {
1450       GNUNET_CONTAINER_multihashmap_destroy (sc->requests[i].results);
1451       GNUNET_free (sc->requests[i].keyword);
1452     }
1453   }
1454   GNUNET_free_non_null (sc->requests);
1455   GNUNET_free_non_null (sc->emsg);
1456   GNUNET_FS_uri_destroy (sc->uri);
1457   GNUNET_free_non_null (sc->serialization);
1458   GNUNET_free (sc);
1459 }
1460
1461
1462 /**
1463  * Start search for content.
1464  *
1465  * @param h handle to the file sharing subsystem
1466  * @param uri specifies the search parameters; can be
1467  *        a KSK URI or an SKS URI.
1468  * @param anonymity desired level of anonymity
1469  * @param options options for the search
1470  * @param cctx initial value for the client context
1471  * @return context that can be used to control the search
1472  */
1473 struct GNUNET_FS_SearchContext *
1474 GNUNET_FS_search_start (struct GNUNET_FS_Handle *h,
1475                         const struct GNUNET_FS_Uri *uri, uint32_t anonymity,
1476                         enum GNUNET_FS_SearchOptions options, void *cctx)
1477 {
1478   struct GNUNET_FS_SearchContext *ret;
1479
1480   ret = search_start (h, uri, anonymity, options, cctx, NULL);
1481   if (NULL == ret)
1482     return NULL;
1483   ret->top = GNUNET_FS_make_top (h, &GNUNET_FS_search_signal_suspend_, ret);
1484   return ret;
1485 }
1486
1487
1488 /**
1489  * Pause search.
1490  *
1491  * @param sc context for the search that should be paused
1492  */
1493 void
1494 GNUNET_FS_search_pause (struct GNUNET_FS_SearchContext *sc)
1495 {
1496   struct GNUNET_FS_ProgressInfo pi;
1497
1498   if (GNUNET_SCHEDULER_NO_TASK != sc->task)
1499   {
1500     GNUNET_SCHEDULER_cancel (sc->task);
1501     sc->task = GNUNET_SCHEDULER_NO_TASK;
1502   }
1503   if (NULL != sc->client)
1504     GNUNET_CLIENT_disconnect (sc->client);
1505   sc->client = NULL;
1506   GNUNET_FS_search_sync_ (sc);
1507   GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1508                                          &search_result_freeze_probes, sc);
1509   pi.status = GNUNET_FS_STATUS_SEARCH_PAUSED;
1510   sc->client_info = GNUNET_FS_search_make_status_ (&pi, sc->h, sc);
1511 }
1512
1513
1514 /**
1515  * Continue paused search.
1516  *
1517  * @param sc context for the search that should be resumed
1518  */
1519 void
1520 GNUNET_FS_search_continue (struct GNUNET_FS_SearchContext *sc)
1521 {
1522   struct GNUNET_FS_ProgressInfo pi;
1523
1524   GNUNET_assert (NULL == sc->client);
1525   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == sc->task);
1526   do_reconnect (sc, NULL);
1527   GNUNET_FS_search_sync_ (sc);
1528   pi.status = GNUNET_FS_STATUS_SEARCH_CONTINUED;
1529   sc->client_info = GNUNET_FS_search_make_status_ (&pi, sc->h, sc);
1530   GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1531                                          &search_result_resume_probes, sc);
1532 }
1533
1534
1535 /**
1536  * Signal stop for the given search result.
1537  *
1538  * @param cls the global FS handle
1539  * @param key the key for the search result (unused)
1540  * @param value the search result to free
1541  * @return #GNUNET_OK
1542  */
1543 static int
1544 search_result_stop (void *cls,
1545                     const struct GNUNET_HashCode *key,
1546                     void *value)
1547 {
1548   struct GNUNET_FS_SearchContext *sc = cls;
1549   struct GNUNET_FS_SearchResult *sr = value;
1550   struct GNUNET_FS_ProgressInfo pi;
1551
1552   GNUNET_FS_search_stop_probe_ (sr);
1553   if (NULL != sr->download)
1554   {
1555     sr->download->search = NULL;
1556     sr->download->top =
1557         GNUNET_FS_make_top (sr->download->h,
1558                             &GNUNET_FS_download_signal_suspend_, sr->download);
1559     if (NULL != sr->download->serialization)
1560     {
1561       GNUNET_FS_remove_sync_file_ (sc->h, GNUNET_FS_SYNC_PATH_CHILD_DOWNLOAD,
1562                                    sr->download->serialization);
1563       GNUNET_free (sr->download->serialization);
1564       sr->download->serialization = NULL;
1565     }
1566     pi.status = GNUNET_FS_STATUS_DOWNLOAD_LOST_PARENT;
1567     GNUNET_FS_download_make_status_ (&pi, sr->download);
1568     GNUNET_FS_download_sync_ (sr->download);
1569     sr->download = NULL;
1570   }
1571   pi.status = GNUNET_FS_STATUS_SEARCH_RESULT_STOPPED;
1572   pi.value.search.specifics.result_stopped.cctx = sr->client_info;
1573   pi.value.search.specifics.result_stopped.meta = sr->meta;
1574   pi.value.search.specifics.result_stopped.uri = sr->uri;
1575   sr->client_info = GNUNET_FS_search_make_status_ (&pi, sr->h, sc);
1576   return GNUNET_OK;
1577 }
1578
1579
1580 /**
1581  * Free the given search result.
1582  *
1583  * @param cls the global FS handle
1584  * @param key the key for the search result (unused)
1585  * @param value the search result to free
1586  * @return #GNUNET_OK
1587  */
1588 static int
1589 search_result_free (void *cls,
1590                     const struct GNUNET_HashCode *key,
1591                     void *value)
1592 {
1593   struct GNUNET_FS_SearchResult *sr = value;
1594
1595   if (NULL != sr->update_search)
1596   {
1597     GNUNET_FS_search_stop (sr->update_search);
1598     GNUNET_assert (NULL == sr->update_search);
1599   }
1600   GNUNET_break (NULL == sr->probe_ctx);
1601   GNUNET_break (GNUNET_SCHEDULER_NO_TASK == sr->probe_cancel_task);
1602   GNUNET_break (GNUNET_SCHEDULER_NO_TASK == sr->probe_ping_task);
1603   GNUNET_break (NULL == sr->client_info);
1604   GNUNET_free_non_null (sr->serialization);
1605   GNUNET_FS_uri_destroy (sr->uri);
1606   GNUNET_CONTAINER_meta_data_destroy (sr->meta);
1607   GNUNET_free_non_null (sr->keyword_bitmap);
1608   GNUNET_free (sr);
1609   return GNUNET_OK;
1610 }
1611
1612
1613 /**
1614  * Stop search for content.
1615  *
1616  * @param sc context for the search that should be stopped
1617  */
1618 void
1619 GNUNET_FS_search_stop (struct GNUNET_FS_SearchContext *sc)
1620 {
1621   struct GNUNET_FS_ProgressInfo pi;
1622   unsigned int i;
1623
1624   if (NULL != sc->top)
1625     GNUNET_FS_end_top (sc->h, sc->top);
1626   GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1627                                          &search_result_stop, sc);
1628   if (NULL != sc->psearch_result)
1629     sc->psearch_result->update_search = NULL;
1630   if (NULL != sc->serialization)
1631   {
1632     GNUNET_FS_remove_sync_file_ (sc->h,
1633                                  (sc->psearch_result !=
1634                                   NULL) ? GNUNET_FS_SYNC_PATH_CHILD_SEARCH :
1635                                  GNUNET_FS_SYNC_PATH_MASTER_SEARCH,
1636                                  sc->serialization);
1637     GNUNET_FS_remove_sync_dir_ (sc->h,
1638                                 (sc->psearch_result !=
1639                                  NULL) ? GNUNET_FS_SYNC_PATH_CHILD_SEARCH :
1640                                 GNUNET_FS_SYNC_PATH_MASTER_SEARCH,
1641                                 sc->serialization);
1642     GNUNET_free (sc->serialization);
1643   }
1644   pi.status = GNUNET_FS_STATUS_SEARCH_STOPPED;
1645   sc->client_info = GNUNET_FS_search_make_status_ (&pi, sc->h, sc);
1646   GNUNET_break (NULL == sc->client_info);
1647   if (GNUNET_SCHEDULER_NO_TASK != sc->task)
1648     GNUNET_SCHEDULER_cancel (sc->task);
1649   if (NULL != sc->client)
1650     GNUNET_CLIENT_disconnect (sc->client);
1651   GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1652                                          &search_result_free, sc);
1653   GNUNET_CONTAINER_multihashmap_destroy (sc->master_result_map);
1654   if (NULL != sc->requests)
1655   {
1656     GNUNET_assert (GNUNET_FS_uri_test_ksk (sc->uri));
1657     for (i = 0; i < sc->uri->data.ksk.keywordCount; i++)
1658       GNUNET_CONTAINER_multihashmap_destroy (sc->requests[i].results);
1659   }
1660   GNUNET_free_non_null (sc->requests);
1661   GNUNET_free_non_null (sc->emsg);
1662   GNUNET_FS_uri_destroy (sc->uri);
1663   GNUNET_free (sc);
1664 }
1665
1666 /* end of fs_search.c */