fixing drq code
[oweals/gnunet.git] / src / fs / gnunet-publish.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 2, 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-publish.c
22  * @brief publishing files on GNUnet
23  * @author Christian Grothoff
24  * @author Krista Bennett
25  * @author James Blackwell
26  * @author Igor Wronsky
27  *
28  * TODO:
29  * - support for some options is still missing (uri argument)
30  */
31 #include "platform.h"
32 #include "gnunet_fs_service.h"
33
34 #define DEFAULT_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_YEARS, 2)
35
36 static int ret;
37
38 static int verbose;
39
40 static const struct GNUNET_CONFIGURATION_Handle *cfg;
41
42 static struct GNUNET_FS_Handle *ctx;
43
44 static struct GNUNET_FS_PublishContext *pc;
45
46 static struct GNUNET_CONTAINER_MetaData *meta;
47
48 static struct GNUNET_FS_Uri *topKeywords;
49
50 static unsigned int anonymity = 1;
51
52 static unsigned int priority = 365;
53
54 static char *uri_string;
55
56 static char *next_id;
57
58 static char *this_id;
59
60 static char *pseudonym;
61
62 static int do_insert;
63
64 static int disable_extractor;
65
66 static int do_simulate;
67
68 static int extract_only;
69
70 static int do_disable_creation_time;
71
72
73 /**
74  * Called by FS client to give information about the progress of an 
75  * operation.
76  *
77  * @param cls closure
78  * @param info details about the event, specifying the event type
79  *        and various bits about the event
80  * @return client-context (for the next progress call
81  *         for this operation; should be set to NULL for
82  *         SUSPEND and STOPPED events).  The value returned
83  *         will be passed to future callbacks in the respective
84  *         field in the GNUNET_FS_ProgressInfo struct.
85  */
86 static void *
87 progress_cb (void *cls,
88              const struct GNUNET_FS_ProgressInfo *info)
89 {
90   char *s;
91
92   switch (info->status)
93     {
94     case GNUNET_FS_STATUS_PUBLISH_START:
95       break;
96     case GNUNET_FS_STATUS_PUBLISH_PROGRESS:
97       if (verbose)
98         {
99           s = GNUNET_STRINGS_relative_time_to_string(info->value.publish.eta);
100           fprintf (stdout,
101                    _("Publishing `%s' at %llu/%llu (%s remaining)\n"),
102                    info->value.publish.filename,
103                    (unsigned long long) info->value.publish.completed,
104                    (unsigned long long) info->value.publish.size,
105                    s);
106           GNUNET_free (s);
107         }
108       break;
109     case GNUNET_FS_STATUS_PUBLISH_ERROR:
110       fprintf (stderr,
111                _("Error publishing: %s.\n"),
112                info->value.publish.specifics.error.message);
113       GNUNET_FS_publish_stop (pc);      
114       break;
115     case GNUNET_FS_STATUS_PUBLISH_COMPLETED:
116       fprintf (stdout,
117                _("Publishing `%s' done.\n"),
118                info->value.publish.filename);
119       if (info->value.publish.pctx == NULL)
120         GNUNET_FS_publish_stop (pc);
121       break;
122     case GNUNET_FS_STATUS_PUBLISH_STOPPED: 
123       if (info->value.publish.sc == pc)
124         GNUNET_FS_stop (ctx);
125       return NULL;      
126     default:
127       fprintf (stderr,
128                _("Unexpected status: %d\n"),
129                info->status);
130       return NULL;
131     }
132   return ""; /* non-null */
133 }
134
135
136 /**
137  * Print metadata entries (except binary
138  * metadata and the filename).
139  *
140  * @param cls closure
141  * @param plugin_name name of the plugin that generated the meta data
142  * @param type type of the meta data
143  * @param format format of data
144  * @param data_mime_type mime type of data
145  * @param data value of the meta data
146  * @param data_size number of bytes in data
147  * @return always 0
148  */
149 static int
150 meta_printer (void *cls,
151               const char *plugin_name,
152               enum EXTRACTOR_MetaType type, 
153               enum EXTRACTOR_MetaFormat format,
154               const char *data_mime_type,
155               const char *data,
156               size_t data_size)
157 {
158   if ( (format != EXTRACTOR_METAFORMAT_UTF8) &&
159        (format != EXTRACTOR_METAFORMAT_C_STRING) )
160     return 0;
161   if (type == EXTRACTOR_METATYPE_FILENAME) 
162     return 0;
163   fprintf (stdout, 
164            "%s - %s",
165            EXTRACTOR_metatype_to_string (type),
166            data);
167   return 0;
168 }
169
170
171 /**
172  * Merge metadata entries.
173  *
174  * @param cls closure, target metadata structure
175  * @param plugin_name name of the plugin that generated the meta data
176  * @param type type of the meta data
177  * @param format format of data
178  * @param data_mime_type mime type of data
179  * @param data value of the meta data
180  * @param data_size number of bytes in data
181  * @return always 0
182  */
183 static int
184 meta_merger (void *cls,
185               const char *plugin_name,
186               enum EXTRACTOR_MetaType type, 
187               enum EXTRACTOR_MetaFormat format,
188               const char *data_mime_type,
189               const char *data,
190               size_t data_size)
191 {
192   struct GNUNET_CONTAINER_MetaData *m = cls;
193
194   GNUNET_CONTAINER_meta_data_insert (m,
195                                      plugin_name,
196                                      type, 
197                                      format,
198                                      data_mime_type,
199                                      data,
200                                      data_size);
201   return 0;
202 }
203
204
205 /**
206  * Function called on all entries before the
207  * publication.  This is where we perform
208  * modifications to the default based on
209  * command-line options.
210  *
211  * @param cls closure
212  * @param fi the entry in the publish-structure
213  * @param length length of the file or directory
214  * @param m metadata for the file or directory (can be modified)
215  * @param uri pointer to the keywords that will be used for this entry (can be modified)
216  * @param anonymity pointer to selected anonymity level (can be modified)
217  * @param priority pointer to selected priority (can be modified)
218  * @param expirationTime pointer to selected expiration time (can be modified)
219  * @param client_info pointer to client context set upon creation (can be modified)
220  * @return GNUNET_OK to continue, GNUNET_NO to remove
221  *         this entry from the directory, GNUNET_SYSERR
222  *         to abort the iteration
223  */
224 static int
225 publish_inspector (void *cls,
226                    struct GNUNET_FS_FileInformation *fi,
227                    uint64_t length,
228                    struct GNUNET_CONTAINER_MetaData *m,
229                    struct GNUNET_FS_Uri **uri,
230                    unsigned int *anonymity,
231                    unsigned int *priority,
232                    struct GNUNET_TIME_Absolute *expirationTime,
233                    void **client_info)
234 {
235   char *fn;
236   char *fs;
237   struct GNUNET_FS_Uri *new_uri;
238
239   if (! do_disable_creation_time)
240     GNUNET_CONTAINER_meta_data_add_publication_date (meta);
241   if (NULL != topKeywords)
242     {
243       new_uri = GNUNET_FS_uri_ksk_merge (topKeywords,
244                                          *uri);
245       GNUNET_FS_uri_destroy (*uri);
246       *uri = new_uri;
247       GNUNET_FS_uri_destroy (topKeywords);
248       topKeywords = NULL;
249     }
250   if (NULL != meta)
251     {
252       GNUNET_CONTAINER_meta_data_iterate (meta,
253                                           &meta_merger,
254                                           m);
255       GNUNET_CONTAINER_meta_data_destroy (meta);
256       meta = NULL;
257     }
258   if (extract_only)
259     {
260       fn = GNUNET_CONTAINER_meta_data_get_by_type (meta,
261                                                    EXTRACTOR_METATYPE_FILENAME);
262       fs = GNUNET_STRINGS_byte_size_fancy (length);
263       fprintf (stdout,
264                _("Keywords for file `%s' (%s)\n"),
265                fn,
266                fs);
267       GNUNET_free (fn);
268       GNUNET_free (fs);
269       GNUNET_CONTAINER_meta_data_iterate (meta,
270                                           &meta_printer,
271                                           NULL);
272       fprintf (stdout, "\n");
273     }
274   if (GNUNET_FS_meta_data_test_for_directory (meta))
275     GNUNET_FS_file_information_inspect (fi,
276                                         &publish_inspector,
277                                         NULL);
278   return GNUNET_OK;
279 }
280
281
282 /**
283  * Main function that will be run by the scheduler.
284  *
285  * @param cls closure
286  * @param sched the scheduler to use
287  * @param args remaining command-line arguments
288  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
289  * @param c configuration
290  */
291 static void
292 run (void *cls,
293      struct GNUNET_SCHEDULER_Handle *sched,
294      char *const *args,
295      const char *cfgfile,
296      const struct GNUNET_CONFIGURATION_Handle *c)
297 {
298   struct GNUNET_FS_FileInformation *fi;
299   struct GNUNET_FS_Namespace *namespace;
300   struct EXTRACTOR_PluginList *l;
301   char *ex;
302   char *emsg;
303   
304   /* check arguments */
305   if ( ( (uri_string == NULL) || (extract_only) ) 
306        && ( (args[0] == NULL) || (args[1] != NULL) ) )
307     {
308       printf (_
309               ("You must specify one and only one filename for insertion.\n"));
310       ret = -1;
311       return;
312     }
313   if ((uri_string != NULL) && (args[0] != NULL))
314     {
315       printf (_("You must NOT specify an URI and a filename.\n"));
316       ret = -1;
317       return;
318     }
319   if ((uri_string != NULL) && (extract_only))
320     {
321       printf (_("Cannot extract metadata from a URI!\n"));
322       ret = -1;
323       return;
324     }
325   if (pseudonym != NULL)
326     {
327       if (NULL == this_id)
328         {
329           fprintf (stderr,
330                    _("Option `%s' is required when using option `%s'.\n"),
331                    "-t", "-P");
332           ret = -1;
333           return;
334         }
335     }
336   else
337     {                           /* ordinary insertion checks */
338       if (NULL != next_id)
339         {
340           fprintf (stderr,
341                    _("Option `%s' makes no sense without option `%s'.\n"),
342                    "-N", "-P");
343           ret = -1;
344           return;
345         }
346       if (NULL != this_id)
347         {
348           fprintf (stderr,
349                    _("Option `%s' makes no sense without option `%s'.\n"),
350                    "-t", "-P");
351           ret = -1;
352           return;
353         }
354     }
355   if (args[0] == NULL)
356     {
357       fprintf (stderr,
358                _("Need the name of a file to publish!\n"));
359       ret = 1;
360       return;
361     }
362   cfg = c;
363   ctx = GNUNET_FS_start (sched,
364                          cfg,
365                          "gnunet-publish",
366                          &progress_cb,
367                          NULL,
368                          GNUNET_FS_FLAGS_NONE,
369                          GNUNET_FS_OPTIONS_END);
370   if (NULL == ctx)
371     {
372       fprintf (stderr,
373                _("Could not initialize `%s' subsystem.\n"),
374                "FS");
375       ret = 1;
376       return;
377     }
378   namespace = NULL;
379   if (NULL != pseudonym)
380     {
381       namespace = GNUNET_FS_namespace_create (ctx,
382                                               pseudonym);
383       if (NULL == namespace)
384         {
385           fprintf (stderr,
386                    _("Could not create namespace `%s'\n"),
387                    pseudonym);
388           GNUNET_FS_stop (ctx);
389           ret = 1;
390           return;
391         }
392     }
393   if (NULL != uri_string)
394     {
395       // FIXME -- implement!
396       return;
397     }
398
399   l = NULL;
400   if (! disable_extractor)
401     {
402       l = EXTRACTOR_plugin_add_defaults (EXTRACTOR_OPTION_DEFAULT_POLICY);
403       if (GNUNET_OK ==
404           GNUNET_CONFIGURATION_get_value_string (cfg, "FS", "EXTRACTORS",
405                                                  &ex))
406         {
407           if (strlen (ex) > 0)
408             l = EXTRACTOR_plugin_add_config (l, ex, EXTRACTOR_OPTION_DEFAULT_POLICY);
409           GNUNET_free (ex);
410         }
411     }
412   fi = GNUNET_FS_file_information_create_from_directory (NULL,
413                                                          args[0],
414                                                          &GNUNET_FS_directory_scanner_default,
415                                                          l,
416                                                          !do_insert,
417                                                          anonymity,
418                                                          priority,
419                                                          GNUNET_TIME_relative_to_absolute (DEFAULT_EXPIRATION),
420                                                          &emsg);
421   EXTRACTOR_plugin_remove_all (l);  
422   if (fi == NULL)
423     {
424       fprintf (stderr,
425                _("Could not publish `%s': %s\n"),
426                args[0],
427                emsg);
428       GNUNET_free (emsg);
429       if (namespace != NULL)
430         GNUNET_FS_namespace_delete (namespace, GNUNET_NO);
431       GNUNET_FS_stop (ctx);
432       ret = 1;
433       return;
434     }
435   GNUNET_FS_file_information_inspect (fi,
436                                       &publish_inspector,
437                                       NULL);
438   if (extract_only)
439     {
440       if (namespace != NULL)
441         GNUNET_FS_namespace_delete (namespace, GNUNET_NO);
442       GNUNET_FS_file_information_destroy (fi, NULL, NULL);
443       GNUNET_FS_stop (ctx);
444       return;
445     }
446   pc = GNUNET_FS_publish_start (ctx,
447                                 fi,
448                                 namespace,
449                                 this_id,
450                                 next_id,
451                                 (do_simulate) 
452                                 ? GNUNET_FS_PUBLISH_OPTION_SIMULATE_ONLY
453                                 : GNUNET_FS_PUBLISH_OPTION_NONE);
454   if (NULL == pc)
455     {
456       fprintf (stderr,
457                _("Could not start publishing.\n"));
458       GNUNET_FS_stop (ctx);
459       ret = 1;
460       return;
461     }
462 }
463
464
465 /**
466  * gnunet-publish command line options
467  */
468 static struct GNUNET_GETOPT_CommandLineOption options[] = {
469   {'a', "anonymity", "LEVEL",
470    gettext_noop ("set the desired LEVEL of sender-anonymity"),
471    1, &GNUNET_GETOPT_set_uint, &anonymity},
472   {'d', "disable-creation-time", NULL,
473    gettext_noop
474    ("disable adding the creation time to the metadata of the uploaded file"),
475    0, &GNUNET_GETOPT_set_one, &do_disable_creation_time},
476   {'D', "disable-extractor", NULL,
477    gettext_noop
478    ("do not use libextractor to add keywords or metadata"),
479    0, &GNUNET_GETOPT_set_one, &disable_extractor},
480   {'e', "extract", NULL,
481    gettext_noop
482    ("print list of extracted keywords that would be used, but do not perform upload"),
483    0, &GNUNET_GETOPT_set_one, &extract_only},
484   {'k', "key", "KEYWORD",
485    gettext_noop
486    ("add an additional keyword for the top-level file or directory"
487     " (this option can be specified multiple times)"),
488    1, &GNUNET_FS_getopt_set_keywords, &topKeywords},
489   // *: option not yet used... (can handle in a pass over FI)
490   {'m', "meta", "TYPE:VALUE",
491    gettext_noop ("set the meta-data for the given TYPE to the given VALUE"),
492    1, &GNUNET_FS_getopt_set_metadata, &meta},
493   {'n', "noindex", NULL,
494    gettext_noop ("do not index, perform full insertion (stores entire "
495                  "file in encrypted form in GNUnet database)"),
496    0, &GNUNET_GETOPT_set_one, &do_insert},
497   {'N', "next", "ID",
498    gettext_noop
499    ("specify ID of an updated version to be published in the future"
500     " (for namespace insertions only)"),
501    1, &GNUNET_GETOPT_set_string, &next_id},
502   {'p', "priority", "PRIORITY",
503    gettext_noop ("specify the priority of the content"),
504    1, &GNUNET_GETOPT_set_uint, &priority},
505   {'P', "pseudonym", "NAME",
506    gettext_noop
507    ("publish the files under the pseudonym NAME (place file into namespace)"),
508    1, &GNUNET_GETOPT_set_string, &pseudonym},
509   // *: option not yet used... (need FS API support!)
510   {'s', "simulate-only", NULL,
511    gettext_noop ("only simulate the process but do not do any "
512                  "actual publishing (useful to compute URIs)"),
513    0, &GNUNET_GETOPT_set_one, &do_simulate},
514   {'t', "this", "ID",
515    gettext_noop ("set the ID of this version of the publication"
516                  " (for namespace insertions only)"),
517    1, &GNUNET_GETOPT_set_string, &this_id},
518   // *: option not yet used... (need FS API support!)
519   {'u', "uri", "URI",
520    gettext_noop ("URI to be published (can be used instead of passing a "
521                  "file to add keywords to the file with the respective URI)"),
522    1, &GNUNET_GETOPT_set_string, &uri_string}, 
523   {'V', "verbose", NULL,
524    gettext_noop ("be verbose (print progress information)"),
525    0, &GNUNET_GETOPT_set_one, &verbose},
526   GNUNET_GETOPT_OPTION_END
527 };
528
529
530 /**
531  * The main function to publish content to GNUnet.
532  *
533  * @param argc number of arguments from the command line
534  * @param argv command line arguments
535  * @return 0 ok, 1 on error
536  */
537 int
538 main (int argc, char *const *argv)
539 {
540   return (GNUNET_OK ==
541           GNUNET_PROGRAM_run (argc,
542                               argv,
543                               "gnunet-publish",
544                               gettext_noop
545                               ("Publish files on GNUnet."),
546                               options, &run, NULL)) ? ret : 1;
547 }
548
549 /* end of gnunet-publish.c */
550
551 ////////////////////////////////////////////////////////////////
552
553 #if 0
554 /**
555  * Print progess message.
556  */
557 static void *
558 printstatus (void *ctx, const GNUNET_FSUI_Event * event)
559 {
560   unsigned long long delta;
561   char *fstring;
562
563   switch (event->type)
564     {
565     case GNUNET_FSUI_upload_progress:
566       if (*verboselevel)
567         {
568           char *ret;
569           GNUNET_CronTime now;
570
571           now = GNUNET_get_time ();
572           delta = event->data.UploadProgress.eta - now;
573           if (event->data.UploadProgress.eta < now)
574             delta = 0;
575           ret = GNUNET_get_time_interval_as_fancy_string (delta);
576           PRINTF (_("%16llu of %16llu bytes inserted "
577                     "(estimating %6s to completion) - %s\n"),
578                   event->data.UploadProgress.completed,
579                   event->data.UploadProgress.total,
580                   ret, event->data.UploadProgress.filename);
581           GNUNET_free (ret);
582         }
583       break;
584     case GNUNET_FSUI_upload_completed:
585       if (*verboselevel)
586         {
587           delta = GNUNET_get_time () - start_time;
588           PRINTF (_("Upload of `%s' complete, "
589                     "%llu bytes took %llu seconds (%8.3f KiB/s).\n"),
590                   event->data.UploadCompleted.filename,
591                   event->data.UploadCompleted.total,
592                   delta / GNUNET_CRON_SECONDS,
593                   (delta == 0)
594                   ? (double) (-1.0)
595                   : (double) (event->data.UploadCompleted.total
596                               / 1024.0 * GNUNET_CRON_SECONDS / delta));
597         }
598       fstring = GNUNET_ECRS_uri_to_string (event->data.UploadCompleted.uri);
599       printf (_("File `%s' has URI: %s\n"),
600               event->data.UploadCompleted.filename, fstring);
601       GNUNET_free (fstring);
602       if (ul == event->data.UploadCompleted.uc.pos)
603         {
604           postProcess (event->data.UploadCompleted.uri);
605           errorCode = 0;
606           GNUNET_shutdown_initiate ();
607         }
608       break;
609     case GNUNET_FSUI_upload_aborted:
610       printf (_("\nUpload aborted.\n"));
611       errorCode = 2;
612       GNUNET_shutdown_initiate ();
613       break;
614     case GNUNET_FSUI_upload_error:
615       printf (_("\nError uploading file: %s"),
616               event->data.UploadError.message);
617       errorCode = 3;
618       GNUNET_shutdown_initiate ();
619       break;
620     case GNUNET_FSUI_upload_started:
621     case GNUNET_FSUI_upload_stopped:
622       break;
623     default:
624       printf (_("\nUnexpected event: %d\n"), event->type);
625       GNUNET_GE_BREAK (ectx, 0);
626       break;
627     }
628   return NULL;
629 }
630 #endif
631
632 /* end of gnunet-publish.c */