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