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