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