indentation
[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_NO
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 *search_start (struct GNUNET_FS_Handle *h,
444                                                      const struct GNUNET_FS_Uri
445                                                      *uri, uint32_t anonymity,
446                                                      enum
447                                                      GNUNET_FS_SearchOptions
448                                                      options, void *cctx,
449                                                      struct
450                                                      GNUNET_FS_SearchResult
451                                                      *psearch);
452
453
454 /**
455  * We have received an SKS result.  Start searching for updates and
456  * notify the client if it is a new result.
457  *
458  * @param sc context for the overall query
459  * @param id_update identifier for updates, NULL for none
460  * @param uri the URI that was found
461  * @param meta metadata associated with the URI
462   */
463 static void
464 process_sks_result (struct GNUNET_FS_SearchContext *sc, const char *id_update,
465                     const struct GNUNET_FS_Uri *uri,
466                     const struct GNUNET_CONTAINER_MetaData *meta)
467 {
468   struct GNUNET_FS_Uri uu;
469   GNUNET_HashCode key;
470   struct GNUNET_FS_SearchResult *sr;
471
472   /* check if new */
473   GNUNET_FS_uri_to_key (uri, &key);
474   GNUNET_CRYPTO_hash_xor (&uri->data.chk.chk.key, &uri->data.chk.chk.query,
475                           &key);
476   if (GNUNET_SYSERR ==
477       GNUNET_CONTAINER_multihashmap_get_multiple (sc->master_result_map, &key,
478                                                   &test_result_present,
479                                                   (void *) uri))
480     return;                     /* duplicate result */
481   sr = GNUNET_malloc (sizeof (struct GNUNET_FS_SearchResult));
482   sr->sc = sc;
483   sr->uri = GNUNET_FS_uri_dup (uri);
484   sr->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
485   sr->key = key;
486   GNUNET_CONTAINER_multihashmap_put (sc->master_result_map, &key, sr,
487                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
488   GNUNET_FS_search_result_sync_ (sr);
489   GNUNET_FS_search_start_probe_ (sr);
490   /* notify client */
491   notify_client_chk_result (sc, sr);
492   /* search for updates */
493   if (strlen (id_update) == 0)
494     return;                     /* no updates */
495   uu.type = sks;
496   uu.data.sks.namespace = sc->uri->data.sks.namespace;
497   uu.data.sks.identifier = GNUNET_strdup (id_update);
498   (void) search_start (sc->h, &uu, sc->anonymity, sc->options, NULL, sr);
499   GNUNET_free (uu.data.sks.identifier);
500 }
501
502
503 /**
504  * Process a keyword-search result.
505  *
506  * @param sc our search context
507  * @param kb the kblock
508  * @param size size of kb
509  */
510 static void
511 process_kblock (struct GNUNET_FS_SearchContext *sc, const struct KBlock *kb,
512                 size_t size)
513 {
514   unsigned int i;
515   size_t j;
516   GNUNET_HashCode q;
517   char pt[size - sizeof (struct KBlock)];
518   struct GNUNET_CRYPTO_AesSessionKey skey;
519   struct GNUNET_CRYPTO_AesInitializationVector iv;
520   const char *eos;
521   struct GNUNET_CONTAINER_MetaData *meta;
522   struct GNUNET_FS_Uri *uri;
523   char *emsg;
524
525   GNUNET_CRYPTO_hash (&kb->keyspace,
526                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
527                       &q);
528   /* find key */
529   for (i = 0; i < sc->uri->data.ksk.keywordCount; i++)
530     if (0 == memcmp (&q, &sc->requests[i].query, sizeof (GNUNET_HashCode)))
531       break;
532   if (i == sc->uri->data.ksk.keywordCount)
533   {
534     /* oops, does not match any of our keywords!? */
535     GNUNET_break (0);
536     return;
537   }
538   /* decrypt */
539   GNUNET_CRYPTO_hash_to_aes_key (&sc->requests[i].key, &skey, &iv);
540   if (-1 ==
541       GNUNET_CRYPTO_aes_decrypt (&kb[1], size - sizeof (struct KBlock), &skey,
542                                  &iv, pt))
543   {
544     GNUNET_break (0);
545     return;
546   }
547   /* parse */
548   eos = memchr (pt, 0, sizeof (pt));
549   if (NULL == eos)
550   {
551     GNUNET_break_op (0);
552     return;
553   }
554   j = eos - pt + 1;
555   if (sizeof (pt) == j)
556     meta = GNUNET_CONTAINER_meta_data_create ();
557   else
558     meta = GNUNET_CONTAINER_meta_data_deserialize (&pt[j], sizeof (pt) - j);
559   if (meta == NULL)
560   {
561     GNUNET_break_op (0);        /* kblock malformed */
562     return;
563   }
564   uri = GNUNET_FS_uri_parse (pt, &emsg);
565   if (uri == NULL)
566   {
567     GNUNET_break_op (0);        /* kblock malformed */
568     GNUNET_free_non_null (emsg);
569     GNUNET_CONTAINER_meta_data_destroy (meta);
570     return;
571   }
572   /* process */
573   process_ksk_result (sc, &sc->requests[i], uri, meta);
574
575   /* clean up */
576   GNUNET_CONTAINER_meta_data_destroy (meta);
577   GNUNET_FS_uri_destroy (uri);
578 }
579
580
581 /**
582  * Process a keyword-search result with a namespace advertisment.
583  *
584  * @param sc our search context
585  * @param nb the nblock
586  * @param size size of nb
587  */
588 static void
589 process_nblock (struct GNUNET_FS_SearchContext *sc, const struct NBlock *nb,
590                 size_t size)
591 {
592   unsigned int i;
593   size_t j;
594   GNUNET_HashCode q;
595   char pt[size - sizeof (struct NBlock)];
596   struct GNUNET_CRYPTO_AesSessionKey skey;
597   struct GNUNET_CRYPTO_AesInitializationVector iv;
598   const char *eos;
599   struct GNUNET_CONTAINER_MetaData *meta;
600   struct GNUNET_FS_Uri *uri;
601   char *uris;
602
603   GNUNET_CRYPTO_hash (&nb->keyspace,
604                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
605                       &q);
606   /* find key */
607   for (i = 0; i < sc->uri->data.ksk.keywordCount; i++)
608     if (0 == memcmp (&q, &sc->requests[i].query, sizeof (GNUNET_HashCode)))
609       break;
610   if (i == sc->uri->data.ksk.keywordCount)
611   {
612     /* oops, does not match any of our keywords!? */
613     GNUNET_break (0);
614     return;
615   }
616   /* decrypt */
617   GNUNET_CRYPTO_hash_to_aes_key (&sc->requests[i].key, &skey, &iv);
618   if (-1 ==
619       GNUNET_CRYPTO_aes_decrypt (&nb[1], size - sizeof (struct NBlock), &skey,
620                                  &iv, pt))
621   {
622     GNUNET_break (0);
623     return;
624   }
625   /* parse */
626   eos = memchr (pt, 0, sizeof (pt));
627   if (NULL == eos)
628   {
629     GNUNET_break_op (0);
630     return;
631   }
632   j = eos - pt + 1;
633   if (sizeof (pt) == j)
634     meta = GNUNET_CONTAINER_meta_data_create ();
635   else
636     meta = GNUNET_CONTAINER_meta_data_deserialize (&pt[j], sizeof (pt) - j);
637   if (meta == NULL)
638   {
639     GNUNET_break_op (0);        /* nblock malformed */
640     return;
641   }
642
643   uri = GNUNET_malloc (sizeof (struct GNUNET_FS_Uri));
644   uri->type = sks;
645   uri->data.sks.identifier = GNUNET_strdup (pt);
646   GNUNET_CRYPTO_hash (&nb->subspace,
647                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
648                       &uri->data.sks.namespace);
649   uris = GNUNET_FS_uri_to_string (uri);
650   GNUNET_CONTAINER_meta_data_insert (meta, "<gnunet>", EXTRACTOR_METATYPE_URI,
651                                      EXTRACTOR_METAFORMAT_UTF8, "text/plain",
652                                      uris, strlen (uris) + 1);
653   GNUNET_free (uris);
654   GNUNET_PSEUDONYM_add (sc->h->cfg, &uri->data.sks.namespace, meta);
655   /* process */
656   process_ksk_result (sc, &sc->requests[i], uri, meta);
657
658   /* clean up */
659   GNUNET_CONTAINER_meta_data_destroy (meta);
660   GNUNET_FS_uri_destroy (uri);
661 }
662
663
664 /**
665  * Process a namespace-search result.
666  *
667  * @param sc our search context
668  * @param sb the sblock
669  * @param size size of sb
670  */
671 static void
672 process_sblock (struct GNUNET_FS_SearchContext *sc, const struct SBlock *sb,
673                 size_t size)
674 {
675   size_t len = size - sizeof (struct SBlock);
676   char pt[len];
677   struct GNUNET_CRYPTO_AesSessionKey skey;
678   struct GNUNET_CRYPTO_AesInitializationVector iv;
679   struct GNUNET_FS_Uri *uri;
680   struct GNUNET_CONTAINER_MetaData *meta;
681   const char *id;
682   const char *uris;
683   size_t off;
684   char *emsg;
685   GNUNET_HashCode key;
686   char *identifier;
687
688   /* decrypt */
689   identifier = sc->uri->data.sks.identifier;
690   GNUNET_CRYPTO_hash (identifier, strlen (identifier), &key);
691   GNUNET_CRYPTO_hash_to_aes_key (&key, &skey, &iv);
692   if (-1 == GNUNET_CRYPTO_aes_decrypt (&sb[1], len, &skey, &iv, pt))
693   {
694     GNUNET_break (0);
695     return;
696   }
697   /* parse */
698   off = GNUNET_STRINGS_buffer_tokenize (pt, len, 2, &id, &uris);
699   if (off == 0)
700   {
701     GNUNET_break_op (0);        /* sblock malformed */
702     return;
703   }
704   meta = GNUNET_CONTAINER_meta_data_deserialize (&pt[off], len - off);
705   if (meta == NULL)
706   {
707     GNUNET_break_op (0);        /* sblock malformed */
708     return;
709   }
710   uri = GNUNET_FS_uri_parse (uris, &emsg);
711   if (uri == NULL)
712   {
713     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to parse URI `%s': %s\n", uris,
714                 emsg);
715     GNUNET_break_op (0);        /* sblock malformed */
716     GNUNET_free_non_null (emsg);
717     GNUNET_CONTAINER_meta_data_destroy (meta);
718     return;
719   }
720   /* process */
721   process_sks_result (sc, id, uri, meta);
722   /* clean up */
723   GNUNET_FS_uri_destroy (uri);
724   GNUNET_CONTAINER_meta_data_destroy (meta);
725 }
726
727
728 /**
729  * Process a search result.
730  *
731  * @param sc our search context
732  * @param type type of the result
733  * @param expiration when it will expire
734  * @param data the (encrypted) response
735  * @param size size of data
736  */
737 static void
738 process_result (struct GNUNET_FS_SearchContext *sc, enum GNUNET_BLOCK_Type type,
739                 struct GNUNET_TIME_Absolute expiration, const void *data,
740                 size_t size)
741 {
742   if (GNUNET_TIME_absolute_get_duration (expiration).rel_value > 0)
743   {
744     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
745                 "Result received has already expired.\n");
746     return;                     /* result expired */
747   }
748   switch (type)
749   {
750   case GNUNET_BLOCK_TYPE_FS_KBLOCK:
751     if (!GNUNET_FS_uri_test_ksk (sc->uri))
752     {
753       GNUNET_break (0);
754       return;
755     }
756     if (sizeof (struct KBlock) > size)
757     {
758       GNUNET_break_op (0);
759       return;
760     }
761     process_kblock (sc, data, size);
762     break;
763   case GNUNET_BLOCK_TYPE_FS_SBLOCK:
764     if (!GNUNET_FS_uri_test_sks (sc->uri))
765     {
766       GNUNET_break (0);
767       return;
768     }
769     if (sizeof (struct SBlock) > size)
770     {
771       GNUNET_break_op (0);
772       return;
773     }
774     process_sblock (sc, data, size);
775     break;
776   case GNUNET_BLOCK_TYPE_FS_NBLOCK:
777     if (!GNUNET_FS_uri_test_ksk (sc->uri))
778     {
779       GNUNET_break (0);
780       return;
781     }
782     if (sizeof (struct NBlock) > size)
783     {
784       GNUNET_break_op (0);
785       return;
786     }
787     process_nblock (sc, data, size);
788     break;
789   case GNUNET_BLOCK_TYPE_ANY:
790     GNUNET_break (0);
791     break;
792   case GNUNET_BLOCK_TYPE_FS_DBLOCK:
793     GNUNET_break (0);
794     break;
795   case GNUNET_BLOCK_TYPE_FS_ONDEMAND:
796     GNUNET_break (0);
797     break;
798   case GNUNET_BLOCK_TYPE_FS_IBLOCK:
799     GNUNET_break (0);
800     break;
801   default:
802     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
803                 _("Got result with unknown block type `%d', ignoring"), type);
804     break;
805   }
806 }
807
808
809 /**
810  * Shutdown any existing connection to the FS
811  * service and try to establish a fresh one
812  * (and then re-transmit our search request).
813  *
814  * @param sc the search to reconnec
815  */
816 static void try_reconnect (struct GNUNET_FS_SearchContext *sc);
817
818
819 /**
820  * Type of a function to call when we receive a message
821  * from the service.
822  *
823  * @param cls closure
824  * @param msg message received, NULL on timeout or fatal error
825  */
826 static void
827 receive_results (void *cls, const struct GNUNET_MessageHeader *msg)
828 {
829   struct GNUNET_FS_SearchContext *sc = cls;
830   const struct PutMessage *cm;
831   uint16_t msize;
832
833   if ((NULL == msg) || (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_FS_PUT) ||
834       (ntohs (msg->size) <= sizeof (struct PutMessage)))
835   {
836     try_reconnect (sc);
837     return;
838   }
839   msize = ntohs (msg->size);
840   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
841               "Receiving %u bytes of result from fs service\n", msize);
842   cm = (const struct PutMessage *) msg;
843   process_result (sc, ntohl (cm->type),
844                   GNUNET_TIME_absolute_ntoh (cm->expiration), &cm[1],
845                   msize - sizeof (struct PutMessage));
846   /* continue receiving */
847   GNUNET_CLIENT_receive (sc->client, &receive_results, sc,
848                          GNUNET_TIME_UNIT_FOREVER_REL);
849 }
850
851
852 /**
853  * Schedule the transmission of the (next) search request
854  * to the service.
855  *
856  * @param sc context for the search
857  */
858 static void schedule_transmit_search_request (struct GNUNET_FS_SearchContext
859                                               *sc);
860
861
862 /**
863  * Closure for 'build_result_set'.
864  */
865 struct MessageBuilderContext
866 {
867   /**
868    * How many entries can we store to xoff.
869    */
870   unsigned int put_cnt;
871
872   /**
873    * How many entries should we skip.
874    */
875   unsigned int skip_cnt;
876
877   /**
878    * Where to store the keys.
879    */
880   GNUNET_HashCode *xoff;
881
882   /**
883    * Search context we are iterating for.
884    */
885   struct GNUNET_FS_SearchContext *sc;
886
887   /**
888    * URI the search result must match, NULL for any
889    */
890   struct GNUNET_FS_Uri *uri;
891 };
892
893
894 /**
895  * Iterating over the known results, pick those
896  * matching the given result range and store
897  * their keys at 'xoff'.
898  *
899  * @param cls the 'struct MessageBuilderContext'
900  * @param key key for a result
901  * @param value the search result
902  * @return GNUNET_OK to continue iterating
903  */
904 static int
905 build_result_set (void *cls, const GNUNET_HashCode * key, void *value)
906 {
907   struct MessageBuilderContext *mbc = cls;
908   struct GNUNET_FS_SearchResult *sr = value;
909
910   if ((mbc->uri != NULL) &&
911       (GNUNET_YES != GNUNET_FS_uri_test_equal (mbc->uri, sr->uri)))
912     return GNUNET_OK;
913   if (mbc->skip_cnt > 0)
914   {
915     mbc->skip_cnt--;
916     return GNUNET_OK;
917   }
918   if (mbc->put_cnt == 0)
919     return GNUNET_SYSERR;
920   mbc->sc->search_request_map_offset++;
921   mbc->xoff[--mbc->put_cnt] = *key;
922   return GNUNET_OK;
923 }
924
925
926 /**
927  * Iterating over the known results, count those
928  * matching the given result range and increment
929  * put count for each.
930  *
931  * @param cls the 'struct MessageBuilderContext'
932  * @param key key for a result
933  * @param value the search result
934  * @return GNUNET_OK to continue iterating
935  */
936 static int
937 find_result_set (void *cls, const GNUNET_HashCode * key, void *value)
938 {
939   struct MessageBuilderContext *mbc = cls;
940   struct GNUNET_FS_SearchResult *sr = value;
941
942   if ((mbc->uri != NULL) &&
943       (GNUNET_YES != GNUNET_FS_uri_test_equal (mbc->uri, sr->uri)))
944     return GNUNET_OK;
945   mbc->put_cnt++;
946   return GNUNET_OK;
947 }
948
949
950 /**
951  * We're ready to transmit the search request to the
952  * file-sharing service.  Do it.
953  *
954  * @param cls closure
955  * @param size number of bytes available in buf
956  * @param buf where the callee should write the message
957  * @return number of bytes written to buf
958  */
959 static size_t
960 transmit_search_request (void *cls, size_t size, void *buf)
961 {
962   struct GNUNET_FS_SearchContext *sc = cls;
963   struct MessageBuilderContext mbc;
964   size_t msize;
965   struct SearchMessage *sm;
966   const char *identifier;
967   GNUNET_HashCode key;
968   GNUNET_HashCode idh;
969   unsigned int sqms;
970
971   if (NULL == buf)
972   {
973     try_reconnect (sc);
974     return 0;
975   }
976   mbc.sc = sc;
977   mbc.skip_cnt = sc->search_request_map_offset;
978   sm = buf;
979   sm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_START_SEARCH);
980   mbc.xoff = (GNUNET_HashCode *) & sm[1];
981   if (GNUNET_FS_uri_test_ksk (sc->uri))
982   {
983     msize = sizeof (struct SearchMessage);
984     GNUNET_assert (size >= msize);
985     mbc.uri = NULL;
986     mbc.put_cnt = 0;
987     GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
988                                            &find_result_set, &mbc);
989     sqms = mbc.put_cnt;
990     mbc.put_cnt = (size - msize) / sizeof (GNUNET_HashCode);
991     mbc.put_cnt = GNUNET_MIN (mbc.put_cnt, sqms - mbc.skip_cnt);
992     if (sc->search_request_map_offset < sqms)
993       GNUNET_assert (mbc.put_cnt > 0);
994
995     sm->header.size = htons (msize);
996     if (0 != (sc->options & GNUNET_FS_SEARCH_OPTION_LOOPBACK_ONLY))
997       sm->options = htonl (1);
998     else
999       sm->options = htonl (0);
1000     sm->type = htonl (GNUNET_BLOCK_TYPE_ANY);
1001     sm->anonymity_level = htonl (sc->anonymity);
1002     memset (&sm->target, 0, sizeof (GNUNET_HashCode));
1003     sm->query = sc->requests[sc->keyword_offset].query;
1004     msize += sizeof (GNUNET_HashCode) * mbc.put_cnt;
1005     GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1006                                            &build_result_set, &mbc);
1007     sm->header.size = htons (msize);
1008     if (sqms != sc->search_request_map_offset)
1009     {
1010       /* more requesting to be done... */
1011       schedule_transmit_search_request (sc);
1012       return msize;
1013     }
1014     sc->keyword_offset++;
1015     if (sc->uri->data.ksk.keywordCount != sc->keyword_offset)
1016     {
1017       /* more requesting to be done... */
1018       schedule_transmit_search_request (sc);
1019       return msize;
1020     }
1021   }
1022   else
1023   {
1024     GNUNET_assert (GNUNET_FS_uri_test_sks (sc->uri));
1025     msize = sizeof (struct SearchMessage);
1026     GNUNET_assert (size >= msize);
1027     if (0 != (sc->options & GNUNET_FS_SEARCH_OPTION_LOOPBACK_ONLY))
1028       sm->options = htonl (1);
1029     else
1030       sm->options = htonl (0);
1031     sm->type = htonl (GNUNET_BLOCK_TYPE_FS_SBLOCK);
1032     sm->anonymity_level = htonl (sc->anonymity);
1033     sm->target = sc->uri->data.sks.namespace;
1034     identifier = sc->uri->data.sks.identifier;
1035     GNUNET_CRYPTO_hash (identifier, strlen (identifier), &key);
1036     GNUNET_CRYPTO_hash (&key, sizeof (GNUNET_HashCode), &idh);
1037     GNUNET_CRYPTO_hash_xor (&idh, &sm->target, &sm->query);
1038     mbc.put_cnt = (size - msize) / sizeof (GNUNET_HashCode);
1039     sqms = GNUNET_CONTAINER_multihashmap_size (sc->master_result_map);
1040     mbc.put_cnt = GNUNET_MIN (mbc.put_cnt, sqms - mbc.skip_cnt);
1041     mbc.uri = NULL;
1042     if (sc->search_request_map_offset < sqms)
1043       GNUNET_assert (mbc.put_cnt > 0);
1044     msize += sizeof (GNUNET_HashCode) * mbc.put_cnt;
1045     GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1046                                            &build_result_set, &mbc);
1047     sm->header.size = htons (msize);
1048     if (sqms != sc->search_request_map_offset)
1049     {
1050       /* more requesting to be done... */
1051       schedule_transmit_search_request (sc);
1052       return msize;
1053     }
1054   }
1055   GNUNET_CLIENT_receive (sc->client, &receive_results, sc,
1056                          GNUNET_TIME_UNIT_FOREVER_REL);
1057   return msize;
1058 }
1059
1060
1061 /**
1062  * Schedule the transmission of the (next) search request
1063  * to the service.
1064  *
1065  * @param sc context for the search
1066  */
1067 static void
1068 schedule_transmit_search_request (struct GNUNET_FS_SearchContext *sc)
1069 {
1070   size_t size;
1071   unsigned int sqms;
1072   unsigned int fit;
1073
1074   size = sizeof (struct SearchMessage);
1075   sqms =
1076       GNUNET_CONTAINER_multihashmap_size (sc->master_result_map) -
1077       sc->search_request_map_offset;
1078   fit = (GNUNET_SERVER_MAX_MESSAGE_SIZE - 1 - size) / sizeof (GNUNET_HashCode);
1079   fit = GNUNET_MIN (fit, sqms);
1080   size += sizeof (GNUNET_HashCode) * fit;
1081   GNUNET_CLIENT_notify_transmit_ready (sc->client, size,
1082                                        GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1083                                        GNUNET_NO, &transmit_search_request, sc);
1084
1085 }
1086
1087
1088 /**
1089  * Reconnect to the FS service and transmit
1090  * our queries NOW.
1091  *
1092  * @param cls our search context
1093  * @param tc unused
1094  */
1095 static void
1096 do_reconnect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1097 {
1098   struct GNUNET_FS_SearchContext *sc = cls;
1099   struct GNUNET_CLIENT_Connection *client;
1100
1101   sc->task = GNUNET_SCHEDULER_NO_TASK;
1102   client = GNUNET_CLIENT_connect ("fs", sc->h->cfg);
1103   if (NULL == client)
1104   {
1105     try_reconnect (sc);
1106     return;
1107   }
1108   sc->client = client;
1109   sc->search_request_map_offset = 0;
1110   sc->keyword_offset = 0;
1111   schedule_transmit_search_request (sc);
1112 }
1113
1114
1115 /**
1116  * Shutdown any existing connection to the FS
1117  * service and try to establish a fresh one
1118  * (and then re-transmit our search request).
1119  *
1120  * @param sc the search to reconnec
1121  */
1122 static void
1123 try_reconnect (struct GNUNET_FS_SearchContext *sc)
1124 {
1125   if (NULL != sc->client)
1126   {
1127     GNUNET_CLIENT_disconnect (sc->client, GNUNET_NO);
1128     sc->client = NULL;
1129   }
1130   sc->task =
1131       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, &do_reconnect,
1132                                     sc);
1133 }
1134
1135
1136 /**
1137  * Start search for content, internal API.
1138  *
1139  * @param h handle to the file sharing subsystem
1140  * @param uri specifies the search parameters; can be
1141  *        a KSK URI or an SKS URI.
1142  * @param anonymity desired level of anonymity
1143  * @param options options for the search
1144  * @param cctx initial value for the client context
1145  * @param psearch parent search result (for namespace update searches)
1146  * @return context that can be used to control the search
1147  */
1148 static struct GNUNET_FS_SearchContext *
1149 search_start (struct GNUNET_FS_Handle *h, const struct GNUNET_FS_Uri *uri,
1150               uint32_t anonymity, enum GNUNET_FS_SearchOptions options,
1151               void *cctx, struct GNUNET_FS_SearchResult *psearch)
1152 {
1153   struct GNUNET_FS_SearchContext *sc;
1154   struct GNUNET_FS_ProgressInfo pi;
1155
1156   sc = GNUNET_malloc (sizeof (struct GNUNET_FS_SearchContext));
1157   sc->h = h;
1158   sc->options = options;
1159   sc->uri = GNUNET_FS_uri_dup (uri);
1160   sc->anonymity = anonymity;
1161   sc->start_time = GNUNET_TIME_absolute_get ();
1162   if (psearch != NULL)
1163   {
1164     sc->psearch_result = psearch;
1165     psearch->update_search = sc;
1166   }
1167   sc->master_result_map = GNUNET_CONTAINER_multihashmap_create (16);
1168   sc->client_info = cctx;
1169   if (GNUNET_OK != GNUNET_FS_search_start_searching_ (sc))
1170   {
1171     GNUNET_FS_uri_destroy (sc->uri);
1172     GNUNET_CONTAINER_multihashmap_destroy (sc->master_result_map);
1173     GNUNET_free (sc);
1174     return NULL;
1175   }
1176   GNUNET_FS_search_sync_ (sc);
1177   pi.status = GNUNET_FS_STATUS_SEARCH_START;
1178   sc->client_info = GNUNET_FS_search_make_status_ (&pi, sc);
1179   return sc;
1180 }
1181
1182
1183 /**
1184  * Build the request and actually initiate the search using the
1185  * GNUnet FS service.
1186  *
1187  * @param sc search context
1188  * @return GNUNET_OK on success, GNUNET_SYSERR on error
1189  */
1190 int
1191 GNUNET_FS_search_start_searching_ (struct GNUNET_FS_SearchContext *sc)
1192 {
1193   unsigned int i;
1194   const char *keyword;
1195   GNUNET_HashCode hc;
1196   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pub;
1197   struct GNUNET_CRYPTO_RsaPrivateKey *pk;
1198
1199   GNUNET_assert (NULL == sc->client);
1200   if (GNUNET_FS_uri_test_ksk (sc->uri))
1201   {
1202     GNUNET_assert (0 != sc->uri->data.ksk.keywordCount);
1203     sc->requests =
1204         GNUNET_malloc (sizeof (struct SearchRequestEntry) *
1205                        sc->uri->data.ksk.keywordCount);
1206     for (i = 0; i < sc->uri->data.ksk.keywordCount; i++)
1207     {
1208       keyword = &sc->uri->data.ksk.keywords[i][1];
1209       GNUNET_CRYPTO_hash (keyword, strlen (keyword), &hc);
1210       pk = GNUNET_CRYPTO_rsa_key_create_from_hash (&hc);
1211       GNUNET_assert (pk != NULL);
1212       GNUNET_CRYPTO_rsa_key_get_public (pk, &pub);
1213       GNUNET_CRYPTO_rsa_key_free (pk);
1214       GNUNET_CRYPTO_hash (&pub,
1215                           sizeof (struct
1216                                   GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1217                           &sc->requests[i].query);
1218       sc->requests[i].mandatory = (sc->uri->data.ksk.keywords[i][0] == '+');
1219       if (sc->requests[i].mandatory)
1220         sc->mandatory_count++;
1221       sc->requests[i].results = GNUNET_CONTAINER_multihashmap_create (4);
1222       GNUNET_CRYPTO_hash (keyword, strlen (keyword), &sc->requests[i].key);
1223     }
1224   }
1225   sc->client = GNUNET_CLIENT_connect ("fs", sc->h->cfg);
1226   if (NULL == sc->client)
1227     return GNUNET_SYSERR;
1228   schedule_transmit_search_request (sc);
1229   return GNUNET_OK;
1230 }
1231
1232
1233 /**
1234  * Freeze probes for the given search result.
1235  *
1236  * @param cls the global FS handle
1237  * @param key the key for the search result (unused)
1238  * @param value the search result to free
1239  * @return GNUNET_OK
1240  */
1241 static int
1242 search_result_freeze_probes (void *cls, const GNUNET_HashCode * key,
1243                              void *value)
1244 {
1245   struct GNUNET_FS_SearchResult *sr = value;
1246
1247   if (sr->probe_ctx != NULL)
1248   {
1249     GNUNET_FS_download_stop (sr->probe_ctx, GNUNET_YES);
1250     sr->probe_ctx = NULL;
1251   }
1252   if (sr->probe_cancel_task != GNUNET_SCHEDULER_NO_TASK)
1253   {
1254     GNUNET_SCHEDULER_cancel (sr->probe_cancel_task);
1255     sr->probe_cancel_task = GNUNET_SCHEDULER_NO_TASK;
1256   }
1257   if (sr->update_search != NULL)
1258     GNUNET_FS_search_pause (sr->update_search);
1259   return GNUNET_OK;
1260 }
1261
1262
1263 /**
1264  * Resume probes for the given search result.
1265  *
1266  * @param cls the global FS handle
1267  * @param key the key for the search result (unused)
1268  * @param value the search result to free
1269  * @return GNUNET_OK
1270  */
1271 static int
1272 search_result_resume_probes (void *cls, const GNUNET_HashCode * key,
1273                              void *value)
1274 {
1275   struct GNUNET_FS_SearchResult *sr = value;
1276
1277   GNUNET_FS_search_start_probe_ (sr);
1278   if (sr->update_search != NULL)
1279     GNUNET_FS_search_continue (sr->update_search);
1280   return GNUNET_OK;
1281 }
1282
1283
1284 /**
1285  * Signal suspend and free the given search result.
1286  *
1287  * @param cls the global FS handle
1288  * @param key the key for the search result (unused)
1289  * @param value the search result to free
1290  * @return GNUNET_OK
1291  */
1292 static int
1293 search_result_suspend (void *cls, const GNUNET_HashCode * key, void *value)
1294 {
1295   struct GNUNET_FS_SearchContext *sc = cls;
1296   struct GNUNET_FS_SearchResult *sr = value;
1297   struct GNUNET_FS_ProgressInfo pi;
1298
1299   if (sr->download != NULL)
1300     GNUNET_FS_download_signal_suspend_ (sr->download);
1301   if (sr->update_search != NULL)
1302     GNUNET_FS_search_signal_suspend_ (sr->update_search);
1303   pi.status = GNUNET_FS_STATUS_SEARCH_RESULT_SUSPEND;
1304   pi.value.search.specifics.result_suspend.cctx = sr->client_info;
1305   pi.value.search.specifics.result_suspend.meta = sr->meta;
1306   pi.value.search.specifics.result_suspend.uri = sr->uri;
1307   sr->client_info = GNUNET_FS_search_make_status_ (&pi, sc);
1308   GNUNET_break (NULL == sr->client_info);
1309   GNUNET_free_non_null (sr->serialization);
1310   GNUNET_FS_uri_destroy (sr->uri);
1311   GNUNET_CONTAINER_meta_data_destroy (sr->meta);
1312   if (sr->probe_ctx != NULL)
1313     GNUNET_FS_download_stop (sr->probe_ctx, GNUNET_YES);
1314   if (sr->probe_cancel_task != GNUNET_SCHEDULER_NO_TASK)
1315     GNUNET_SCHEDULER_cancel (sr->probe_cancel_task);
1316   GNUNET_free (sr);
1317   return GNUNET_OK;
1318 }
1319
1320
1321 /**
1322  * Create SUSPEND event for the given search operation
1323  * and then clean up our state (without stop signal).
1324  *
1325  * @param cls the 'struct GNUNET_FS_SearchContext' to signal for
1326  */
1327 void
1328 GNUNET_FS_search_signal_suspend_ (void *cls)
1329 {
1330   struct GNUNET_FS_SearchContext *sc = cls;
1331   struct GNUNET_FS_ProgressInfo pi;
1332   unsigned int i;
1333
1334   GNUNET_FS_end_top (sc->h, sc->top);
1335   GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1336                                          &search_result_suspend, sc);
1337   pi.status = GNUNET_FS_STATUS_SEARCH_SUSPEND;
1338   sc->client_info = GNUNET_FS_search_make_status_ (&pi, sc);
1339   GNUNET_break (NULL == sc->client_info);
1340   if (sc->task != GNUNET_SCHEDULER_NO_TASK)
1341     GNUNET_SCHEDULER_cancel (sc->task);
1342   if (NULL != sc->client)
1343     GNUNET_CLIENT_disconnect (sc->client, GNUNET_NO);
1344   GNUNET_CONTAINER_multihashmap_destroy (sc->master_result_map);
1345   if (sc->requests != NULL)
1346   {
1347     GNUNET_assert (GNUNET_FS_uri_test_ksk (sc->uri));
1348     for (i = 0; i < sc->uri->data.ksk.keywordCount; i++)
1349       GNUNET_CONTAINER_multihashmap_destroy (sc->requests[i].results);
1350   }
1351   GNUNET_free_non_null (sc->requests);
1352   GNUNET_free_non_null (sc->emsg);
1353   GNUNET_FS_uri_destroy (sc->uri);
1354   GNUNET_free_non_null (sc->serialization);
1355   GNUNET_free (sc);
1356 }
1357
1358
1359 /**
1360  * Start search for content.
1361  *
1362  * @param h handle to the file sharing subsystem
1363  * @param uri specifies the search parameters; can be
1364  *        a KSK URI or an SKS URI.
1365  * @param anonymity desired level of anonymity
1366  * @param options options for the search
1367  * @param cctx initial value for the client context
1368  * @return context that can be used to control the search
1369  */
1370 struct GNUNET_FS_SearchContext *
1371 GNUNET_FS_search_start (struct GNUNET_FS_Handle *h,
1372                         const struct GNUNET_FS_Uri *uri, uint32_t anonymity,
1373                         enum GNUNET_FS_SearchOptions options, void *cctx)
1374 {
1375   struct GNUNET_FS_SearchContext *ret;
1376
1377   ret = search_start (h, uri, anonymity, options, cctx, NULL);
1378   if (ret == NULL)
1379     return NULL;
1380   ret->top = GNUNET_FS_make_top (h, &GNUNET_FS_search_signal_suspend_, ret);
1381   return ret;
1382 }
1383
1384
1385 /**
1386  * Pause search.  
1387  *
1388  * @param sc context for the search that should be paused
1389  */
1390 void
1391 GNUNET_FS_search_pause (struct GNUNET_FS_SearchContext *sc)
1392 {
1393   struct GNUNET_FS_ProgressInfo pi;
1394
1395   if (sc->task != GNUNET_SCHEDULER_NO_TASK)
1396     GNUNET_SCHEDULER_cancel (sc->task);
1397   sc->task = GNUNET_SCHEDULER_NO_TASK;
1398   if (NULL != sc->client)
1399     GNUNET_CLIENT_disconnect (sc->client, GNUNET_NO);
1400   sc->client = NULL;
1401   GNUNET_FS_search_sync_ (sc);
1402   GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1403                                          &search_result_freeze_probes, sc);
1404   pi.status = GNUNET_FS_STATUS_SEARCH_PAUSED;
1405   sc->client_info = GNUNET_FS_search_make_status_ (&pi, sc);
1406 }
1407
1408
1409 /**
1410  * Continue paused search.
1411  *
1412  * @param sc context for the search that should be resumed
1413  */
1414 void
1415 GNUNET_FS_search_continue (struct GNUNET_FS_SearchContext *sc)
1416 {
1417   struct GNUNET_FS_ProgressInfo pi;
1418
1419   GNUNET_assert (sc->client == NULL);
1420   GNUNET_assert (sc->task == GNUNET_SCHEDULER_NO_TASK);
1421   do_reconnect (sc, NULL);
1422   GNUNET_FS_search_sync_ (sc);
1423   pi.status = GNUNET_FS_STATUS_SEARCH_CONTINUED;
1424   sc->client_info = GNUNET_FS_search_make_status_ (&pi, sc);
1425   GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1426                                          &search_result_resume_probes, sc);
1427 }
1428
1429
1430 /**
1431  * Free the given search result.
1432  *
1433  * @param cls the global FS handle
1434  * @param key the key for the search result (unused)
1435  * @param value the search result to free
1436  * @return GNUNET_OK
1437  */
1438 static int
1439 search_result_free (void *cls, const GNUNET_HashCode * key, void *value)
1440 {
1441   struct GNUNET_FS_SearchContext *sc = cls;
1442   struct GNUNET_FS_SearchResult *sr = value;
1443   struct GNUNET_FS_ProgressInfo pi;
1444
1445   if (NULL != sr->download)
1446   {
1447     sr->download->search = NULL;
1448     sr->download->top =
1449         GNUNET_FS_make_top (sr->download->h,
1450                             &GNUNET_FS_download_signal_suspend_, sr->download);
1451     if (NULL != sr->download->serialization)
1452     {
1453       GNUNET_FS_remove_sync_file_ (sc->h, GNUNET_FS_SYNC_PATH_CHILD_DOWNLOAD,
1454                                    sr->download->serialization);
1455       GNUNET_free (sr->download->serialization);
1456       sr->download->serialization = NULL;
1457     }
1458     pi.status = GNUNET_FS_STATUS_DOWNLOAD_LOST_PARENT;
1459     GNUNET_FS_download_make_status_ (&pi, sr->download);
1460     GNUNET_FS_download_sync_ (sr->download);
1461     sr->download = NULL;
1462   }
1463   if (NULL != sr->update_search)
1464   {
1465     GNUNET_FS_search_stop (sr->update_search);
1466     GNUNET_assert (sr->update_search == NULL);
1467   }
1468   pi.status = GNUNET_FS_STATUS_SEARCH_RESULT_STOPPED;
1469   pi.value.search.specifics.result_stopped.cctx = sr->client_info;
1470   pi.value.search.specifics.result_stopped.meta = sr->meta;
1471   pi.value.search.specifics.result_stopped.uri = sr->uri;
1472   sr->client_info = GNUNET_FS_search_make_status_ (&pi, sc);
1473   GNUNET_break (NULL == sr->client_info);
1474   GNUNET_free_non_null (sr->serialization);
1475   GNUNET_FS_uri_destroy (sr->uri);
1476   GNUNET_CONTAINER_meta_data_destroy (sr->meta);
1477   if (sr->probe_ctx != NULL)
1478     GNUNET_FS_download_stop (sr->probe_ctx, GNUNET_YES);
1479   if (sr->probe_cancel_task != GNUNET_SCHEDULER_NO_TASK)
1480     GNUNET_SCHEDULER_cancel (sr->probe_cancel_task);
1481   GNUNET_free (sr);
1482   return GNUNET_OK;
1483 }
1484
1485
1486 /**
1487  * Stop search for content.
1488  *
1489  * @param sc context for the search that should be stopped
1490  */
1491 void
1492 GNUNET_FS_search_stop (struct GNUNET_FS_SearchContext *sc)
1493 {
1494   struct GNUNET_FS_ProgressInfo pi;
1495   unsigned int i;
1496
1497   if (sc->top != NULL)
1498     GNUNET_FS_end_top (sc->h, sc->top);
1499   if (sc->psearch_result != NULL)
1500     sc->psearch_result->update_search = NULL;
1501   GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1502                                          &search_result_free, sc);
1503   if (sc->serialization != NULL)
1504   {
1505     GNUNET_FS_remove_sync_file_ (sc->h,
1506                                  (sc->psearch_result !=
1507                                   NULL) ? GNUNET_FS_SYNC_PATH_CHILD_SEARCH :
1508                                  GNUNET_FS_SYNC_PATH_MASTER_SEARCH,
1509                                  sc->serialization);
1510     GNUNET_FS_remove_sync_dir_ (sc->h,
1511                                 (sc->psearch_result !=
1512                                  NULL) ? GNUNET_FS_SYNC_PATH_CHILD_SEARCH :
1513                                 GNUNET_FS_SYNC_PATH_MASTER_SEARCH,
1514                                 sc->serialization);
1515     GNUNET_free (sc->serialization);
1516   }
1517   pi.status = GNUNET_FS_STATUS_SEARCH_STOPPED;
1518   sc->client_info = GNUNET_FS_search_make_status_ (&pi, sc);
1519   GNUNET_break (NULL == sc->client_info);
1520   if (sc->task != GNUNET_SCHEDULER_NO_TASK)
1521     GNUNET_SCHEDULER_cancel (sc->task);
1522   if (NULL != sc->client)
1523     GNUNET_CLIENT_disconnect (sc->client, GNUNET_NO);
1524   GNUNET_CONTAINER_multihashmap_destroy (sc->master_result_map);
1525   if (sc->requests != NULL)
1526   {
1527     GNUNET_assert (GNUNET_FS_uri_test_ksk (sc->uri));
1528     for (i = 0; i < sc->uri->data.ksk.keywordCount; i++)
1529       GNUNET_CONTAINER_multihashmap_destroy (sc->requests[i].results);
1530   }
1531   GNUNET_free_non_null (sc->requests);
1532   GNUNET_free_non_null (sc->emsg);
1533   GNUNET_FS_uri_destroy (sc->uri);
1534   GNUNET_free (sc);
1535 }
1536
1537 /* end of fs_search.c */