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