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