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