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