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