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