fix for mantis 2445
[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.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   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.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   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     mbc.put_cnt = 0;
1018     GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1019                                            &find_result_set, &mbc);
1020     sqms = mbc.put_cnt;
1021     mbc.put_cnt = (size - msize) / sizeof (struct GNUNET_HashCode);
1022     mbc.put_cnt = GNUNET_MIN (mbc.put_cnt, sqms - mbc.skip_cnt);
1023     if (sc->search_request_map_offset < sqms)
1024       GNUNET_assert (mbc.put_cnt > 0);
1025
1026     sm->header.size = htons (msize);
1027     sm->type = htonl (GNUNET_BLOCK_TYPE_ANY);
1028     sm->anonymity_level = htonl (sc->anonymity);
1029     memset (&sm->target, 0, sizeof (struct GNUNET_HashCode));
1030     sm->query = sc->requests[sc->keyword_offset].query;
1031     msize += sizeof (struct GNUNET_HashCode) * mbc.put_cnt;
1032     GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1033                                            &build_result_set, &mbc);
1034     sm->header.size = htons (msize);
1035     GNUNET_assert (sqms >= sc->search_request_map_offset);
1036     if (sqms != sc->search_request_map_offset)
1037     {
1038       /* more requesting to be done... */
1039       sm->options = htonl (options | SEARCH_MESSAGE_OPTION_CONTINUED);
1040       schedule_transmit_search_request (sc);
1041       return msize;
1042     }
1043     sm->options = htonl (options);
1044     sc->keyword_offset++;
1045     if (sc->uri->data.ksk.keywordCount != sc->keyword_offset)
1046     {
1047       /* more requesting to be done... */
1048       schedule_transmit_search_request (sc);
1049       return msize;
1050     }
1051   }
1052   else
1053   {
1054     GNUNET_assert (GNUNET_FS_uri_test_sks (sc->uri));
1055     msize = sizeof (struct SearchMessage);
1056     GNUNET_assert (size >= msize);
1057     sm->type = htonl (GNUNET_BLOCK_TYPE_FS_SBLOCK);
1058     sm->anonymity_level = htonl (sc->anonymity);
1059     sm->target = sc->uri->data.sks.namespace;
1060     identifier = sc->uri->data.sks.identifier;
1061     GNUNET_CRYPTO_hash (identifier, strlen (identifier), &key);
1062     GNUNET_CRYPTO_hash (&key, sizeof (struct GNUNET_HashCode), &idh);
1063     GNUNET_CRYPTO_hash_xor (&idh, &sm->target, &sm->query);
1064     mbc.put_cnt = (size - msize) / sizeof (struct GNUNET_HashCode);
1065     sqms = GNUNET_CONTAINER_multihashmap_size (sc->master_result_map);
1066     mbc.put_cnt = GNUNET_MIN (mbc.put_cnt, sqms - mbc.skip_cnt);
1067     mbc.keyword_offset = 0;
1068     if (sc->search_request_map_offset < sqms)
1069       GNUNET_assert (mbc.put_cnt > 0);
1070     msize += sizeof (struct GNUNET_HashCode) * mbc.put_cnt;
1071     GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1072                                            &build_result_set, &mbc);
1073     sm->header.size = htons (msize);
1074     GNUNET_assert (sqms >= sc->search_request_map_offset);
1075     if (sqms != sc->search_request_map_offset)
1076     {
1077       /* more requesting to be done... */
1078       sm->options = htonl (options | SEARCH_MESSAGE_OPTION_CONTINUED);
1079       schedule_transmit_search_request (sc);
1080       return msize;
1081     }
1082     sm->options = htonl (options);
1083   }
1084   GNUNET_CLIENT_receive (sc->client, &receive_results, sc,
1085                          GNUNET_TIME_UNIT_FOREVER_REL);
1086   return msize;
1087 }
1088
1089
1090 /**
1091  * Schedule the transmission of the (next) search request
1092  * to the service.
1093  *
1094  * @param sc context for the search
1095  */
1096 static void
1097 schedule_transmit_search_request (struct GNUNET_FS_SearchContext *sc)
1098 {
1099   size_t size;
1100   unsigned int sqms;
1101   unsigned int fit;
1102
1103   size = sizeof (struct SearchMessage);
1104   sqms =
1105       GNUNET_CONTAINER_multihashmap_size (sc->master_result_map) -
1106       sc->search_request_map_offset;
1107   fit = (GNUNET_SERVER_MAX_MESSAGE_SIZE - 1 - size) / sizeof (struct GNUNET_HashCode);
1108   fit = GNUNET_MIN (fit, sqms);
1109   size += sizeof (struct GNUNET_HashCode) * fit;
1110   GNUNET_CLIENT_notify_transmit_ready (sc->client, size,
1111                                        GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1112                                        GNUNET_NO, &transmit_search_request, sc);
1113
1114 }
1115
1116
1117 /**
1118  * Reconnect to the FS service and transmit
1119  * our queries NOW.
1120  *
1121  * @param cls our search context
1122  * @param tc unused
1123  */
1124 static void
1125 do_reconnect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1126 {
1127   struct GNUNET_FS_SearchContext *sc = cls;
1128   struct GNUNET_CLIENT_Connection *client;
1129
1130   sc->task = GNUNET_SCHEDULER_NO_TASK;
1131   client = GNUNET_CLIENT_connect ("fs", sc->h->cfg);
1132   if (NULL == client)
1133   {
1134     try_reconnect (sc);
1135     return;
1136   }
1137   sc->client = client;
1138   sc->search_request_map_offset = 0;
1139   sc->keyword_offset = 0;
1140   schedule_transmit_search_request (sc);
1141 }
1142
1143
1144 /**
1145  * Shutdown any existing connection to the FS
1146  * service and try to establish a fresh one
1147  * (and then re-transmit our search request).
1148  *
1149  * @param sc the search to reconnec
1150  */
1151 static void
1152 try_reconnect (struct GNUNET_FS_SearchContext *sc)
1153 {
1154   if (NULL != sc->client)
1155   {
1156     GNUNET_CLIENT_disconnect (sc->client);
1157     sc->client = NULL;
1158   }
1159   sc->task =
1160       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, &do_reconnect,
1161                                     sc);
1162 }
1163
1164
1165 /**
1166  * Start search for content, internal API.
1167  *
1168  * @param h handle to the file sharing subsystem
1169  * @param uri specifies the search parameters; can be
1170  *        a KSK URI or an SKS URI.
1171  * @param anonymity desired level of anonymity
1172  * @param options options for the search
1173  * @param cctx initial value for the client context
1174  * @param psearch parent search result (for namespace update searches)
1175  * @return context that can be used to control the search
1176  */
1177 static struct GNUNET_FS_SearchContext *
1178 search_start (struct GNUNET_FS_Handle *h, const struct GNUNET_FS_Uri *uri,
1179               uint32_t anonymity, enum GNUNET_FS_SearchOptions options,
1180               void *cctx, struct GNUNET_FS_SearchResult *psearch)
1181 {
1182   struct GNUNET_FS_SearchContext *sc;
1183   struct GNUNET_FS_ProgressInfo pi;
1184
1185   sc = GNUNET_malloc (sizeof (struct GNUNET_FS_SearchContext));
1186   sc->h = h;
1187   sc->options = options;
1188   sc->uri = GNUNET_FS_uri_dup (uri);
1189   sc->anonymity = anonymity;
1190   sc->start_time = GNUNET_TIME_absolute_get ();
1191   if (NULL != psearch)
1192   {
1193     sc->psearch_result = psearch;
1194     psearch->update_search = sc;
1195   }
1196   sc->master_result_map = GNUNET_CONTAINER_multihashmap_create (16);
1197   sc->client_info = cctx;
1198   if (GNUNET_OK != GNUNET_FS_search_start_searching_ (sc))
1199   {
1200     GNUNET_FS_uri_destroy (sc->uri);
1201     GNUNET_CONTAINER_multihashmap_destroy (sc->master_result_map);
1202     GNUNET_free (sc);
1203     return NULL;
1204   }
1205   GNUNET_FS_search_sync_ (sc);
1206   pi.status = GNUNET_FS_STATUS_SEARCH_START;
1207   sc->client_info = GNUNET_FS_search_make_status_ (&pi, sc);
1208   return sc;
1209 }
1210
1211
1212 /**
1213  * Build the request and actually initiate the search using the
1214  * GNUnet FS service.
1215  *
1216  * @param sc search context
1217  * @return GNUNET_OK on success, GNUNET_SYSERR on error
1218  */
1219 int
1220 GNUNET_FS_search_start_searching_ (struct GNUNET_FS_SearchContext *sc)
1221 {
1222   unsigned int i;
1223   const char *keyword;
1224   struct GNUNET_HashCode hc;
1225   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pub;
1226   struct GNUNET_CRYPTO_RsaPrivateKey *pk;
1227
1228   GNUNET_assert (NULL == sc->client);
1229   if (GNUNET_FS_uri_test_ksk (sc->uri))
1230   {
1231     GNUNET_assert (0 != sc->uri->data.ksk.keywordCount);
1232     sc->requests =
1233         GNUNET_malloc (sizeof (struct SearchRequestEntry) *
1234                        sc->uri->data.ksk.keywordCount);
1235     for (i = 0; i < sc->uri->data.ksk.keywordCount; i++)
1236     {
1237       keyword = &sc->uri->data.ksk.keywords[i][1];
1238       GNUNET_CRYPTO_hash (keyword, strlen (keyword), &hc);
1239       pk = GNUNET_CRYPTO_rsa_key_create_from_hash (&hc);
1240       GNUNET_assert (NULL != pk);
1241       GNUNET_CRYPTO_rsa_key_get_public (pk, &pub);
1242       GNUNET_CRYPTO_rsa_key_free (pk);
1243       GNUNET_CRYPTO_hash (&pub,
1244                           sizeof (struct
1245                                   GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1246                           &sc->requests[i].query);
1247       sc->requests[i].mandatory = (sc->uri->data.ksk.keywords[i][0] == '+');
1248       if (sc->requests[i].mandatory)
1249         sc->mandatory_count++;
1250       sc->requests[i].results = GNUNET_CONTAINER_multihashmap_create (4);
1251       GNUNET_CRYPTO_hash (keyword, strlen (keyword), &sc->requests[i].key);
1252     }
1253   }
1254   sc->client = GNUNET_CLIENT_connect ("fs", sc->h->cfg);
1255   if (NULL == sc->client)
1256     return GNUNET_SYSERR;
1257   schedule_transmit_search_request (sc);
1258   return GNUNET_OK;
1259 }
1260
1261
1262 /**
1263  * Freeze probes for the given search result.
1264  *
1265  * @param cls the global FS handle
1266  * @param key the key for the search result (unused)
1267  * @param value the search result to free
1268  * @return GNUNET_OK
1269  */
1270 static int
1271 search_result_freeze_probes (void *cls, const struct GNUNET_HashCode * key,
1272                              void *value)
1273 {
1274   struct GNUNET_FS_SearchResult *sr = value;
1275
1276   if (NULL != sr->probe_ctx)
1277   {
1278     GNUNET_FS_download_stop (sr->probe_ctx, GNUNET_YES);
1279     sr->probe_ctx = NULL;
1280   }
1281   if (GNUNET_SCHEDULER_NO_TASK != sr->probe_cancel_task)
1282   {
1283     GNUNET_SCHEDULER_cancel (sr->probe_cancel_task);
1284     sr->probe_cancel_task = GNUNET_SCHEDULER_NO_TASK;
1285   }
1286   if (NULL != sr->update_search)
1287     GNUNET_FS_search_pause (sr->update_search);
1288   return GNUNET_OK;
1289 }
1290
1291
1292 /**
1293  * Resume probes for the given search result.
1294  *
1295  * @param cls the global FS handle
1296  * @param key the key for the search result (unused)
1297  * @param value the search result to free
1298  * @return GNUNET_OK
1299  */
1300 static int
1301 search_result_resume_probes (void *cls, const struct GNUNET_HashCode * key,
1302                              void *value)
1303 {
1304   struct GNUNET_FS_SearchResult *sr = value;
1305
1306   GNUNET_FS_search_start_probe_ (sr);
1307   if (NULL != sr->update_search)
1308     GNUNET_FS_search_continue (sr->update_search);
1309   return GNUNET_OK;
1310 }
1311
1312
1313 /**
1314  * Signal suspend and free the given search result.
1315  *
1316  * @param cls the global FS handle
1317  * @param key the key for the search result (unused)
1318  * @param value the search result to free
1319  * @return GNUNET_OK
1320  */
1321 static int
1322 search_result_suspend (void *cls, const struct GNUNET_HashCode * key, void *value)
1323 {
1324   struct GNUNET_FS_SearchContext *sc = cls;
1325   struct GNUNET_FS_SearchResult *sr = value;
1326   struct GNUNET_FS_ProgressInfo pi;
1327
1328   if (NULL != sr->download)
1329   {
1330     GNUNET_FS_download_signal_suspend_ (sr->download);
1331     sr->download = NULL;
1332   }
1333   if (NULL != sr->probe_ctx)
1334   {
1335     GNUNET_FS_download_stop (sr->probe_ctx, GNUNET_YES);
1336     sr->probe_ctx = NULL;
1337   }
1338   if (NULL != sr->update_search)
1339   {
1340     GNUNET_FS_search_signal_suspend_ (sr->update_search);
1341     sr->update_search = NULL;
1342   }
1343   pi.status = GNUNET_FS_STATUS_SEARCH_RESULT_SUSPEND;
1344   pi.value.search.specifics.result_suspend.cctx = sr->client_info;
1345   pi.value.search.specifics.result_suspend.meta = sr->meta;
1346   pi.value.search.specifics.result_suspend.uri = sr->uri;
1347   sr->client_info = GNUNET_FS_search_make_status_ (&pi, sc);
1348   GNUNET_break (NULL == sr->client_info);
1349   GNUNET_free_non_null (sr->serialization);
1350   GNUNET_FS_uri_destroy (sr->uri);
1351   GNUNET_CONTAINER_meta_data_destroy (sr->meta);
1352   if (GNUNET_SCHEDULER_NO_TASK != sr->probe_cancel_task)
1353   {
1354     GNUNET_SCHEDULER_cancel (sr->probe_cancel_task);
1355     sr->probe_cancel_task = GNUNET_SCHEDULER_NO_TASK;
1356   }
1357   GNUNET_free_non_null (sr->keyword_bitmap);
1358   GNUNET_free (sr);
1359   return GNUNET_OK;
1360 }
1361
1362
1363 /**
1364  * Create SUSPEND event for the given search operation
1365  * and then clean up our state (without stop signal).
1366  *
1367  * @param cls the 'struct GNUNET_FS_SearchContext' to signal for
1368  */
1369 void
1370 GNUNET_FS_search_signal_suspend_ (void *cls)
1371 {
1372   struct GNUNET_FS_SearchContext *sc = cls;
1373   struct GNUNET_FS_ProgressInfo pi;
1374   unsigned int i;
1375
1376   GNUNET_FS_end_top (sc->h, sc->top);
1377   GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1378                                          &search_result_suspend, sc);
1379   pi.status = GNUNET_FS_STATUS_SEARCH_SUSPEND;
1380   sc->client_info = GNUNET_FS_search_make_status_ (&pi, sc);
1381   GNUNET_break (NULL == sc->client_info);
1382   if (sc->task != GNUNET_SCHEDULER_NO_TASK)
1383     GNUNET_SCHEDULER_cancel (sc->task);
1384   if (NULL != sc->client)
1385     GNUNET_CLIENT_disconnect (sc->client);
1386   GNUNET_CONTAINER_multihashmap_destroy (sc->master_result_map);
1387   if (NULL != sc->requests)
1388   {
1389     GNUNET_assert (GNUNET_FS_uri_test_ksk (sc->uri));
1390     for (i = 0; i < sc->uri->data.ksk.keywordCount; i++)
1391       GNUNET_CONTAINER_multihashmap_destroy (sc->requests[i].results);
1392   }
1393   GNUNET_free_non_null (sc->requests);
1394   GNUNET_free_non_null (sc->emsg);
1395   GNUNET_FS_uri_destroy (sc->uri);
1396   GNUNET_free_non_null (sc->serialization);
1397   GNUNET_free (sc);
1398 }
1399
1400
1401 /**
1402  * Start search for content.
1403  *
1404  * @param h handle to the file sharing subsystem
1405  * @param uri specifies the search parameters; can be
1406  *        a KSK URI or an SKS URI.
1407  * @param anonymity desired level of anonymity
1408  * @param options options for the search
1409  * @param cctx initial value for the client context
1410  * @return context that can be used to control the search
1411  */
1412 struct GNUNET_FS_SearchContext *
1413 GNUNET_FS_search_start (struct GNUNET_FS_Handle *h,
1414                         const struct GNUNET_FS_Uri *uri, uint32_t anonymity,
1415                         enum GNUNET_FS_SearchOptions options, void *cctx)
1416 {
1417   struct GNUNET_FS_SearchContext *ret;
1418
1419   ret = search_start (h, uri, anonymity, options, cctx, NULL);
1420   if (NULL == ret)
1421     return NULL;
1422   ret->top = GNUNET_FS_make_top (h, &GNUNET_FS_search_signal_suspend_, ret);
1423   return ret;
1424 }
1425
1426
1427 /**
1428  * Pause search.
1429  *
1430  * @param sc context for the search that should be paused
1431  */
1432 void
1433 GNUNET_FS_search_pause (struct GNUNET_FS_SearchContext *sc)
1434 {
1435   struct GNUNET_FS_ProgressInfo pi;
1436
1437   if (GNUNET_SCHEDULER_NO_TASK != sc->task)
1438     GNUNET_SCHEDULER_cancel (sc->task);
1439   sc->task = GNUNET_SCHEDULER_NO_TASK;
1440   if (NULL != sc->client)
1441     GNUNET_CLIENT_disconnect (sc->client);
1442   sc->client = NULL;
1443   GNUNET_FS_search_sync_ (sc);
1444   GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1445                                          &search_result_freeze_probes, sc);
1446   pi.status = GNUNET_FS_STATUS_SEARCH_PAUSED;
1447   sc->client_info = GNUNET_FS_search_make_status_ (&pi, sc);
1448 }
1449
1450
1451 /**
1452  * Continue paused search.
1453  *
1454  * @param sc context for the search that should be resumed
1455  */
1456 void
1457 GNUNET_FS_search_continue (struct GNUNET_FS_SearchContext *sc)
1458 {
1459   struct GNUNET_FS_ProgressInfo pi;
1460
1461   GNUNET_assert (NULL == sc->client);
1462   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == sc->task);
1463   do_reconnect (sc, NULL);
1464   GNUNET_FS_search_sync_ (sc);
1465   pi.status = GNUNET_FS_STATUS_SEARCH_CONTINUED;
1466   sc->client_info = GNUNET_FS_search_make_status_ (&pi, sc);
1467   GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1468                                          &search_result_resume_probes, sc);
1469 }
1470
1471
1472 /**
1473  * Signal stop for the given search result.
1474  *
1475  * @param cls the global FS handle
1476  * @param key the key for the search result (unused)
1477  * @param value the search result to free
1478  * @return GNUNET_OK
1479  */
1480 static int
1481 search_result_stop (void *cls, const struct GNUNET_HashCode * key, void *value)
1482 {
1483   struct GNUNET_FS_SearchContext *sc = cls;
1484   struct GNUNET_FS_SearchResult *sr = value;
1485   struct GNUNET_FS_ProgressInfo pi;
1486
1487   if (NULL != sr->probe_ctx)
1488   {
1489     GNUNET_FS_download_stop (sr->probe_ctx, GNUNET_YES);
1490     sr->probe_ctx = NULL;
1491   }
1492   if (GNUNET_SCHEDULER_NO_TASK != sr->probe_cancel_task)
1493   {
1494     GNUNET_SCHEDULER_cancel (sr->probe_cancel_task);
1495     sr->probe_cancel_task = GNUNET_SCHEDULER_NO_TASK;
1496   }
1497
1498   if (NULL != sr->download)
1499   {
1500     sr->download->search = NULL;
1501     sr->download->top =
1502         GNUNET_FS_make_top (sr->download->h,
1503                             &GNUNET_FS_download_signal_suspend_, sr->download);
1504     if (NULL != sr->download->serialization)
1505     {
1506       GNUNET_FS_remove_sync_file_ (sc->h, GNUNET_FS_SYNC_PATH_CHILD_DOWNLOAD,
1507                                    sr->download->serialization);
1508       GNUNET_free (sr->download->serialization);
1509       sr->download->serialization = NULL;
1510     }
1511     pi.status = GNUNET_FS_STATUS_DOWNLOAD_LOST_PARENT;
1512     GNUNET_FS_download_make_status_ (&pi, sr->download);
1513     GNUNET_FS_download_sync_ (sr->download);
1514     sr->download = NULL;
1515   }
1516   pi.status = GNUNET_FS_STATUS_SEARCH_RESULT_STOPPED;
1517   pi.value.search.specifics.result_stopped.cctx = sr->client_info;
1518   pi.value.search.specifics.result_stopped.meta = sr->meta;
1519   pi.value.search.specifics.result_stopped.uri = sr->uri;
1520   sr->client_info = GNUNET_FS_search_make_status_ (&pi, sc);
1521   return GNUNET_OK;
1522 }
1523
1524
1525 /**
1526  * Free the given search result.
1527  *
1528  * @param cls the global FS handle
1529  * @param key the key for the search result (unused)
1530  * @param value the search result to free
1531  * @return GNUNET_OK
1532  */
1533 static int
1534 search_result_free (void *cls, const struct GNUNET_HashCode * key, void *value)
1535 {
1536   struct GNUNET_FS_SearchResult *sr = value;
1537
1538   if (NULL != sr->update_search)
1539   {
1540     GNUNET_FS_search_stop (sr->update_search);
1541     GNUNET_assert (NULL == sr->update_search);
1542   }
1543   GNUNET_break (NULL == sr->probe_ctx);
1544   GNUNET_break (GNUNET_SCHEDULER_NO_TASK == sr->probe_cancel_task);
1545   GNUNET_break (NULL == sr->client_info);
1546   GNUNET_free_non_null (sr->serialization);
1547   GNUNET_FS_uri_destroy (sr->uri);
1548   GNUNET_CONTAINER_meta_data_destroy (sr->meta);
1549   GNUNET_free_non_null (sr->keyword_bitmap);
1550   GNUNET_free (sr);
1551   return GNUNET_OK;
1552 }
1553
1554
1555 /**
1556  * Stop search for content.
1557  *
1558  * @param sc context for the search that should be stopped
1559  */
1560 void
1561 GNUNET_FS_search_stop (struct GNUNET_FS_SearchContext *sc)
1562 {
1563   struct GNUNET_FS_ProgressInfo pi;
1564   unsigned int i;
1565
1566   if (NULL != sc->top)
1567     GNUNET_FS_end_top (sc->h, sc->top);
1568   GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1569                                          &search_result_stop, sc);
1570   if (NULL != sc->psearch_result)
1571     sc->psearch_result->update_search = NULL;
1572   if (NULL != sc->serialization)
1573   {
1574     GNUNET_FS_remove_sync_file_ (sc->h,
1575                                  (sc->psearch_result !=
1576                                   NULL) ? GNUNET_FS_SYNC_PATH_CHILD_SEARCH :
1577                                  GNUNET_FS_SYNC_PATH_MASTER_SEARCH,
1578                                  sc->serialization);
1579     GNUNET_FS_remove_sync_dir_ (sc->h,
1580                                 (sc->psearch_result !=
1581                                  NULL) ? GNUNET_FS_SYNC_PATH_CHILD_SEARCH :
1582                                 GNUNET_FS_SYNC_PATH_MASTER_SEARCH,
1583                                 sc->serialization);
1584     GNUNET_free (sc->serialization);
1585   }
1586   pi.status = GNUNET_FS_STATUS_SEARCH_STOPPED;
1587   sc->client_info = GNUNET_FS_search_make_status_ (&pi, sc);
1588   GNUNET_break (NULL == sc->client_info);
1589   if (GNUNET_SCHEDULER_NO_TASK != sc->task)
1590     GNUNET_SCHEDULER_cancel (sc->task);
1591   if (NULL != sc->client)
1592     GNUNET_CLIENT_disconnect (sc->client);
1593   GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map,
1594                                          &search_result_free, sc);
1595   GNUNET_CONTAINER_multihashmap_destroy (sc->master_result_map);
1596   if (NULL != sc->requests)
1597   {
1598     GNUNET_assert (GNUNET_FS_uri_test_ksk (sc->uri));
1599     for (i = 0; i < sc->uri->data.ksk.keywordCount; i++)
1600       GNUNET_CONTAINER_multihashmap_destroy (sc->requests[i].results);
1601   }
1602   GNUNET_free_non_null (sc->requests);
1603   GNUNET_free_non_null (sc->emsg);
1604   GNUNET_FS_uri_destroy (sc->uri);
1605   GNUNET_free (sc);
1606 }
1607
1608 /* end of fs_search.c */