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