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