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