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