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