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