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