-only trigger check config if we actually need it
[oweals/gnunet.git] / src / fs / gnunet-search.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2001, 2002, 2004, 2005, 2006, 2007, 2009 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20 /**
21  * @file fs/gnunet-search.c
22  * @brief searching for files on GNUnet
23  * @author Christian Grothoff
24  * @author Krista Bennett
25  * @author James Blackwell
26  * @author Igor Wronsky
27  */
28 #include "platform.h"
29 #include "gnunet_fs_service.h"
30
31 static int ret;
32
33 static const struct GNUNET_CONFIGURATION_Handle *cfg;
34
35 static struct GNUNET_FS_Handle *ctx;
36
37 static struct GNUNET_FS_SearchContext *sc;
38
39 static char *output_filename;
40
41 static struct GNUNET_FS_DirectoryBuilder *db;
42
43 static unsigned int anonymity = 1;
44
45 /**
46  * Timeout for the search, 0 means to wait for CTRL-C.
47  */
48 static struct GNUNET_TIME_Relative timeout;
49
50 static unsigned int results_limit;
51
52 static unsigned int results;
53
54 static int verbose;
55
56 static int local_only;
57
58 static struct GNUNET_SCHEDULER_Task *tt;
59
60
61 /**
62  * Type of a function that libextractor calls for each
63  * meta data item found.
64  *
65  * @param cls closure (user-defined, unused)
66  * @param plugin_name name of the plugin that produced this value;
67  *        special values can be used (i.e. '<zlib>' for zlib being
68  *        used in the main libextractor library and yielding
69  *        meta data).
70  * @param type libextractor-type describing the meta data
71  * @param format basic format information about data
72  * @param data_mime_type mime-type of data (not of the original file);
73  *        can be NULL (if mime-type is not known)
74  * @param data actual meta-data found
75  * @param data_size number of bytes in data
76  * @return 0 to continue extracting, 1 to abort
77  */
78 static int
79 item_printer (void *cls, const char *plugin_name, enum EXTRACTOR_MetaType type,
80               enum EXTRACTOR_MetaFormat format, const char *data_mime_type,
81               const char *data, size_t data_size)
82 {
83   if ((format != EXTRACTOR_METAFORMAT_UTF8) &&
84       (format != EXTRACTOR_METAFORMAT_C_STRING))
85     return 0;
86   if (type == EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME)
87     return 0;
88 #if HAVE_LIBEXTRACTOR
89   printf ("\t%20s: %s\n",
90           dgettext (LIBEXTRACTOR_GETTEXT_DOMAIN,
91                     EXTRACTOR_metatype_to_string (type)), data);
92 #else
93   printf ("\t%20d: %s\n",
94           type,
95           data);
96 #endif
97   return 0;
98 }
99
100
101 static void
102 clean_task (void *cls)
103 {
104   size_t dsize;
105   void *ddata;
106
107   GNUNET_FS_stop (ctx);
108   ctx = NULL;
109   if (output_filename == NULL)
110     return;
111   if (GNUNET_OK != GNUNET_FS_directory_builder_finish (db, &dsize, &ddata))
112   {
113     GNUNET_break (0);
114     GNUNET_free (output_filename);
115     return;
116   }
117   if (dsize !=
118       GNUNET_DISK_fn_write (output_filename, ddata, dsize,
119                             GNUNET_DISK_PERM_USER_READ |
120                             GNUNET_DISK_PERM_USER_WRITE))
121   {
122     FPRINTF (stderr,
123              _("Failed to write directory with search results to `%s'\n"),
124              output_filename);
125   }
126   GNUNET_free_non_null (ddata);
127   GNUNET_free (output_filename);
128 }
129
130
131 /**
132  * Called by FS client to give information about the progress of an
133  * operation.
134  *
135  * @param cls closure
136  * @param info details about the event, specifying the event type
137  *        and various bits about the event
138  * @return client-context (for the next progress call
139  *         for this operation; should be set to NULL for
140  *         SUSPEND and STOPPED events).  The value returned
141  *         will be passed to future callbacks in the respective
142  *         field in the GNUNET_FS_ProgressInfo struct.
143  */
144 static void *
145 progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *info)
146 {
147   static unsigned int cnt;
148   int is_directory;
149   char *uri;
150   char *filename;
151
152   switch (info->status)
153   {
154   case GNUNET_FS_STATUS_SEARCH_START:
155     break;
156   case GNUNET_FS_STATUS_SEARCH_RESULT:
157     if (db != NULL)
158       GNUNET_FS_directory_builder_add (db,
159                                        info->value.search.specifics.result.uri,
160                                        info->value.search.specifics.result.meta,
161                                        NULL);
162     uri = GNUNET_FS_uri_to_string (info->value.search.specifics.result.uri);
163     printf ("#%u:\n", cnt++);
164     filename =
165         GNUNET_CONTAINER_meta_data_get_by_type (info->value.search.
166                                                 specifics.result.meta,
167                                                 EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME);
168     is_directory =
169         GNUNET_FS_meta_data_test_for_directory (info->value.search.
170                                                 specifics.result.meta);
171     if (filename != NULL)
172     {
173       GNUNET_DISK_filename_canonicalize (filename);
174       if (GNUNET_YES == is_directory)
175         printf ("gnunet-download -o \"%s%s\" -R %s\n", filename, GNUNET_FS_DIRECTORY_EXT, uri);
176       else
177         printf ("gnunet-download -o \"%s\" %s\n", filename, uri);
178     }
179     else if (GNUNET_YES == is_directory)
180       printf ("gnunet-download -o \"collection%s\" -R %s\n", GNUNET_FS_DIRECTORY_EXT, uri);
181     else
182       printf ("gnunet-download %s\n", uri);
183     if (verbose)
184       GNUNET_CONTAINER_meta_data_iterate (info->value.search.specifics.
185                                           result.meta, &item_printer, NULL);
186     printf ("\n");
187     fflush (stdout);
188     GNUNET_free_non_null (filename);
189     GNUNET_free (uri);
190     results++;
191     if ((results_limit > 0) && (results >= results_limit))
192       GNUNET_SCHEDULER_shutdown ();
193     break;
194   case GNUNET_FS_STATUS_SEARCH_UPDATE:
195     break;
196   case GNUNET_FS_STATUS_SEARCH_RESULT_STOPPED:
197     /* ignore */
198     break;
199   case GNUNET_FS_STATUS_SEARCH_ERROR:
200     FPRINTF (stderr, _("Error searching: %s.\n"),
201              info->value.search.specifics.error.message);
202     GNUNET_SCHEDULER_shutdown ();
203     break;
204   case GNUNET_FS_STATUS_SEARCH_STOPPED:
205     GNUNET_SCHEDULER_add_now (&clean_task, NULL);
206     break;
207   default:
208     FPRINTF (stderr, _("Unexpected status: %d\n"), info->status);
209     break;
210   }
211   return NULL;
212 }
213
214
215 static void
216 shutdown_task (void *cls)
217 {
218   if (sc != NULL)
219   {
220     GNUNET_FS_search_stop (sc);
221     sc = NULL;
222   }
223 }
224
225
226 static void
227 timeout_task (void *cls)
228 {
229   tt = NULL;
230   GNUNET_SCHEDULER_shutdown ();
231 }
232
233
234 /**
235  * Main function that will be run by the scheduler.
236  *
237  * @param cls closure
238  * @param args remaining command-line arguments
239  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
240  * @param c configuration
241  */
242 static void
243 run (void *cls, char *const *args, const char *cfgfile,
244      const struct GNUNET_CONFIGURATION_Handle *c)
245 {
246   struct GNUNET_FS_Uri *uri;
247   unsigned int argc;
248   enum GNUNET_FS_SearchOptions options;
249
250   argc = 0;
251   while (NULL != args[argc])
252     argc++;
253   uri = GNUNET_FS_uri_ksk_create_from_args (argc, (const char **) args);
254   if (NULL == uri)
255   {
256     FPRINTF (stderr, "%s",  _("Could not create keyword URI from arguments.\n"));
257     ret = 1;
258     return;
259   }
260   cfg = c;
261   ctx =
262       GNUNET_FS_start (cfg, "gnunet-search", &progress_cb, NULL,
263                        GNUNET_FS_FLAGS_NONE, GNUNET_FS_OPTIONS_END);
264   if (NULL == ctx)
265   {
266     FPRINTF (stderr, _("Could not initialize `%s' subsystem.\n"), "FS");
267     GNUNET_FS_uri_destroy (uri);
268     ret = 1;
269     return;
270   }
271   if (output_filename != NULL)
272     db = GNUNET_FS_directory_builder_create (NULL);
273   options = GNUNET_FS_SEARCH_OPTION_NONE;
274   if (local_only)
275     options |= GNUNET_FS_SEARCH_OPTION_LOOPBACK_ONLY;
276   sc = GNUNET_FS_search_start (ctx, uri, anonymity, options, NULL);
277   GNUNET_FS_uri_destroy (uri);
278   if (NULL == sc)
279   {
280     FPRINTF (stderr, "%s",  _("Could not start searching.\n"));
281     GNUNET_FS_stop (ctx);
282     ret = 1;
283     return;
284   }
285   if (0 != timeout.rel_value_us)
286     tt = GNUNET_SCHEDULER_add_delayed (timeout,
287                                        &timeout_task,
288                                        NULL);
289   GNUNET_SCHEDULER_add_shutdown (&shutdown_task,
290                                  NULL);
291 }
292
293
294 /**
295  * The main function to search GNUnet.
296  *
297  * @param argc number of arguments from the command line
298  * @param argv command line arguments
299  * @return 0 ok, 1 on error
300  */
301 int
302 main (int argc, char *const *argv)
303 {
304   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
305     {'a', "anonymity", "LEVEL",
306      gettext_noop ("set the desired LEVEL of receiver-anonymity"),
307      1, &GNUNET_GETOPT_set_uint, &anonymity},
308     {'n', "no-network", NULL,
309      gettext_noop ("only search the local peer (no P2P network search)"),
310      0, &GNUNET_GETOPT_set_one, &local_only},
311     {'o', "output", "PREFIX",
312      gettext_noop ("write search results to file starting with PREFIX"),
313      1, &GNUNET_GETOPT_set_string, &output_filename},
314     {'t', "timeout", "DELAY",
315      gettext_noop ("automatically terminate search after DELAY"),
316      1, &GNUNET_GETOPT_set_relative_time, &timeout},
317     {'V', "verbose", NULL,
318      gettext_noop ("be verbose (print progress information)"),
319      0, &GNUNET_GETOPT_set_one, &verbose},
320     {'N', "results", "VALUE",
321      gettext_noop
322      ("automatically terminate search after VALUE results are found"),
323      1, &GNUNET_GETOPT_set_uint, &results_limit},
324     GNUNET_GETOPT_OPTION_END
325   };
326
327   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
328     return 2;
329
330   ret = (GNUNET_OK ==
331          GNUNET_PROGRAM_run (argc, argv, "gnunet-search [OPTIONS] KEYWORD",
332                              gettext_noop
333                              ("Search GNUnet for files that were published on GNUnet"),
334                              options, &run, NULL)) ? ret : 1;
335   GNUNET_free ((void*) argv);
336   return ret;
337 }
338
339 /* end of gnunet-search.c */