-fix #2378
[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 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 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   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   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.namespace = sc->uri->data.sks.namespace;
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   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 (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.namespace);
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.namespace, 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   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, const void *data,
766                 size_t size)
767 {
768   if (GNUNET_TIME_absolute_get_duration (expiration).rel_value > 0)
769   {
770     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
771                 "Result received has already expired.\n");
772     return;                     /* result expired */
773   }
774   switch (type)
775   {
776   case GNUNET_BLOCK_TYPE_FS_KBLOCK:
777     if (!GNUNET_FS_uri_test_ksk (sc->uri))
778     {
779       GNUNET_break (0);
780       return;
781     }
782     if (sizeof (struct KBlock) > size)
783     {
784       GNUNET_break_op (0);
785       return;
786     }
787     process_kblock (sc, data, size);
788     break;
789   case GNUNET_BLOCK_TYPE_FS_SBLOCK:
790     if (!GNUNET_FS_uri_test_sks (sc->uri))
791     {
792       GNUNET_break (0);
793       return;
794     }
795     if (sizeof (struct SBlock) > size)
796     {
797       GNUNET_break_op (0);
798       return;
799     }
800     process_sblock (sc, data, size);
801     break;
802   case GNUNET_BLOCK_TYPE_FS_NBLOCK:
803     if (!GNUNET_FS_uri_test_ksk (sc->uri))
804     {
805       GNUNET_break (0);
806       return;
807     }
808     if (sizeof (struct NBlock) > size)
809     {
810       GNUNET_break_op (0);
811       return;
812     }
813     process_nblock (sc, data, size);
814     break;
815   case GNUNET_BLOCK_TYPE_ANY:
816     GNUNET_break (0);
817     break;
818   case GNUNET_BLOCK_TYPE_FS_DBLOCK:
819     GNUNET_break (0);
820     break;
821   case GNUNET_BLOCK_TYPE_FS_ONDEMAND:
822     GNUNET_break (0);
823     break;
824   case GNUNET_BLOCK_TYPE_FS_IBLOCK:
825     GNUNET_break (0);
826     break;
827   default:
828     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
829                 _("Got result with unknown block type `%d', ignoring"), type);
830     break;
831   }
832 }
833
834
835 /**
836  * Shutdown any existing connection to the FS
837  * service and try to establish a fresh one
838  * (and then re-transmit our search request).
839  *
840  * @param sc the search to reconnec
841  */
842 static void
843 try_reconnect (struct GNUNET_FS_SearchContext *sc);
844
845
846 /**
847  * Type of a function to call when we receive a message
848  * from the service.
849  *
850  * @param cls closure
851  * @param msg message received, NULL on timeout or fatal error
852  */
853 static void
854 receive_results (void *cls, const struct GNUNET_MessageHeader *msg)
855 {
856   struct GNUNET_FS_SearchContext *sc = cls;
857   const struct ClientPutMessage *cm;
858   uint16_t msize;
859
860   if ((NULL == msg) || (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_FS_PUT) ||
861       (ntohs (msg->size) <= sizeof (struct ClientPutMessage)))
862   {
863     try_reconnect (sc);
864     return;
865   }
866   msize = ntohs (msg->size);
867   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
868               "Receiving %u bytes of result from fs service\n", msize);
869   cm = (const struct ClientPutMessage *) msg;
870   process_result (sc, ntohl (cm->type),
871                   GNUNET_TIME_absolute_ntoh (cm->expiration), &cm[1],
872                   msize - sizeof (struct ClientPutMessage));
873   /* continue receiving */
874   GNUNET_CLIENT_receive (sc->client, &receive_results, sc,
875                          GNUNET_TIME_UNIT_FOREVER_REL);
876 }
877
878
879 /**
880  * Schedule the transmission of the (next) search request
881  * to the service.
882  *
883  * @param sc context for the search
884  */
885 static void
886 schedule_transmit_search_request (struct GNUNET_FS_SearchContext *sc);
887
888
889 /**
890  * Closure for 'build_result_set'.
891  */
892 struct MessageBuilderContext
893 {
894   /**
895    * How many entries can we store to xoff.
896    */
897   unsigned int put_cnt;
898
899   /**
900    * How many entries should we skip.
901    */
902   unsigned int skip_cnt;
903
904   /**
905    * Where to store the keys.
906    */
907   GNUNET_HashCode *xoff;
908
909   /**
910    * Search context we are iterating for.
911    */
912   struct GNUNET_FS_SearchContext *sc;
913
914   /**
915    * Keyword offset the search result must match (0 for SKS)
916    */
917   unsigned int keyword_offset;
918 };
919
920
921 /**
922  * Iterating over the known results, pick those matching the given
923  * result range and store their keys at 'xoff'.
924  *
925  * @param cls the 'struct MessageBuilderContext'
926  * @param key key for a result
927  * @param value the search result
928  * @return GNUNET_OK to continue iterating
929  */
930 static int
931 build_result_set (void *cls, const GNUNET_HashCode * key, void *value)
932 {
933   struct MessageBuilderContext *mbc = cls;
934   struct GNUNET_FS_SearchResult *sr = value;
935
936   if ( (NULL != sr->keyword_bitmap) &&
937        (0 == (sr->keyword_bitmap[mbc->keyword_offset / 8] & (1 << (mbc->keyword_offset % 8)))) )
938     return GNUNET_OK; /* have no match for this keyword yet */
939   if (mbc->skip_cnt > 0)
940   {
941     mbc->skip_cnt--;
942     return GNUNET_OK;
943   }
944   if (0 == mbc->put_cnt)
945     return GNUNET_SYSERR;
946   mbc->sc->search_request_map_offset++;
947   mbc->xoff[--mbc->put_cnt] = *key;
948   return GNUNET_OK;
949 }
950
951
952 /**
953  * Iterating over the known results, count those
954  * matching the given result range and increment
955  * put count for each.
956  *
957  * @param cls the 'struct MessageBuilderContext'
958  * @param key key for a result
959  * @param value the search result
960  * @return GNUNET_OK to continue iterating
961  */
962 static int
963 find_result_set (void *cls, const GNUNET_HashCode * key, void *value)
964 {
965   struct MessageBuilderContext *mbc = cls;
966   struct GNUNET_FS_SearchResult *sr = value;
967
968   if ( (NULL != sr->keyword_bitmap) &&
969        (0 == (sr->keyword_bitmap[mbc->keyword_offset / 8] & (1 << (mbc->keyword_offset % 8)))) )
970     return GNUNET_OK; /* have no match for this keyword yet */
971   mbc->put_cnt++;
972   return GNUNET_OK;
973 }
974
975
976 /**
977  * We're ready to transmit the search request to the
978  * file-sharing service.  Do it.
979  *
980  * @param cls closure
981  * @param size number of bytes available in buf
982  * @param buf where the callee should write the message
983  * @return number of bytes written to buf
984  */
985 static size_t
986 transmit_search_request (void *cls, size_t size, void *buf)
987 {
988   struct GNUNET_FS_SearchContext *sc = cls;
989   struct MessageBuilderContext mbc;
990   size_t msize;
991   struct SearchMessage *sm;
992   const char *identifier;
993   GNUNET_HashCode key;
994   GNUNET_HashCode idh;
995   unsigned int sqms;
996   uint32_t options;
997
998   if (NULL == buf)
999   {
1000     try_reconnect (sc);
1001     return 0;
1002   }
1003   mbc.sc = sc;
1004   mbc.skip_cnt = sc->search_request_map_offset;
1005   sm = buf;
1006   sm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_START_SEARCH);
1007   mbc.xoff = (GNUNET_HashCode *) & sm[1];
1008   options = SEARCH_MESSAGE_OPTION_NONE;
1009   if (0 != (sc->options & GNUNET_FS_SEARCH_OPTION_LOOPBACK_ONLY))
1010     options |= SEARCH_MESSAGE_OPTION_LOOPBACK_ONLY;
1011   if (GNUNET_FS_uri_test_ksk (sc->uri))
1012   {
1013     msize = sizeof (struct SearchMessage);
1014     GNUNET_assert (size >= msize);
1015     mbc.keyword_offset = sc->keyword_offset;
1016     mbc.put_cnt = 0;
1017     GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1018                                            &find_result_set, &mbc);
1019     sqms = mbc.put_cnt;
1020     mbc.put_cnt = (size - msize) / sizeof (GNUNET_HashCode);
1021     mbc.put_cnt = GNUNET_MIN (mbc.put_cnt, sqms - mbc.skip_cnt);
1022     if (sc->search_request_map_offset < sqms)
1023       GNUNET_assert (mbc.put_cnt > 0);
1024
1025     sm->header.size = htons (msize);
1026     sm->type = htonl (GNUNET_BLOCK_TYPE_ANY);
1027     sm->anonymity_level = htonl (sc->anonymity);
1028     memset (&sm->target, 0, sizeof (GNUNET_HashCode));
1029     sm->query = sc->requests[sc->keyword_offset].query;
1030     msize += sizeof (GNUNET_HashCode) * mbc.put_cnt;
1031     GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1032                                            &build_result_set, &mbc);
1033     sm->header.size = htons (msize);
1034     GNUNET_assert (sqms >= sc->search_request_map_offset);
1035     if (sqms != sc->search_request_map_offset)
1036     {
1037       /* more requesting to be done... */
1038       sm->options = htonl (options | SEARCH_MESSAGE_OPTION_CONTINUED);
1039       schedule_transmit_search_request (sc);
1040       return msize;
1041     }
1042     sm->options = htonl (options);
1043     sc->keyword_offset++;
1044     if (sc->uri->data.ksk.keywordCount != sc->keyword_offset)
1045     {
1046       /* more requesting to be done... */
1047       schedule_transmit_search_request (sc);
1048       return msize;
1049     }
1050   }
1051   else
1052   {
1053     GNUNET_assert (GNUNET_FS_uri_test_sks (sc->uri));
1054     msize = sizeof (struct SearchMessage);
1055     GNUNET_assert (size >= msize);
1056     sm->type = htonl (GNUNET_BLOCK_TYPE_FS_SBLOCK);
1057     sm->anonymity_level = htonl (sc->anonymity);
1058     sm->target = sc->uri->data.sks.namespace;
1059     identifier = sc->uri->data.sks.identifier;
1060     GNUNET_CRYPTO_hash (identifier, strlen (identifier), &key);
1061     GNUNET_CRYPTO_hash (&key, sizeof (GNUNET_HashCode), &idh);
1062     GNUNET_CRYPTO_hash_xor (&idh, &sm->target, &sm->query);
1063     mbc.put_cnt = (size - msize) / sizeof (GNUNET_HashCode);
1064     sqms = GNUNET_CONTAINER_multihashmap_size (sc->master_result_map);
1065     mbc.put_cnt = GNUNET_MIN (mbc.put_cnt, sqms - mbc.skip_cnt);
1066     mbc.keyword_offset = 0;
1067     if (sc->search_request_map_offset < sqms)
1068       GNUNET_assert (mbc.put_cnt > 0);
1069     msize += sizeof (GNUNET_HashCode) * mbc.put_cnt;
1070     GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1071                                            &build_result_set, &mbc);
1072     sm->header.size = htons (msize);
1073     GNUNET_assert (sqms >= sc->search_request_map_offset);
1074     if (sqms != sc->search_request_map_offset)
1075     {
1076       /* more requesting to be done... */
1077       sm->options = htonl (options | SEARCH_MESSAGE_OPTION_CONTINUED);
1078       schedule_transmit_search_request (sc);
1079       return msize;
1080     }
1081     sm->options = htonl (options);
1082   }
1083   GNUNET_CLIENT_receive (sc->client, &receive_results, sc,
1084                          GNUNET_TIME_UNIT_FOREVER_REL);
1085   return msize;
1086 }
1087
1088
1089 /**
1090  * Schedule the transmission of the (next) search request
1091  * to the service.
1092  *
1093  * @param sc context for the search
1094  */
1095 static void
1096 schedule_transmit_search_request (struct GNUNET_FS_SearchContext *sc)
1097 {
1098   size_t size;
1099   unsigned int sqms;
1100   unsigned int fit;
1101
1102   size = sizeof (struct SearchMessage);
1103   sqms =
1104       GNUNET_CONTAINER_multihashmap_size (sc->master_result_map) -
1105       sc->search_request_map_offset;
1106   fit = (GNUNET_SERVER_MAX_MESSAGE_SIZE - 1 - size) / sizeof (GNUNET_HashCode);
1107   fit = GNUNET_MIN (fit, sqms);
1108   size += sizeof (GNUNET_HashCode) * fit;
1109   GNUNET_CLIENT_notify_transmit_ready (sc->client, size,
1110                                        GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1111                                        GNUNET_NO, &transmit_search_request, sc);
1112
1113 }
1114
1115
1116 /**
1117  * Reconnect to the FS service and transmit
1118  * our queries NOW.
1119  *
1120  * @param cls our search context
1121  * @param tc unused
1122  */
1123 static void
1124 do_reconnect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1125 {
1126   struct GNUNET_FS_SearchContext *sc = cls;
1127   struct GNUNET_CLIENT_Connection *client;
1128
1129   sc->task = GNUNET_SCHEDULER_NO_TASK;
1130   client = GNUNET_CLIENT_connect ("fs", sc->h->cfg);
1131   if (NULL == client)
1132   {
1133     try_reconnect (sc);
1134     return;
1135   }
1136   sc->client = client;
1137   sc->search_request_map_offset = 0;
1138   sc->keyword_offset = 0;
1139   schedule_transmit_search_request (sc);
1140 }
1141
1142
1143 /**
1144  * Shutdown any existing connection to the FS
1145  * service and try to establish a fresh one
1146  * (and then re-transmit our search request).
1147  *
1148  * @param sc the search to reconnec
1149  */
1150 static void
1151 try_reconnect (struct GNUNET_FS_SearchContext *sc)
1152 {
1153   if (NULL != sc->client)
1154   {
1155     GNUNET_CLIENT_disconnect (sc->client);
1156     sc->client = NULL;
1157   }
1158   sc->task =
1159       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, &do_reconnect,
1160                                     sc);
1161 }
1162
1163
1164 /**
1165  * Start search for content, internal API.
1166  *
1167  * @param h handle to the file sharing subsystem
1168  * @param uri specifies the search parameters; can be
1169  *        a KSK URI or an SKS URI.
1170  * @param anonymity desired level of anonymity
1171  * @param options options for the search
1172  * @param cctx initial value for the client context
1173  * @param psearch parent search result (for namespace update searches)
1174  * @return context that can be used to control the search
1175  */
1176 static struct GNUNET_FS_SearchContext *
1177 search_start (struct GNUNET_FS_Handle *h, const struct GNUNET_FS_Uri *uri,
1178               uint32_t anonymity, enum GNUNET_FS_SearchOptions options,
1179               void *cctx, struct GNUNET_FS_SearchResult *psearch)
1180 {
1181   struct GNUNET_FS_SearchContext *sc;
1182   struct GNUNET_FS_ProgressInfo pi;
1183
1184   sc = GNUNET_malloc (sizeof (struct GNUNET_FS_SearchContext));
1185   sc->h = h;
1186   sc->options = options;
1187   sc->uri = GNUNET_FS_uri_dup (uri);
1188   sc->anonymity = anonymity;
1189   sc->start_time = GNUNET_TIME_absolute_get ();
1190   if (NULL != psearch)
1191   {
1192     sc->psearch_result = psearch;
1193     psearch->update_search = sc;
1194   }
1195   sc->master_result_map = GNUNET_CONTAINER_multihashmap_create (16);
1196   sc->client_info = cctx;
1197   if (GNUNET_OK != GNUNET_FS_search_start_searching_ (sc))
1198   {
1199     GNUNET_FS_uri_destroy (sc->uri);
1200     GNUNET_CONTAINER_multihashmap_destroy (sc->master_result_map);
1201     GNUNET_free (sc);
1202     return NULL;
1203   }
1204   GNUNET_FS_search_sync_ (sc);
1205   pi.status = GNUNET_FS_STATUS_SEARCH_START;
1206   sc->client_info = GNUNET_FS_search_make_status_ (&pi, sc);
1207   return sc;
1208 }
1209
1210
1211 /**
1212  * Build the request and actually initiate the search using the
1213  * GNUnet FS service.
1214  *
1215  * @param sc search context
1216  * @return GNUNET_OK on success, GNUNET_SYSERR on error
1217  */
1218 int
1219 GNUNET_FS_search_start_searching_ (struct GNUNET_FS_SearchContext *sc)
1220 {
1221   unsigned int i;
1222   const char *keyword;
1223   GNUNET_HashCode hc;
1224   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pub;
1225   struct GNUNET_CRYPTO_RsaPrivateKey *pk;
1226
1227   GNUNET_assert (NULL == sc->client);
1228   if (GNUNET_FS_uri_test_ksk (sc->uri))
1229   {
1230     GNUNET_assert (0 != sc->uri->data.ksk.keywordCount);
1231     sc->requests =
1232         GNUNET_malloc (sizeof (struct SearchRequestEntry) *
1233                        sc->uri->data.ksk.keywordCount);
1234     for (i = 0; i < sc->uri->data.ksk.keywordCount; i++)
1235     {
1236       keyword = &sc->uri->data.ksk.keywords[i][1];
1237       GNUNET_CRYPTO_hash (keyword, strlen (keyword), &hc);
1238       pk = GNUNET_CRYPTO_rsa_key_create_from_hash (&hc);
1239       GNUNET_assert (NULL != pk);
1240       GNUNET_CRYPTO_rsa_key_get_public (pk, &pub);
1241       GNUNET_CRYPTO_rsa_key_free (pk);
1242       GNUNET_CRYPTO_hash (&pub,
1243                           sizeof (struct
1244                                   GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1245                           &sc->requests[i].query);
1246       sc->requests[i].mandatory = (sc->uri->data.ksk.keywords[i][0] == '+');
1247       if (sc->requests[i].mandatory)
1248         sc->mandatory_count++;
1249       sc->requests[i].results = GNUNET_CONTAINER_multihashmap_create (4);
1250       GNUNET_CRYPTO_hash (keyword, strlen (keyword), &sc->requests[i].key);
1251     }
1252   }
1253   sc->client = GNUNET_CLIENT_connect ("fs", sc->h->cfg);
1254   if (NULL == sc->client)
1255     return GNUNET_SYSERR;
1256   schedule_transmit_search_request (sc);
1257   return GNUNET_OK;
1258 }
1259
1260
1261 /**
1262  * Freeze probes for the given search result.
1263  *
1264  * @param cls the global FS handle
1265  * @param key the key for the search result (unused)
1266  * @param value the search result to free
1267  * @return GNUNET_OK
1268  */
1269 static int
1270 search_result_freeze_probes (void *cls, const GNUNET_HashCode * key,
1271                              void *value)
1272 {
1273   struct GNUNET_FS_SearchResult *sr = value;
1274
1275   if (NULL != sr->probe_ctx)
1276   {
1277     GNUNET_FS_download_stop (sr->probe_ctx, GNUNET_YES);
1278     sr->probe_ctx = NULL;
1279   }
1280   if (GNUNET_SCHEDULER_NO_TASK != sr->probe_cancel_task)
1281   {
1282     GNUNET_SCHEDULER_cancel (sr->probe_cancel_task);
1283     sr->probe_cancel_task = GNUNET_SCHEDULER_NO_TASK;
1284   }
1285   if (NULL != sr->update_search)
1286     GNUNET_FS_search_pause (sr->update_search);
1287   return GNUNET_OK;
1288 }
1289
1290
1291 /**
1292  * Resume probes for the given search result.
1293  *
1294  * @param cls the global FS handle
1295  * @param key the key for the search result (unused)
1296  * @param value the search result to free
1297  * @return GNUNET_OK
1298  */
1299 static int
1300 search_result_resume_probes (void *cls, const GNUNET_HashCode * key,
1301                              void *value)
1302 {
1303   struct GNUNET_FS_SearchResult *sr = value;
1304
1305   GNUNET_FS_search_start_probe_ (sr);
1306   if (NULL != sr->update_search)
1307     GNUNET_FS_search_continue (sr->update_search);
1308   return GNUNET_OK;
1309 }
1310
1311
1312 /**
1313  * Signal suspend and free the given search result.
1314  *
1315  * @param cls the global FS handle
1316  * @param key the key for the search result (unused)
1317  * @param value the search result to free
1318  * @return GNUNET_OK
1319  */
1320 static int
1321 search_result_suspend (void *cls, const GNUNET_HashCode * key, void *value)
1322 {
1323   struct GNUNET_FS_SearchContext *sc = cls;
1324   struct GNUNET_FS_SearchResult *sr = value;
1325   struct GNUNET_FS_ProgressInfo pi;
1326
1327   if (NULL != sr->download)
1328   {
1329     GNUNET_FS_download_signal_suspend_ (sr->download);
1330     sr->download = NULL;
1331   }
1332   if (NULL != sr->probe_ctx)
1333   {
1334     GNUNET_FS_download_stop (sr->probe_ctx, GNUNET_YES);
1335     sr->probe_ctx = NULL;
1336   }
1337   if (NULL != sr->update_search)
1338   {
1339     GNUNET_FS_search_signal_suspend_ (sr->update_search);
1340     sr->update_search = NULL;
1341   }
1342   pi.status = GNUNET_FS_STATUS_SEARCH_RESULT_SUSPEND;
1343   pi.value.search.specifics.result_suspend.cctx = sr->client_info;
1344   pi.value.search.specifics.result_suspend.meta = sr->meta;
1345   pi.value.search.specifics.result_suspend.uri = sr->uri;
1346   sr->client_info = GNUNET_FS_search_make_status_ (&pi, sc);
1347   GNUNET_break (NULL == sr->client_info);
1348   GNUNET_free_non_null (sr->serialization);
1349   GNUNET_FS_uri_destroy (sr->uri);
1350   GNUNET_CONTAINER_meta_data_destroy (sr->meta);
1351   if (GNUNET_SCHEDULER_NO_TASK != sr->probe_cancel_task)
1352   {
1353     GNUNET_SCHEDULER_cancel (sr->probe_cancel_task);
1354     sr->probe_cancel_task = GNUNET_SCHEDULER_NO_TASK;
1355   }
1356   GNUNET_free_non_null (sr->keyword_bitmap);
1357   GNUNET_free (sr);
1358   return GNUNET_OK;
1359 }
1360
1361
1362 /**
1363  * Create SUSPEND event for the given search operation
1364  * and then clean up our state (without stop signal).
1365  *
1366  * @param cls the 'struct GNUNET_FS_SearchContext' to signal for
1367  */
1368 void
1369 GNUNET_FS_search_signal_suspend_ (void *cls)
1370 {
1371   struct GNUNET_FS_SearchContext *sc = cls;
1372   struct GNUNET_FS_ProgressInfo pi;
1373   unsigned int i;
1374
1375   GNUNET_FS_end_top (sc->h, sc->top);
1376   GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1377                                          &search_result_suspend, sc);
1378   pi.status = GNUNET_FS_STATUS_SEARCH_SUSPEND;
1379   sc->client_info = GNUNET_FS_search_make_status_ (&pi, sc);
1380   GNUNET_break (NULL == sc->client_info);
1381   if (sc->task != GNUNET_SCHEDULER_NO_TASK)
1382     GNUNET_SCHEDULER_cancel (sc->task);
1383   if (NULL != sc->client)
1384     GNUNET_CLIENT_disconnect (sc->client);
1385   GNUNET_CONTAINER_multihashmap_destroy (sc->master_result_map);
1386   if (NULL != sc->requests)
1387   {
1388     GNUNET_assert (GNUNET_FS_uri_test_ksk (sc->uri));
1389     for (i = 0; i < sc->uri->data.ksk.keywordCount; i++)
1390       GNUNET_CONTAINER_multihashmap_destroy (sc->requests[i].results);
1391   }
1392   GNUNET_free_non_null (sc->requests);
1393   GNUNET_free_non_null (sc->emsg);
1394   GNUNET_FS_uri_destroy (sc->uri);
1395   GNUNET_free_non_null (sc->serialization);
1396   GNUNET_free (sc);
1397 }
1398
1399
1400 /**
1401  * Start search for content.
1402  *
1403  * @param h handle to the file sharing subsystem
1404  * @param uri specifies the search parameters; can be
1405  *        a KSK URI or an SKS URI.
1406  * @param anonymity desired level of anonymity
1407  * @param options options for the search
1408  * @param cctx initial value for the client context
1409  * @return context that can be used to control the search
1410  */
1411 struct GNUNET_FS_SearchContext *
1412 GNUNET_FS_search_start (struct GNUNET_FS_Handle *h,
1413                         const struct GNUNET_FS_Uri *uri, uint32_t anonymity,
1414                         enum GNUNET_FS_SearchOptions options, void *cctx)
1415 {
1416   struct GNUNET_FS_SearchContext *ret;
1417
1418   ret = search_start (h, uri, anonymity, options, cctx, NULL);
1419   if (NULL == ret)
1420     return NULL;
1421   ret->top = GNUNET_FS_make_top (h, &GNUNET_FS_search_signal_suspend_, ret);
1422   return ret;
1423 }
1424
1425
1426 /**
1427  * Pause search.
1428  *
1429  * @param sc context for the search that should be paused
1430  */
1431 void
1432 GNUNET_FS_search_pause (struct GNUNET_FS_SearchContext *sc)
1433 {
1434   struct GNUNET_FS_ProgressInfo pi;
1435
1436   if (GNUNET_SCHEDULER_NO_TASK != sc->task)
1437     GNUNET_SCHEDULER_cancel (sc->task);
1438   sc->task = GNUNET_SCHEDULER_NO_TASK;
1439   if (NULL != sc->client)
1440     GNUNET_CLIENT_disconnect (sc->client);
1441   sc->client = NULL;
1442   GNUNET_FS_search_sync_ (sc);
1443   GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1444                                          &search_result_freeze_probes, sc);
1445   pi.status = GNUNET_FS_STATUS_SEARCH_PAUSED;
1446   sc->client_info = GNUNET_FS_search_make_status_ (&pi, sc);
1447 }
1448
1449
1450 /**
1451  * Continue paused search.
1452  *
1453  * @param sc context for the search that should be resumed
1454  */
1455 void
1456 GNUNET_FS_search_continue (struct GNUNET_FS_SearchContext *sc)
1457 {
1458   struct GNUNET_FS_ProgressInfo pi;
1459
1460   GNUNET_assert (NULL == sc->client);
1461   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == sc->task);
1462   do_reconnect (sc, NULL);
1463   GNUNET_FS_search_sync_ (sc);
1464   pi.status = GNUNET_FS_STATUS_SEARCH_CONTINUED;
1465   sc->client_info = GNUNET_FS_search_make_status_ (&pi, sc);
1466   GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1467                                          &search_result_resume_probes, sc);
1468 }
1469
1470
1471 /**
1472  * Signal stop for the given search result.
1473  *
1474  * @param cls the global FS handle
1475  * @param key the key for the search result (unused)
1476  * @param value the search result to free
1477  * @return GNUNET_OK
1478  */
1479 static int
1480 search_result_stop (void *cls, const GNUNET_HashCode * key, void *value)
1481 {
1482   struct GNUNET_FS_SearchContext *sc = cls;
1483   struct GNUNET_FS_SearchResult *sr = value;
1484   struct GNUNET_FS_ProgressInfo pi;
1485
1486   if (NULL != sr->download)
1487   {
1488     sr->download->search = NULL;
1489     sr->download->top =
1490         GNUNET_FS_make_top (sr->download->h,
1491                             &GNUNET_FS_download_signal_suspend_, sr->download);
1492     if (NULL != sr->download->serialization)
1493     {
1494       GNUNET_FS_remove_sync_file_ (sc->h, GNUNET_FS_SYNC_PATH_CHILD_DOWNLOAD,
1495                                    sr->download->serialization);
1496       GNUNET_free (sr->download->serialization);
1497       sr->download->serialization = NULL;
1498     }
1499     pi.status = GNUNET_FS_STATUS_DOWNLOAD_LOST_PARENT;
1500     GNUNET_FS_download_make_status_ (&pi, sr->download);
1501     GNUNET_FS_download_sync_ (sr->download);
1502     sr->download = NULL;
1503   }
1504   pi.status = GNUNET_FS_STATUS_SEARCH_RESULT_STOPPED;
1505   pi.value.search.specifics.result_stopped.cctx = sr->client_info;
1506   pi.value.search.specifics.result_stopped.meta = sr->meta;
1507   pi.value.search.specifics.result_stopped.uri = sr->uri;
1508   sr->client_info = GNUNET_FS_search_make_status_ (&pi, sc);
1509   return GNUNET_OK;
1510 }
1511
1512
1513 /**
1514  * Free the given search result.
1515  *
1516  * @param cls the global FS handle
1517  * @param key the key for the search result (unused)
1518  * @param value the search result to free
1519  * @return GNUNET_OK
1520  */
1521 static int
1522 search_result_free (void *cls, const GNUNET_HashCode * key, void *value)
1523 {
1524   struct GNUNET_FS_SearchResult *sr = value;
1525
1526   if (NULL != sr->update_search)
1527   {
1528     GNUNET_FS_search_stop (sr->update_search);
1529     GNUNET_assert (NULL == sr->update_search);
1530   }
1531   GNUNET_break (NULL == sr->client_info);
1532   GNUNET_free_non_null (sr->serialization);
1533   GNUNET_FS_uri_destroy (sr->uri);
1534   GNUNET_CONTAINER_meta_data_destroy (sr->meta);
1535   if (NULL != sr->probe_ctx)
1536     GNUNET_FS_download_stop (sr->probe_ctx, GNUNET_YES);
1537   if (GNUNET_SCHEDULER_NO_TASK != sr->probe_cancel_task)
1538     GNUNET_SCHEDULER_cancel (sr->probe_cancel_task);
1539   GNUNET_free_non_null (sr->keyword_bitmap);
1540   GNUNET_free (sr);
1541   return GNUNET_OK;
1542 }
1543
1544
1545 /**
1546  * Stop search for content.
1547  *
1548  * @param sc context for the search that should be stopped
1549  */
1550 void
1551 GNUNET_FS_search_stop (struct GNUNET_FS_SearchContext *sc)
1552 {
1553   struct GNUNET_FS_ProgressInfo pi;
1554   unsigned int i;
1555
1556   if (NULL != sc->top)
1557     GNUNET_FS_end_top (sc->h, sc->top);
1558   GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1559                                          &search_result_stop, sc);
1560   if (NULL != sc->psearch_result)
1561     sc->psearch_result->update_search = NULL;
1562   if (NULL != sc->serialization)
1563   {
1564     GNUNET_FS_remove_sync_file_ (sc->h,
1565                                  (sc->psearch_result !=
1566                                   NULL) ? GNUNET_FS_SYNC_PATH_CHILD_SEARCH :
1567                                  GNUNET_FS_SYNC_PATH_MASTER_SEARCH,
1568                                  sc->serialization);
1569     GNUNET_FS_remove_sync_dir_ (sc->h,
1570                                 (sc->psearch_result !=
1571                                  NULL) ? GNUNET_FS_SYNC_PATH_CHILD_SEARCH :
1572                                 GNUNET_FS_SYNC_PATH_MASTER_SEARCH,
1573                                 sc->serialization);
1574     GNUNET_free (sc->serialization);
1575   }
1576   pi.status = GNUNET_FS_STATUS_SEARCH_STOPPED;
1577   sc->client_info = GNUNET_FS_search_make_status_ (&pi, sc);
1578   GNUNET_break (NULL == sc->client_info);
1579   if (GNUNET_SCHEDULER_NO_TASK != sc->task)
1580     GNUNET_SCHEDULER_cancel (sc->task);
1581   if (NULL != sc->client)
1582     GNUNET_CLIENT_disconnect (sc->client);
1583   GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1584                                          &search_result_free, sc);
1585   GNUNET_CONTAINER_multihashmap_destroy (sc->master_result_map);
1586   if (NULL != sc->requests)
1587   {
1588     GNUNET_assert (GNUNET_FS_uri_test_ksk (sc->uri));
1589     for (i = 0; i < sc->uri->data.ksk.keywordCount; i++)
1590       GNUNET_CONTAINER_multihashmap_destroy (sc->requests[i].results);
1591   }
1592   GNUNET_free_non_null (sc->requests);
1593   GNUNET_free_non_null (sc->emsg);
1594   GNUNET_FS_uri_destroy (sc->uri);
1595   GNUNET_free (sc);
1596 }
1597
1598 /* end of fs_search.c */