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