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