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