fixing gnunet-publish for files
[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     GNUNET_asprintf (&emsg,
445                      _("Could not access file: %s\n"),
446                      STRERROR (errno));
447   else if (S_ISDIR (sbuf.st_mode))
448     fi = GNUNET_FS_file_information_create_from_directory (NULL,
449                                                            args[0],
450                                                            &GNUNET_FS_directory_scanner_default,
451                                                            l,
452                                                            !do_insert,
453                                                            anonymity,
454                                                            priority,
455                                                            GNUNET_TIME_relative_to_absolute (DEFAULT_EXPIRATION),
456                                                            &emsg);
457   else
458     {
459       fi = GNUNET_FS_file_information_create_from_file (NULL,
460                                                         args[0],
461                                                         NULL,
462                                                         NULL,
463                                                         !do_insert,
464                                                         anonymity,
465                                                         priority,
466                                                         GNUNET_TIME_relative_to_absolute (DEFAULT_EXPIRATION));
467       GNUNET_break (fi != NULL);
468     }
469   EXTRACTOR_plugin_remove_all (l);  
470   if (fi == NULL)
471     {
472       fprintf (stderr,
473                _("Could not publish `%s': %s\n"),
474                args[0],
475                emsg);
476       GNUNET_free (emsg);
477       if (namespace != NULL)
478         GNUNET_FS_namespace_delete (namespace, GNUNET_NO);
479       GNUNET_FS_stop (ctx);
480       ret = 1;
481       return;
482     }
483   GNUNET_FS_file_information_inspect (fi,
484                                       &publish_inspector,
485                                       NULL);
486   if (extract_only)
487     {
488       if (namespace != NULL)
489         GNUNET_FS_namespace_delete (namespace, GNUNET_NO);
490       GNUNET_FS_file_information_destroy (fi, NULL, NULL);
491       GNUNET_FS_stop (ctx);
492       return;
493     }
494   pc = GNUNET_FS_publish_start (ctx,
495                                 fi,
496                                 namespace,
497                                 this_id,
498                                 next_id,
499                                 (do_simulate) 
500                                 ? GNUNET_FS_PUBLISH_OPTION_SIMULATE_ONLY
501                                 : GNUNET_FS_PUBLISH_OPTION_NONE);
502   if (NULL == pc)
503     {
504       fprintf (stderr,
505                _("Could not start publishing.\n"));
506       GNUNET_FS_stop (ctx);
507       ret = 1;
508       return;
509     }
510 }
511
512
513 /**
514  * gnunet-publish command line options
515  */
516 static struct GNUNET_GETOPT_CommandLineOption options[] = {
517   {'a', "anonymity", "LEVEL",
518    gettext_noop ("set the desired LEVEL of sender-anonymity"),
519    1, &GNUNET_GETOPT_set_uint, &anonymity},
520   {'d', "disable-creation-time", NULL,
521    gettext_noop
522    ("disable adding the creation time to the metadata of the uploaded file"),
523    0, &GNUNET_GETOPT_set_one, &do_disable_creation_time},
524   {'D', "disable-extractor", NULL,
525    gettext_noop
526    ("do not use libextractor to add keywords or metadata"),
527    0, &GNUNET_GETOPT_set_one, &disable_extractor},
528   {'e', "extract", NULL,
529    gettext_noop
530    ("print list of extracted keywords that would be used, but do not perform upload"),
531    0, &GNUNET_GETOPT_set_one, &extract_only},
532   {'k', "key", "KEYWORD",
533    gettext_noop
534    ("add an additional keyword for the top-level file or directory"
535     " (this option can be specified multiple times)"),
536    1, &GNUNET_FS_getopt_set_keywords, &topKeywords},
537   // *: option not yet used... (can handle in a pass over FI)
538   {'m', "meta", "TYPE:VALUE",
539    gettext_noop ("set the meta-data for the given TYPE to the given VALUE"),
540    1, &GNUNET_FS_getopt_set_metadata, &meta},
541   {'n', "noindex", NULL,
542    gettext_noop ("do not index, perform full insertion (stores entire "
543                  "file in encrypted form in GNUnet database)"),
544    0, &GNUNET_GETOPT_set_one, &do_insert},
545   {'N', "next", "ID",
546    gettext_noop
547    ("specify ID of an updated version to be published in the future"
548     " (for namespace insertions only)"),
549    1, &GNUNET_GETOPT_set_string, &next_id},
550   {'p', "priority", "PRIORITY",
551    gettext_noop ("specify the priority of the content"),
552    1, &GNUNET_GETOPT_set_uint, &priority},
553   {'P', "pseudonym", "NAME",
554    gettext_noop
555    ("publish the files under the pseudonym NAME (place file into namespace)"),
556    1, &GNUNET_GETOPT_set_string, &pseudonym},
557   // *: option not yet used... (need FS API support!)
558   {'s', "simulate-only", NULL,
559    gettext_noop ("only simulate the process but do not do any "
560                  "actual publishing (useful to compute URIs)"),
561    0, &GNUNET_GETOPT_set_one, &do_simulate},
562   {'t', "this", "ID",
563    gettext_noop ("set the ID of this version of the publication"
564                  " (for namespace insertions only)"),
565    1, &GNUNET_GETOPT_set_string, &this_id},
566   // *: option not yet used... (need FS API support!)
567   {'u', "uri", "URI",
568    gettext_noop ("URI to be published (can be used instead of passing a "
569                  "file to add keywords to the file with the respective URI)"),
570    1, &GNUNET_GETOPT_set_string, &uri_string}, 
571   {'V', "verbose", NULL,
572    gettext_noop ("be verbose (print progress information)"),
573    0, &GNUNET_GETOPT_set_one, &verbose},
574   GNUNET_GETOPT_OPTION_END
575 };
576
577
578 /**
579  * The main function to publish content to GNUnet.
580  *
581  * @param argc number of arguments from the command line
582  * @param argv command line arguments
583  * @return 0 ok, 1 on error
584  */
585 int
586 main (int argc, char *const *argv)
587 {
588   return (GNUNET_OK ==
589           GNUNET_PROGRAM_run (argc,
590                               argv,
591                               "gnunet-publish",
592                               gettext_noop
593                               ("Publish files on GNUnet."),
594                               options, &run, NULL)) ? ret : 1;
595 }
596
597 /* end of gnunet-publish.c */
598
599 ////////////////////////////////////////////////////////////////
600
601 #if 0
602 /**
603  * Print progess message.
604  */
605 static void *
606 printstatus (void *ctx, const GNUNET_FSUI_Event * event)
607 {
608   unsigned long long delta;
609   char *fstring;
610
611   switch (event->type)
612     {
613     case GNUNET_FSUI_upload_progress:
614       if (*verboselevel)
615         {
616           char *ret;
617           GNUNET_CronTime now;
618
619           now = GNUNET_get_time ();
620           delta = event->data.UploadProgress.eta - now;
621           if (event->data.UploadProgress.eta < now)
622             delta = 0;
623           ret = GNUNET_get_time_interval_as_fancy_string (delta);
624           PRINTF (_("%16llu of %16llu bytes inserted "
625                     "(estimating %6s to completion) - %s\n"),
626                   event->data.UploadProgress.completed,
627                   event->data.UploadProgress.total,
628                   ret, event->data.UploadProgress.filename);
629           GNUNET_free (ret);
630         }
631       break;
632     case GNUNET_FSUI_upload_completed:
633       if (*verboselevel)
634         {
635           delta = GNUNET_get_time () - start_time;
636           PRINTF (_("Upload of `%s' complete, "
637                     "%llu bytes took %llu seconds (%8.3f KiB/s).\n"),
638                   event->data.UploadCompleted.filename,
639                   event->data.UploadCompleted.total,
640                   delta / GNUNET_CRON_SECONDS,
641                   (delta == 0)
642                   ? (double) (-1.0)
643                   : (double) (event->data.UploadCompleted.total
644                               / 1024.0 * GNUNET_CRON_SECONDS / delta));
645         }
646       fstring = GNUNET_ECRS_uri_to_string (event->data.UploadCompleted.uri);
647       printf (_("File `%s' has URI: %s\n"),
648               event->data.UploadCompleted.filename, fstring);
649       GNUNET_free (fstring);
650       if (ul == event->data.UploadCompleted.uc.pos)
651         {
652           postProcess (event->data.UploadCompleted.uri);
653           errorCode = 0;
654           GNUNET_shutdown_initiate ();
655         }
656       break;
657     case GNUNET_FSUI_upload_aborted:
658       printf (_("\nUpload aborted.\n"));
659       errorCode = 2;
660       GNUNET_shutdown_initiate ();
661       break;
662     case GNUNET_FSUI_upload_error:
663       printf (_("\nError uploading file: %s"),
664               event->data.UploadError.message);
665       errorCode = 3;
666       GNUNET_shutdown_initiate ();
667       break;
668     case GNUNET_FSUI_upload_started:
669     case GNUNET_FSUI_upload_stopped:
670       break;
671     default:
672       printf (_("\nUnexpected event: %d\n"), event->type);
673       GNUNET_GE_BREAK (ectx, 0);
674       break;
675     }
676   return NULL;
677 }
678 #endif
679
680 /* end of gnunet-publish.c */