making GNUNET_SCHEDULER_cancel() perform in O(1) instead of O(n) to help or even...
[oweals/gnunet.git] / src / fs / gnunet-publish.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001-2013 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 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20 /**
21  * @file fs/gnunet-publish.c
22  * @brief publishing files on GNUnet
23  * @author Christian Grothoff
24  * @author Krista Bennett
25  * @author James Blackwell
26  * @author Igor Wronsky
27  */
28 #include "platform.h"
29 #include "gnunet_fs_service.h"
30 #include "gnunet_identity_service.h"
31
32 /**
33  * Global return value from 'main'.
34  */
35 static int ret = 1;
36
37 /**
38  * Command line option 'verbose' set
39  */
40 static int verbose;
41
42 /**
43  * Handle to our configuration.
44  */
45 static const struct GNUNET_CONFIGURATION_Handle *cfg;
46
47 /**
48  * Handle for interaction with file-sharing service.
49  */
50 static struct GNUNET_FS_Handle *ctx;
51
52 /**
53  * Handle to FS-publishing operation.
54  */
55 static struct GNUNET_FS_PublishContext *pc;
56
57 /**
58  * Meta-data provided via command-line option.
59  */
60 static struct GNUNET_CONTAINER_MetaData *meta;
61
62 /**
63  * Keywords provided via command-line option.
64  */
65 static struct GNUNET_FS_Uri *topKeywords;
66
67 /**
68  * Options we set for published blocks.
69  */
70 static struct GNUNET_FS_BlockOptions bo = { {0LL}, 1, 365, 1 };
71
72 /**
73  * Value of URI provided on command-line (when not publishing
74  * a file but just creating UBlocks to refer to an existing URI).
75  */
76 static char *uri_string;
77
78 /**
79  * Value of URI provided on command-line (when not publishing
80  * a file but just creating UBlocks to refer to an existing URI);
81  * parsed version of 'uri_string'.
82  */
83 static struct GNUNET_FS_Uri *uri;
84
85 /**
86  * Command-line option for namespace publishing: identifier for updates
87  * to this publication.
88  */
89 static char *next_id;
90
91 /**
92  * Command-line option for namespace publishing: identifier for this
93  * publication.
94  */
95 static char *this_id;
96
97 /**
98  * Command-line option identifying the pseudonym to use for the publication.
99  */
100 static char *pseudonym;
101
102 /**
103  * Command-line option for 'inserting'
104  */
105 static int do_insert;
106
107 /**
108  * Command-line option to disable meta data extraction.
109  */
110 static int disable_extractor;
111
112 /**
113  * Command-line option to merely simulate publishing operation.
114  */
115 static int do_simulate;
116
117 /**
118  * Command-line option to only perform meta data extraction, but not publish.
119  */
120 static int extract_only;
121
122 /**
123  * Command-line option to disable adding creation time.
124  */
125 static int do_disable_creation_time;
126
127 /**
128  * Task run on CTRL-C to kill everything nicely.
129  */
130 static struct GNUNET_SCHEDULER_Task * kill_task;
131
132 /**
133  * Handle to the directory scanner (for recursive insertions).
134  */
135 static struct GNUNET_FS_DirScanner *ds;
136
137 /**
138  * Which namespace do we publish to? NULL if we do not publish to
139  * a namespace.
140  */
141 static struct GNUNET_IDENTITY_Ego *namespace;
142
143 /**
144  * Handle to identity service.
145  */
146 static struct GNUNET_IDENTITY_Handle *identity;
147
148
149 /**
150  * We are finished with the publishing operation, clean up all
151  * FS state.
152  *
153  * @param cls NULL
154  * @param tc scheduler context
155  */
156 static void
157 do_stop_task (void *cls,
158               const struct GNUNET_SCHEDULER_TaskContext *tc)
159 {
160   struct GNUNET_FS_PublishContext *p;
161
162   kill_task = NULL;
163   if (NULL != identity)
164   {
165     GNUNET_IDENTITY_disconnect (identity);
166     identity = NULL;
167   }
168   if (NULL != pc)
169   {
170     p = pc;
171     pc = NULL;
172     GNUNET_FS_publish_stop (p);
173   }
174   if (NULL != meta)
175   {
176     GNUNET_CONTAINER_meta_data_destroy (meta);
177     meta = NULL;
178   }
179 }
180
181
182 /**
183  * Stop the directory scanner (we had an error).
184  *
185  * @param cls closure
186  * @param tc scheduler context
187  */
188 static void
189 stop_scanner_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
190 {
191   kill_task = NULL;
192   if (NULL != ds)
193   {
194     GNUNET_FS_directory_scan_abort (ds);
195     ds = NULL;
196   }
197   if (NULL != identity)
198   {
199     GNUNET_IDENTITY_disconnect (identity);
200     identity = NULL;
201   }
202   GNUNET_FS_stop (ctx);
203   ctx = NULL;
204   ret = 1;
205 }
206
207
208 /**
209  * Called by FS client to give information about the progress of an
210  * operation.
211  *
212  * @param cls closure
213  * @param info details about the event, specifying the event type
214  *        and various bits about the event
215  * @return client-context (for the next progress call
216  *         for this operation; should be set to NULL for
217  *         SUSPEND and STOPPED events).  The value returned
218  *         will be passed to future callbacks in the respective
219  *         field in the GNUNET_FS_ProgressInfo struct.
220  */
221 static void *
222 progress_cb (void *cls,
223              const struct GNUNET_FS_ProgressInfo *info)
224 {
225   const char *s;
226   char *suri;
227
228   switch (info->status)
229   {
230   case GNUNET_FS_STATUS_PUBLISH_START:
231     break;
232   case GNUNET_FS_STATUS_PUBLISH_PROGRESS:
233     if (verbose)
234     {
235       s = GNUNET_STRINGS_relative_time_to_string (info->value.publish.eta,
236                                                   GNUNET_YES);
237       FPRINTF (stdout,
238                _("Publishing `%s' at %llu/%llu (%s remaining)\n"),
239                info->value.publish.filename,
240                (unsigned long long) info->value.publish.completed,
241                (unsigned long long) info->value.publish.size, s);
242     }
243     break;
244   case GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY:
245     if (verbose)
246     {
247       s = GNUNET_STRINGS_relative_time_to_string (info->value.publish.specifics.progress_directory.eta,
248                                                   GNUNET_YES);
249       FPRINTF (stdout,
250                _("Publishing `%s' at %llu/%llu (%s remaining)\n"),
251                info->value.publish.filename,
252                (unsigned long long) info->value.publish.specifics.progress_directory.completed,
253                (unsigned long long) info->value.publish.specifics.progress_directory.total, s);
254     }
255     break;
256   case GNUNET_FS_STATUS_PUBLISH_ERROR:
257     FPRINTF (stderr, _("Error publishing: %s.\n"),
258              info->value.publish.specifics.error.message);
259     if (kill_task != NULL)
260     {
261       GNUNET_SCHEDULER_cancel (kill_task);
262       kill_task = NULL;
263     }
264     kill_task = GNUNET_SCHEDULER_add_now (&do_stop_task, NULL);
265     break;
266   case GNUNET_FS_STATUS_PUBLISH_COMPLETED:
267     FPRINTF (stdout,
268              _("Publishing `%s' done.\n"),
269              info->value.publish.filename);
270     suri = GNUNET_FS_uri_to_string (info->value.publish.specifics.
271                                     completed.chk_uri);
272     FPRINTF (stdout,
273              _("URI is `%s'.\n"),
274              suri);
275     GNUNET_free (suri);
276     if (NULL != info->value.publish.specifics.completed.sks_uri)
277     {
278       suri = GNUNET_FS_uri_to_string (info->value.publish.specifics.
279                                       completed.sks_uri);
280       FPRINTF (stdout,
281                _("Namespace URI is `%s'.\n"),
282                suri);
283       GNUNET_free (suri);
284     }
285     if (NULL == info->value.publish.pctx)
286     {
287       if (NULL != kill_task)
288         GNUNET_SCHEDULER_cancel (kill_task);
289       kill_task = GNUNET_SCHEDULER_add_now (&do_stop_task, NULL);
290     }
291     ret = 0;
292     break;
293   case GNUNET_FS_STATUS_PUBLISH_STOPPED:
294     GNUNET_break (NULL == pc);
295     return NULL;
296   case GNUNET_FS_STATUS_UNINDEX_PROGRESS:
297     return NULL;
298   case GNUNET_FS_STATUS_UNINDEX_COMPLETED:
299     FPRINTF (stderr,
300              "%s",
301              _("Cleanup after abort complete.\n"));
302     return NULL;
303   default:
304     FPRINTF (stderr, _("Unexpected status: %d\n"), info->status);
305     return NULL;
306   }
307   return "";                    /* non-null */
308 }
309
310
311 /**
312  * Print metadata entries (except binary
313  * metadata and the filename).
314  *
315  * @param cls closure
316  * @param plugin_name name of the plugin that generated the meta data
317  * @param type type of the meta data
318  * @param format format of data
319  * @param data_mime_type mime type of data
320  * @param data value of the meta data
321  * @param data_size number of bytes in @a data
322  * @return always 0
323  */
324 static int
325 meta_printer (void *cls,
326               const char *plugin_name,
327               enum EXTRACTOR_MetaType type,
328               enum EXTRACTOR_MetaFormat format,
329               const char *data_mime_type,
330               const char *data, size_t data_size)
331 {
332   if ((EXTRACTOR_METAFORMAT_UTF8 != format) &&
333       (EXTRACTOR_METAFORMAT_C_STRING != format))
334     return 0;
335   if (EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME == type)
336     return 0;
337   FPRINTF (stdout, "\t%s - %s\n", EXTRACTOR_metatype_to_string (type), data);
338   return 0;
339 }
340
341
342 /**
343  * Iterator printing keywords
344  *
345  * @param cls closure
346  * @param keyword the keyword
347  * @param is_mandatory is the keyword mandatory (in a search)
348  * @return #GNUNET_OK to continue to iterate, #GNUNET_SYSERR to abort
349  */
350 static int
351 keyword_printer (void *cls,
352                  const char *keyword,
353                  int is_mandatory)
354 {
355   FPRINTF (stdout, "\t%s\n", keyword);
356   return GNUNET_OK;
357 }
358
359
360 /**
361  * Function called on all entries before the publication.  This is
362  * where we perform modifications to the default based on command-line
363  * options.
364  *
365  * @param cls closure
366  * @param fi the entry in the publish-structure
367  * @param length length of the file or directory
368  * @param m metadata for the file or directory (can be modified)
369  * @param uri pointer to the keywords that will be used for this entry (can be modified)
370  * @param bo block options
371  * @param do_index should we index?
372  * @param client_info pointer to client context set upon creation (can be modified)
373  * @return #GNUNET_OK to continue, #GNUNET_NO to remove
374  *         this entry from the directory, #GNUNET_SYSERR
375  *         to abort the iteration
376  */
377 static int
378 publish_inspector (void *cls,
379                    struct GNUNET_FS_FileInformation *fi,
380                    uint64_t length,
381                    struct GNUNET_CONTAINER_MetaData *m,
382                    struct GNUNET_FS_Uri **uri,
383                    struct GNUNET_FS_BlockOptions *bo,
384                    int *do_index,
385                    void **client_info)
386 {
387   char *fn;
388   char *fs;
389   struct GNUNET_FS_Uri *new_uri;
390
391   if (cls == fi)
392     return GNUNET_OK;
393   if ( (disable_extractor) &&
394        (NULL != *uri) )
395   {
396     GNUNET_FS_uri_destroy (*uri);
397     *uri = NULL;
398   }
399   if (NULL != topKeywords)
400   {
401     if (NULL != *uri)
402     {
403       new_uri = GNUNET_FS_uri_ksk_merge (topKeywords, *uri);
404       GNUNET_FS_uri_destroy (*uri);
405       *uri = new_uri;
406       GNUNET_FS_uri_destroy (topKeywords);
407     }
408     else
409     {
410       *uri = topKeywords;
411     }
412     topKeywords = NULL;
413   }
414   if (NULL != meta)
415   {
416     GNUNET_CONTAINER_meta_data_merge (m, meta);
417     GNUNET_CONTAINER_meta_data_destroy (meta);
418     meta = NULL;
419   }
420   if (!do_disable_creation_time)
421     GNUNET_CONTAINER_meta_data_add_publication_date (m);
422   if (extract_only)
423   {
424     fn = GNUNET_CONTAINER_meta_data_get_by_type (m,
425                                                  EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME);
426     fs = GNUNET_STRINGS_byte_size_fancy (length);
427     FPRINTF (stdout, _("Meta data for file `%s' (%s)\n"), fn, fs);
428     GNUNET_CONTAINER_meta_data_iterate (m, &meta_printer, NULL);
429     FPRINTF (stdout, _("Keywords for file `%s' (%s)\n"), fn, fs);
430     GNUNET_free (fn);
431     GNUNET_free (fs);
432     if (NULL != *uri)
433       GNUNET_FS_uri_ksk_get_keywords (*uri, &keyword_printer, NULL);
434     FPRINTF (stdout, "%s",  "\n");
435   }
436   if (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (m))
437     GNUNET_FS_file_information_inspect (fi, &publish_inspector, fi);
438   return GNUNET_OK;
439 }
440
441
442 /**
443  * Function called upon completion of the publishing
444  * of the UBLOCK for the SKS URI.  As this is the last
445  * step, stop our interaction with FS (clean up).
446  *
447  * @param cls NULL (closure)
448  * @param sks_uri URI for the block that was published
449  * @param emsg error message, NULL on success
450  */
451 static void
452 uri_sks_continuation (void *cls,
453                       const struct GNUNET_FS_Uri *sks_uri,
454                       const char *emsg)
455 {
456   if (NULL != emsg)
457   {
458     FPRINTF (stderr, "%s\n", emsg);
459     ret = 1;
460   }
461   GNUNET_FS_uri_destroy (uri);
462   uri = NULL;
463   GNUNET_FS_stop (ctx);
464   ctx = NULL;
465 }
466
467
468 /**
469  * Function called upon completion of the publishing
470  * of the UBLOCK for the KSK URI.  Continue with
471  * publishing the SKS URI (if applicable) or clean up.
472  *
473  * @param cls NULL (closure)
474  * @param ksk_uri URI for the block that was published
475  * @param emsg error message, NULL on success
476  */
477 static void
478 uri_ksk_continuation (void *cls,
479                       const struct GNUNET_FS_Uri *ksk_uri,
480                       const char *emsg)
481 {
482   const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv;
483
484   if (NULL != emsg)
485   {
486     FPRINTF (stderr, "%s\n", emsg);
487     ret = 1;
488   }
489   if (NULL != namespace)
490   {
491     priv = GNUNET_IDENTITY_ego_get_private_key (namespace);
492     GNUNET_FS_publish_sks (ctx, priv, this_id, next_id, meta, uri, &bo,
493                            GNUNET_FS_PUBLISH_OPTION_NONE,
494                            &uri_sks_continuation, NULL);
495     return;
496   }
497   GNUNET_FS_uri_destroy (uri);
498   uri = NULL;
499   GNUNET_FS_stop (ctx);
500   ctx = NULL;
501 }
502
503
504 /**
505  * Iterate over the results from the directory scan and extract
506  * the desired information for the publishing operation.
507  *
508  * @param item root with the data from the directroy scan
509  * @return handle with the information for the publishing operation
510  */
511 static struct GNUNET_FS_FileInformation *
512 get_file_information (struct GNUNET_FS_ShareTreeItem *item)
513 {
514   struct GNUNET_FS_FileInformation *fi;
515   struct GNUNET_FS_FileInformation *fic;
516   struct GNUNET_FS_ShareTreeItem *child;
517
518   if (GNUNET_YES == item->is_directory)
519   {
520     if (NULL == item->meta)
521       item->meta = GNUNET_CONTAINER_meta_data_create ();
522     GNUNET_CONTAINER_meta_data_delete (item->meta,
523                                        EXTRACTOR_METATYPE_MIMETYPE,
524                                        NULL, 0);
525     GNUNET_FS_meta_data_make_directory (item->meta);
526     if (NULL == item->ksk_uri)
527     {
528       const char *mime = GNUNET_FS_DIRECTORY_MIME;
529       item->ksk_uri = GNUNET_FS_uri_ksk_create_from_args (1, &mime);
530     }
531     else
532       GNUNET_FS_uri_ksk_add_keyword (item->ksk_uri, GNUNET_FS_DIRECTORY_MIME,
533                                      GNUNET_NO);
534     fi = GNUNET_FS_file_information_create_empty_directory (ctx, NULL,
535                                                             item->ksk_uri,
536                                                             item->meta,
537                                                             &bo, item->filename);
538     for (child = item->children_head; child; child = child->next)
539     {
540       fic = get_file_information (child);
541       GNUNET_break (GNUNET_OK == GNUNET_FS_file_information_add (fi, fic));
542     }
543   }
544   else
545   {
546     fi = GNUNET_FS_file_information_create_from_file (ctx, NULL,
547                                                       item->filename,
548                                                       item->ksk_uri, item->meta,
549                                                       !do_insert,
550                                                       &bo);
551   }
552   return fi;
553 }
554
555
556 /**
557  * We've finished scanning the directory and optimized the meta data.
558  * Begin the publication process.
559  *
560  * @param directory_scan_result result from the directory scan, freed in this function
561  */
562 static void
563 directory_trim_complete (struct GNUNET_FS_ShareTreeItem *directory_scan_result)
564 {
565   struct GNUNET_FS_FileInformation *fi;
566   const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv;
567
568   fi = get_file_information (directory_scan_result);
569   GNUNET_FS_share_tree_free (directory_scan_result);
570   if (NULL == fi)
571   {
572     FPRINTF (stderr,
573              "%s",
574              _("Could not publish\n"));
575     GNUNET_SCHEDULER_shutdown ();
576     ret = 1;
577     return;
578   }
579   GNUNET_FS_file_information_inspect (fi, &publish_inspector, NULL);
580   if (extract_only)
581   {
582     GNUNET_FS_file_information_destroy (fi, NULL, NULL);
583     GNUNET_SCHEDULER_shutdown ();
584     return;
585   }
586   if (NULL == namespace)
587     priv = NULL;
588   else
589     priv = GNUNET_IDENTITY_ego_get_private_key (namespace);
590   pc = GNUNET_FS_publish_start (ctx, fi,
591                                 priv, this_id, next_id,
592                                 (do_simulate) ?
593                                 GNUNET_FS_PUBLISH_OPTION_SIMULATE_ONLY :
594                                 GNUNET_FS_PUBLISH_OPTION_NONE);
595   if (NULL == pc)
596   {
597     FPRINTF (stderr,
598              "%s",
599              _("Could not start publishing.\n"));
600     GNUNET_SCHEDULER_shutdown ();
601     ret = 1;
602     return;
603   }
604 }
605
606
607 /**
608  * Function called by the directory scanner as we build the tree
609  * that we will need to publish later.
610  *
611  * @param cls closure
612  * @param filename which file we are making progress on
613  * @param is_directory #GNUNET_YES if this is a directory,
614  *                     #GNUNET_NO if this is a file
615  *                     #GNUNET_SYSERR if it is neither (or unknown)
616  * @param reason kind of progress we are making
617  */
618 static void
619 directory_scan_cb (void *cls,
620                    const char *filename,
621                    int is_directory,
622                    enum GNUNET_FS_DirScannerProgressUpdateReason reason)
623 {
624   struct GNUNET_FS_ShareTreeItem *directory_scan_result;
625
626   switch (reason)
627   {
628   case GNUNET_FS_DIRSCANNER_FILE_START:
629     if (verbose > 1)
630     {
631       if (is_directory == GNUNET_YES)
632         FPRINTF (stdout,
633                  _("Scanning directory `%s'.\n"),
634                  filename);
635       else
636         FPRINTF (stdout,
637                  _("Scanning file `%s'.\n"),
638                  filename);
639     }
640     break;
641   case GNUNET_FS_DIRSCANNER_FILE_IGNORED:
642     FPRINTF (stderr,
643              _("There was trouble processing file `%s', skipping it.\n"),
644              filename);
645     break;
646   case GNUNET_FS_DIRSCANNER_ALL_COUNTED:
647     if (verbose)
648       FPRINTF (stdout,
649                "%s",
650                _("Preprocessing complete.\n"));
651     break;
652   case GNUNET_FS_DIRSCANNER_EXTRACT_FINISHED:
653     if (verbose > 2)
654       FPRINTF (stdout,
655                _("Extracting meta data from file `%s' complete.\n"),
656                filename);
657     break;
658   case GNUNET_FS_DIRSCANNER_FINISHED:
659     if (verbose > 1)
660       FPRINTF (stdout,
661                "%s",
662                _("Meta data extraction has finished.\n"));
663     directory_scan_result = GNUNET_FS_directory_scan_get_result (ds);
664     ds = NULL;
665     GNUNET_FS_share_tree_trim (directory_scan_result);
666     directory_trim_complete (directory_scan_result);
667     break;
668   case GNUNET_FS_DIRSCANNER_INTERNAL_ERROR:
669     FPRINTF (stdout,
670              "%s",
671              _("Internal error scanning directory.\n"));
672     if (kill_task != NULL)
673     {
674       GNUNET_SCHEDULER_cancel (kill_task);
675       kill_task = NULL;
676     }
677     kill_task = GNUNET_SCHEDULER_add_now (&stop_scanner_task, NULL);
678     break;
679   default:
680     GNUNET_assert (0);
681     break;
682   }
683   fflush (stdout);
684 }
685
686
687 /**
688  * Continuation proceeding with initialization after identity subsystem
689  * has been initialized.
690  *
691  * @param args0 filename to publish
692  */
693 static void
694 identity_continuation (const char *args0)
695 {
696   char *ex;
697   char *emsg;
698
699   if ( (NULL != pseudonym) &&
700        (NULL == namespace) )
701   {
702     FPRINTF (stderr,
703              _("Selected pseudonym `%s' unknown\n"),
704              pseudonym);
705     GNUNET_SCHEDULER_shutdown ();
706     return;
707   }
708   if (NULL != uri_string)
709   {
710     emsg = NULL;
711     if (NULL == (uri = GNUNET_FS_uri_parse (uri_string, &emsg)))
712     {
713       FPRINTF (stderr,
714                _("Failed to parse URI: %s\n"),
715                emsg);
716       GNUNET_free (emsg);
717       GNUNET_SCHEDULER_shutdown ();
718       ret = 1;
719       return;
720     }
721     GNUNET_FS_publish_ksk (ctx, topKeywords,
722                            meta, uri,
723                            &bo,
724                            GNUNET_FS_PUBLISH_OPTION_NONE,
725                            &uri_ksk_continuation,
726                            NULL);
727     return;
728   }
729   if (GNUNET_OK !=
730       GNUNET_CONFIGURATION_get_value_string (cfg, "FS", "EXTRACTORS", &ex))
731     ex = NULL;
732   if (0 != ACCESS (args0, R_OK))
733   {
734     FPRINTF (stderr,
735              _("Failed to access `%s': %s\n"),
736              args0,
737              STRERROR (errno));
738     GNUNET_free_non_null (ex);
739     return;
740   }
741   ds = GNUNET_FS_directory_scan_start (args0,
742                                        disable_extractor,
743                                        ex,
744                                        &directory_scan_cb, NULL);
745   if (NULL == ds)
746   {
747     FPRINTF (stderr,
748              "%s",
749              _("Failed to start meta directory scanner.  Is gnunet-helper-publish-fs installed?\n"));
750     GNUNET_free_non_null (ex);
751     return;
752   }
753   GNUNET_free_non_null (ex);
754 }
755
756
757 /**
758  * Function called by identity service with known pseudonyms.
759  *
760  * @param cls closure with 'const char *' of filename to publish
761  * @param ego ego handle
762  * @param ctx context for application to store data for this ego
763  *                 (during the lifetime of this process, initially NULL)
764  * @param name name assigned by the user for this ego,
765  *                   NULL if the user just deleted the ego and it
766  *                   must thus no longer be used
767  */
768 static void
769 identity_cb (void *cls,
770              struct GNUNET_IDENTITY_Ego *ego,
771              void **ctx,
772              const char *name)
773 {
774   const char *args0 = cls;
775
776   if (NULL == ego)
777   {
778     identity_continuation (args0);
779     return;
780   }
781   if (NULL == name)
782     return;
783   if (0 == strcmp (name, pseudonym))
784     namespace = ego;
785 }
786
787
788 /**
789  * Main function that will be run by the scheduler.
790  *
791  * @param cls closure
792  * @param args remaining command-line arguments
793  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
794  * @param c configuration
795  */
796 static void
797 run (void *cls,
798      char *const *args,
799      const char *cfgfile,
800      const struct GNUNET_CONFIGURATION_Handle *c)
801 {
802   /* check arguments */
803   if ((NULL != uri_string) && (extract_only))
804   {
805     printf (_("Cannot extract metadata from a URI!\n"));
806     ret = -1;
807     return;
808   }
809   if (((NULL == uri_string) || (extract_only)) &&
810       ((NULL == args[0]) || (NULL != args[1])))
811   {
812     printf (_("You must specify one and only one filename for insertion.\n"));
813     ret = -1;
814     return;
815   }
816   if ((NULL != uri_string) && (NULL != args[0]))
817   {
818     printf (_("You must NOT specify an URI and a filename.\n"));
819     ret = -1;
820     return;
821   }
822   if (NULL != pseudonym)
823   {
824     if (NULL == this_id)
825     {
826       FPRINTF (stderr, _("Option `%s' is required when using option `%s'.\n"),
827                "-t", "-P");
828       ret = -1;
829       return;
830     }
831   }
832   else
833   {                             /* ordinary insertion checks */
834     if (NULL != next_id)
835     {
836       FPRINTF (stderr,
837                _("Option `%s' makes no sense without option `%s'.\n"),
838                "-N", "-P");
839       ret = -1;
840       return;
841     }
842     if (NULL != this_id)
843     {
844       FPRINTF (stderr,
845                _("Option `%s' makes no sense without option `%s'.\n"),
846                "-t", "-P");
847       ret = -1;
848       return;
849     }
850   }
851   cfg = c;
852   ctx =
853       GNUNET_FS_start (cfg, "gnunet-publish", &progress_cb, NULL,
854                        GNUNET_FS_FLAGS_NONE, GNUNET_FS_OPTIONS_END);
855   if (NULL == ctx)
856   {
857     FPRINTF (stderr,
858              _("Could not initialize `%s' subsystem.\n"),
859              "FS");
860     ret = 1;
861     return;
862   }
863   kill_task =
864     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
865                                   &do_stop_task,
866                                   NULL);
867   if (NULL != pseudonym)
868     identity = GNUNET_IDENTITY_connect (cfg,
869                                         &identity_cb,
870                                         args[0]);
871   else
872     identity_continuation (args[0]);
873 }
874
875
876 /**
877  * The main function to publish content to GNUnet.
878  *
879  * @param argc number of arguments from the command line
880  * @param argv command line arguments
881  * @return 0 ok, 1 on error
882  */
883 int
884 main (int argc, char *const *argv)
885 {
886   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
887     {'a', "anonymity", "LEVEL",
888      gettext_noop ("set the desired LEVEL of sender-anonymity"),
889      1, &GNUNET_GETOPT_set_uint, &bo.anonymity_level},
890     {'d', "disable-creation-time", NULL,
891      gettext_noop
892      ("disable adding the creation time to the metadata of the uploaded file"),
893      0, &GNUNET_GETOPT_set_one, &do_disable_creation_time},
894     {'D', "disable-extractor", NULL,
895      gettext_noop ("do not use libextractor to add keywords or metadata"),
896      0, &GNUNET_GETOPT_set_one, &disable_extractor},
897     {'e', "extract", NULL,
898      gettext_noop
899      ("print list of extracted keywords that would be used, but do not perform upload"),
900      0, &GNUNET_GETOPT_set_one, &extract_only},
901     {'k', "key", "KEYWORD",
902      gettext_noop
903      ("add an additional keyword for the top-level file or directory"
904       " (this option can be specified multiple times)"),
905      1, &GNUNET_FS_getopt_set_keywords, &topKeywords},
906     {'m', "meta", "TYPE:VALUE",
907      gettext_noop ("set the meta-data for the given TYPE to the given VALUE"),
908      1, &GNUNET_FS_getopt_set_metadata, &meta},
909     {'n', "noindex", NULL,
910      gettext_noop ("do not index, perform full insertion (stores entire "
911                    "file in encrypted form in GNUnet database)"),
912      0, &GNUNET_GETOPT_set_one, &do_insert},
913     {'N', "next", "ID",
914      gettext_noop
915      ("specify ID of an updated version to be published in the future"
916       " (for namespace insertions only)"),
917      1, &GNUNET_GETOPT_set_string, &next_id},
918     {'p', "priority", "PRIORITY",
919      gettext_noop ("specify the priority of the content"),
920      1, &GNUNET_GETOPT_set_uint, &bo.content_priority},
921     {'P', "pseudonym", "NAME",
922      gettext_noop
923      ("publish the files under the pseudonym NAME (place file into namespace)"),
924      1, &GNUNET_GETOPT_set_string, &pseudonym},
925     {'r', "replication", "LEVEL",
926      gettext_noop ("set the desired replication LEVEL"),
927      1, &GNUNET_GETOPT_set_uint, &bo.replication_level},
928     {'s', "simulate-only", NULL,
929      gettext_noop ("only simulate the process but do not do any "
930                    "actual publishing (useful to compute URIs)"),
931      0, &GNUNET_GETOPT_set_one, &do_simulate},
932     {'t', "this", "ID",
933      gettext_noop ("set the ID of this version of the publication"
934                    " (for namespace insertions only)"),
935      1, &GNUNET_GETOPT_set_string, &this_id},
936     {'u', "uri", "URI",
937      gettext_noop ("URI to be published (can be used instead of passing a "
938                    "file to add keywords to the file with the respective URI)"),
939      1, &GNUNET_GETOPT_set_string, &uri_string},
940     {'V', "verbose", NULL,
941      gettext_noop ("be verbose (print progress information)"),
942      0, &GNUNET_GETOPT_set_one, &verbose},
943     GNUNET_GETOPT_OPTION_END
944   };
945   bo.expiration_time =
946       GNUNET_TIME_year_to_time (GNUNET_TIME_get_current_year () + 2);
947
948   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
949     return 2;
950   ret = (GNUNET_OK ==
951          GNUNET_PROGRAM_run (argc, argv, "gnunet-publish [OPTIONS] FILENAME",
952                              gettext_noop
953                              ("Publish a file or directory on GNUnet"),
954                              options, &run, NULL)) ? ret : 1;
955   GNUNET_free ((void*) argv);
956   return ret;
957 }
958
959 /* end of gnunet-publish.c */