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