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