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