bb84b948eb794ad93b0c873fbcaf45c295b43cd0
[oweals/gnunet.git] / src / fs / fs_file_information.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2011 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 /**
22  * @file fs/fs_file_information.c
23  * @brief  Manage information for publishing directory hierarchies
24  * @author Christian Grothoff
25  *
26  * TODO:
27  * - metadata filename clean up code
28  * - metadata/ksk generation for directories from contained files
29  */
30 #include "platform.h"
31 #include <extractor.h>
32 #include "gnunet_fs_service.h"
33 #include "fs.h"
34 #include "fs_tree.h"
35
36
37 /**
38  * Add meta data that libextractor finds to our meta data
39  * container.
40  *
41  * @param cls closure, our meta data container
42  * @param plugin_name name of the plugin that produced this value;
43  *        special values can be used (i.e. '&lt;zlib&gt;' for zlib being
44  *        used in the main libextractor library and yielding
45  *        meta data).
46  * @param type libextractor-type describing the meta data
47  * @param format basic format information about data
48  * @param data_mime_type mime-type of data (not of the original file);
49  *        can be NULL (if mime-type is not known)
50  * @param data actual meta-data found
51  * @param data_len number of bytes in data
52  * @return always 0 to continue extracting
53  */
54 static int
55 add_to_md (void *cls, const char *plugin_name, enum EXTRACTOR_MetaType type,
56            enum EXTRACTOR_MetaFormat format, const char *data_mime_type,
57            const char *data, size_t data_len)
58 {
59   struct GNUNET_CONTAINER_MetaData *md = cls;
60
61   (void) GNUNET_CONTAINER_meta_data_insert (md, plugin_name, type, format,
62                                             data_mime_type, data, data_len);
63   return 0;
64 }
65
66
67 /**
68  * Extract meta-data from a file.
69  *
70  * @return GNUNET_SYSERR on error, otherwise the number
71  *   of meta-data items obtained
72  */
73 int
74 GNUNET_FS_meta_data_extract_from_file (struct GNUNET_CONTAINER_MetaData *md,
75                                        const char *filename,
76                                        struct EXTRACTOR_PluginList *extractors)
77 {
78   int old;
79
80   if (filename == NULL)
81     return GNUNET_SYSERR;
82   if (extractors == NULL)
83     return 0;
84   old = GNUNET_CONTAINER_meta_data_iterate (md, NULL, NULL);
85   GNUNET_assert (old >= 0);
86   EXTRACTOR_extract (extractors, filename, NULL, 0, &add_to_md, md);
87   return (GNUNET_CONTAINER_meta_data_iterate (md, NULL, NULL) - old);
88 }
89
90
91
92 /**
93  * Obtain the name under which this file information
94  * structure is stored on disk.  Only works for top-level
95  * file information structures.
96  *
97  * @param s structure to get the filename for
98  * @return NULL on error, otherwise filename that
99  *         can be passed to "GNUNET_FS_file_information_recover"
100  *         to read this fi-struct from disk.
101  */
102 const char *
103 GNUNET_FS_file_information_get_id (struct GNUNET_FS_FileInformation *s)
104 {
105   if (NULL != s->dir)
106     return NULL;
107   return s->serialization;
108 }
109
110
111 /**
112  * Create an entry for a file in a publish-structure.
113  *
114  * @param h handle to the file sharing subsystem
115  * @param client_info initial value for the client-info value for this entry
116  * @param filename name of the file or directory to publish
117  * @param keywords under which keywords should this file be available
118  *         directly; can be NULL
119  * @param meta metadata for the file
120  * @param do_index GNUNET_YES for index, GNUNET_NO for insertion,
121  *                GNUNET_SYSERR for simulation
122  * @param bo block options
123  * @return publish structure entry for the file
124  */
125 struct GNUNET_FS_FileInformation *
126 GNUNET_FS_file_information_create_from_file (struct GNUNET_FS_Handle *h,
127                                              void *client_info,
128                                              const char *filename,
129                                              const struct GNUNET_FS_Uri
130                                              *keywords,
131                                              const struct
132                                              GNUNET_CONTAINER_MetaData *meta,
133                                              int do_index,
134                                              const struct GNUNET_FS_BlockOptions
135                                              *bo)
136 {
137   struct FileInfo *fi;
138   struct stat sbuf;
139   struct GNUNET_FS_FileInformation *ret;
140   const char *fn;
141   const char *ss;
142
143 #if WINDOWS
144   char fn_conv[MAX_PATH];
145 #endif
146
147   if (0 != STAT (filename, &sbuf))
148   {
149     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
150     return NULL;
151   }
152   fi = GNUNET_FS_make_file_reader_context_ (filename);
153   if (fi == NULL)
154   {
155     GNUNET_break (0);
156     return NULL;
157   }
158   ret =
159       GNUNET_FS_file_information_create_from_reader (h, client_info,
160                                                      sbuf.st_size,
161                                                      &GNUNET_FS_data_reader_file_,
162                                                      fi, keywords, meta,
163                                                      do_index, bo);
164   if (ret == NULL)
165     return NULL;
166   ret->h = h;
167   ret->filename = GNUNET_strdup (filename);
168 #if !WINDOWS
169   fn = filename;
170 #else
171   plibc_conv_to_win_path (filename, fn_conv);
172   fn = fn_conv;
173 #endif
174   while (NULL != (ss = strstr (fn, DIR_SEPARATOR_STR)))
175     fn = ss + 1;
176   GNUNET_CONTAINER_meta_data_insert (ret->meta, "<gnunet>",
177                                      EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME,
178                                      EXTRACTOR_METAFORMAT_C_STRING,
179                                      "text/plain", fn, strlen (fn) + 1);
180   return ret;
181 }
182
183
184 /**
185  * Create an entry for a file in a publish-structure.
186  *
187  * @param h handle to the file sharing subsystem
188  * @param client_info initial value for the client-info value for this entry
189  * @param length length of the file
190  * @param data data for the file (should not be used afterwards by
191  *        the caller; callee will "free")
192  * @param keywords under which keywords should this file be available
193  *         directly; can be NULL
194  * @param meta metadata for the file
195  * @param do_index GNUNET_YES for index, GNUNET_NO for insertion,
196  *                GNUNET_SYSERR for simulation
197  * @param bo block options
198  * @return publish structure entry for the file
199  */
200 struct GNUNET_FS_FileInformation *
201 GNUNET_FS_file_information_create_from_data (struct GNUNET_FS_Handle *h,
202                                              void *client_info, uint64_t length,
203                                              void *data,
204                                              const struct GNUNET_FS_Uri
205                                              *keywords,
206                                              const struct
207                                              GNUNET_CONTAINER_MetaData *meta,
208                                              int do_index,
209                                              const struct GNUNET_FS_BlockOptions
210                                              *bo)
211 {
212   if (GNUNET_YES == do_index)
213   {
214     GNUNET_break (0);
215     return NULL;
216   }
217   return GNUNET_FS_file_information_create_from_reader (h, client_info, length,
218                                                         &GNUNET_FS_data_reader_copy_,
219                                                         data, keywords, meta,
220                                                         do_index, bo);
221 }
222
223
224 /**
225  * Create an entry for a file in a publish-structure.
226  *
227  * @param h handle to the file sharing subsystem
228  * @param client_info initial value for the client-info value for this entry
229  * @param length length of the file
230  * @param reader function that can be used to obtain the data for the file
231  * @param reader_cls closure for "reader"
232  * @param keywords under which keywords should this file be available
233  *         directly; can be NULL
234  * @param meta metadata for the file
235  * @param do_index GNUNET_YES for index, GNUNET_NO for insertion,
236  *                GNUNET_SYSERR for simulation
237  * @param bo block options
238  * @return publish structure entry for the file
239  */
240 struct GNUNET_FS_FileInformation *
241 GNUNET_FS_file_information_create_from_reader (struct GNUNET_FS_Handle *h,
242                                                void *client_info,
243                                                uint64_t length,
244                                                GNUNET_FS_DataReader reader,
245                                                void *reader_cls,
246                                                const struct GNUNET_FS_Uri
247                                                *keywords,
248                                                const struct
249                                                GNUNET_CONTAINER_MetaData *meta,
250                                                int do_index,
251                                                const struct
252                                                GNUNET_FS_BlockOptions *bo)
253 {
254   struct GNUNET_FS_FileInformation *ret;
255
256   if ((GNUNET_YES == do_index) && (reader != &GNUNET_FS_data_reader_file_))
257   {
258     GNUNET_break (0);
259     return NULL;
260   }
261   ret = GNUNET_malloc (sizeof (struct GNUNET_FS_FileInformation));
262   ret->h = h;
263   ret->client_info = client_info;
264   ret->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
265   if (ret->meta == NULL)
266     ret->meta = GNUNET_CONTAINER_meta_data_create ();
267   ret->keywords = (keywords == NULL) ? NULL : GNUNET_FS_uri_dup (keywords);
268   ret->data.file.reader = reader;
269   ret->data.file.reader_cls = reader_cls;
270   ret->data.file.do_index = do_index;
271   ret->data.file.file_size = length;
272   ret->bo = *bo;
273   return ret;
274 }
275
276
277 /**
278  * Closure for "dir_scan_cb".
279  */
280 struct DirScanCls
281 {
282   /**
283    * Metadata extractors to use.
284    */
285   struct EXTRACTOR_PluginList *extractors;
286
287   /**
288    * Master context.
289    */
290   struct GNUNET_FS_Handle *h;
291
292   /**
293    * Function to call on each directory entry.
294    */
295   GNUNET_FS_FileProcessor proc;
296
297   /**
298    * Closure for proc.
299    */
300   void *proc_cls;
301
302   /**
303    * Scanner to use for subdirectories.
304    */
305   GNUNET_FS_DirectoryScanner scanner;
306
307   /**
308    * Closure for scanner.
309    */
310   void *scanner_cls;
311
312   /**
313    * Set to an error message (if any).
314    */
315   char *emsg;
316
317   /**
318    * Block options.
319    */
320   const struct GNUNET_FS_BlockOptions *bo;
321
322   /**
323    * Should files be indexed?
324    */
325   int do_index;
326
327 };
328
329
330 /**
331  * Function called on each entry in a file to cause
332  * default-publishing.
333  *
334  * @param cls closure (struct DirScanCls)
335  * @param filename name of the file to be published
336  * @return GNUNET_OK on success, GNUNET_SYSERR to abort
337  */
338 static int
339 dir_scan_cb (void *cls, const char *filename)
340 {
341   struct DirScanCls *dsc = cls;
342   struct stat sbuf;
343   struct GNUNET_FS_FileInformation *fi;
344   struct GNUNET_FS_Uri *ksk_uri;
345   struct GNUNET_FS_Uri *keywords;
346   struct GNUNET_CONTAINER_MetaData *meta;
347
348   if (0 != STAT (filename, &sbuf))
349   {
350     GNUNET_asprintf (&dsc->emsg, _("`%s' failed on file `%s': %s"), "stat",
351                      filename, STRERROR (errno));
352     return GNUNET_SYSERR;
353   }
354   if (S_ISDIR (sbuf.st_mode))
355   {
356     fi = GNUNET_FS_file_information_create_from_directory (dsc->h, NULL,
357                                                            filename,
358                                                            dsc->scanner,
359                                                            dsc->scanner_cls,
360                                                            dsc->do_index,
361                                                            dsc->bo, &dsc->emsg);
362     if (NULL == fi)
363     {
364       GNUNET_assert (NULL != dsc->emsg);
365       return GNUNET_SYSERR;
366     }
367   }
368   else
369   {
370     meta = GNUNET_CONTAINER_meta_data_create ();
371     GNUNET_FS_meta_data_extract_from_file (meta, filename, dsc->extractors);
372     keywords = GNUNET_FS_uri_ksk_create_from_meta_data (meta);
373     ksk_uri = GNUNET_FS_uri_ksk_canonicalize (keywords);
374     fi = GNUNET_FS_file_information_create_from_file (dsc->h, NULL, filename,
375                                                       ksk_uri, meta,
376                                                       dsc->do_index, dsc->bo);
377     GNUNET_CONTAINER_meta_data_destroy (meta);
378     GNUNET_FS_uri_destroy (keywords);
379     GNUNET_FS_uri_destroy (ksk_uri);
380   }
381   dsc->proc (dsc->proc_cls, filename, fi);
382   return GNUNET_OK;
383 }
384
385
386 /**
387  * Simple, useful default implementation of a directory scanner
388  * (GNUNET_FS_DirectoryScanner).  This implementation expects to get a
389  * UNIX filename, will publish all files in the directory except hidden
390  * files (those starting with a ".").  Metadata will be extracted
391  * using GNU libextractor; the specific list of plugins should be
392  * specified in "cls", passing NULL will disable (!)  metadata
393  * extraction.  Keywords will be derived from the metadata and be
394  * subject to default canonicalization.  This is strictly a
395  * convenience function.
396  *
397  * @param cls must be of type "struct EXTRACTOR_Extractor*"
398  * @param h handle to the file sharing subsystem
399  * @param dirname name of the directory to scan
400  * @param do_index should files be indexed or inserted
401  * @param bo block options
402  * @param proc function called on each entry
403  * @param proc_cls closure for proc
404  * @param emsg where to store an error message (on errors)
405  * @return GNUNET_OK on success
406  */
407 int
408 GNUNET_FS_directory_scanner_default (void *cls, struct GNUNET_FS_Handle *h,
409                                      const char *dirname, int do_index,
410                                      const struct GNUNET_FS_BlockOptions *bo,
411                                      GNUNET_FS_FileProcessor proc,
412                                      void *proc_cls, char **emsg)
413 {
414   struct EXTRACTOR_PluginList *ex = cls;
415   struct DirScanCls dsc;
416
417   dsc.h = h;
418   dsc.extractors = ex;
419   dsc.proc = proc;
420   dsc.proc_cls = proc_cls;
421   dsc.scanner = &GNUNET_FS_directory_scanner_default;
422   dsc.scanner_cls = cls;
423   dsc.do_index = do_index;
424   dsc.bo = bo;
425   if (-1 == GNUNET_DISK_directory_scan (dirname, &dir_scan_cb, &dsc))
426   {
427     GNUNET_assert (NULL != dsc.emsg);
428     *emsg = dsc.emsg;
429     return GNUNET_SYSERR;
430   }
431   return GNUNET_OK;
432 }
433
434
435 /**
436  * Aggregate information we keep for meta data in each directory.
437  */
438 struct MetaValueInformation
439 {
440
441   /**
442    * Mime-type of data.
443    */
444   const char *mime_type;
445
446   /**
447    * The actual meta data.
448    */
449   const char *data;
450
451   /**
452    * Number of bytes in 'data'.
453    */
454   size_t data_size;
455
456   /**
457    * Type of the meta data.
458    */
459   enum EXTRACTOR_MetaType type;
460
461   /**
462    * Format of the meta data.
463    */
464   enum EXTRACTOR_MetaFormat format;
465
466   /**
467    * How often does this meta value occur in this directory?
468    */
469   unsigned int frequency;
470
471 };
472
473
474 /**
475  * Type of a function that libextractor calls for each
476  * meta data item found.
477  *
478  * @param cls the container multihashmap to update
479  * @param plugin_name name of the plugin that produced this value;
480  *        special values can be used (i.e. '<zlib>' for zlib being
481  *        used in the main libextractor library and yielding
482  *        meta data).
483  * @param type libextractor-type describing the meta data
484  * @param format basic format information about data
485  * @param data_mime_type mime-type of data (not of the original file);
486  *        can be NULL (if mime-type is not known)
487  * @param data actual meta-data found
488  * @param data_len number of bytes in data
489  * @return 0 to continue extracting / iterating
490  */
491 static int
492 update_metamap (void *cls, const char *plugin_name,
493                 enum EXTRACTOR_MetaType type, enum EXTRACTOR_MetaFormat format,
494                 const char *data_mime_type, const char *data, size_t data_len)
495 {
496   struct GNUNET_CONTAINER_MultiHashMap *map = cls;
497   GNUNET_HashCode key;
498   struct MetaValueInformation *mvi;
499
500   GNUNET_CRYPTO_hash (data, data_len, &key);
501   mvi = GNUNET_CONTAINER_multihashmap_get (map, &key);
502   if (mvi == NULL)
503   {
504     mvi = GNUNET_malloc (sizeof (struct MetaValueInformation));
505     mvi->mime_type = data_mime_type;
506     mvi->data = data;
507     mvi->data_size = data_len;
508     mvi->type = type;
509     mvi->format = format;
510     GNUNET_CONTAINER_multihashmap_put (map, &key, mvi,
511                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
512   }
513   mvi->frequency++;
514   return 0;
515 }
516
517
518 /**
519  * Aggregate information we keep for keywords in each directory.
520  */
521 struct KeywordInformation
522 {
523
524   /**
525    * Mime-type of keyword.
526    */
527   const char *keyword;
528
529   /**
530    * How often does this meta value occur in this directory?
531    */
532   unsigned int frequency;
533
534 };
535
536
537 /**
538  * Closure for dirproc function.
539  */
540 struct EntryProcCls
541 {
542   /**
543    * Linked list of directory entries that is being
544    * created.
545    */
546   struct GNUNET_FS_FileInformation *entries;
547
548   /**
549    * Map describing the meta data for all entries in the
550    * directory.  Keys are the hash of the meta-value,
551    * values are of type 'struct MetaValueInformation'.
552    */
553   struct GNUNET_CONTAINER_MultiHashMap *metamap;
554
555   /**
556    * Map describing the keywords for all entries in the
557    * directory.  Keys are the hash of the keyword,
558    * values are of type 'struct KeywordInformation'.
559    */
560   struct GNUNET_CONTAINER_MultiHashMap *keywordmap;
561
562   /**
563    * Number of entries in 'entries'.
564    */
565   unsigned int count;
566
567 };
568
569
570 /**
571  * Function that processes a directory entry that
572  * was obtained from the scanner.  Adds each entry to
573  * the directory and computes directroy meta map.
574  *
575  * @param cls our closure
576  * @param filename name of the file (unused, why there???)
577  * @param fi information for publishing the file
578  */
579 static void
580 dirproc_add (void *cls, const char *filename,
581              struct GNUNET_FS_FileInformation *fi)
582 {
583   struct EntryProcCls *dc = cls;
584   unsigned int i;
585   const char *kw;
586   struct KeywordInformation *ki;
587   GNUNET_HashCode key;
588
589   GNUNET_assert (fi->next == NULL);
590   GNUNET_assert (fi->dir == NULL);
591   fi->next = dc->entries;
592   dc->entries = fi;
593   dc->count++;
594   if (NULL != fi->meta)
595     GNUNET_CONTAINER_meta_data_iterate (fi->meta, &update_metamap, dc->metamap);
596   for (i = 0; i < fi->keywords->data.ksk.keywordCount; i++)
597   {
598     kw = fi->keywords->data.ksk.keywords[i];
599     GNUNET_CRYPTO_hash (kw, strlen (kw), &key);
600     ki = GNUNET_CONTAINER_multihashmap_get (dc->keywordmap, &key);
601     if (ki == NULL)
602     {
603       ki = GNUNET_malloc (sizeof (struct KeywordInformation));
604       ki->keyword = &kw[1];
605       GNUNET_CONTAINER_multihashmap_put (dc->keywordmap, &key, ki,
606                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
607     }
608     ki->frequency++;
609   }
610 }
611
612
613 /**
614  * Closure for 'compute_directory_metadata'.
615  */
616 struct ComputeDirectoryMetadataContext
617 {
618   /**
619    * Where to store the extracted keywords.
620    */
621   struct GNUNET_FS_Uri *ksk;
622
623   /**
624    * Where to store the extracted meta data.
625    */
626   struct GNUNET_CONTAINER_MetaData *meta;
627
628   /**
629    * Threshold to apply for adding meta data.
630    */
631   unsigned int threshold;
632 };
633
634
635 /**
636  * Add metadata that occurs in more than the threshold entries of the
637  * directory to the directory itself.  For example, if most files in a
638  * directory are of the same mime-type, the directory should have that
639  * mime-type as a keyword.
640  *
641  * @param cls the 'struct ComputeDirectoryMetadataContext'
642  * @param key unused
643  * @param value the 'struct MetaValueInformation' (to be freed as well)
644  * @return GNUNET_OK
645  */
646 static int
647 compute_directory_metadata (void *cls, const GNUNET_HashCode * key, void *value)
648 {
649   struct ComputeDirectoryMetadataContext *cdmc = cls;
650   struct MetaValueInformation *mvi = value;
651
652   if (mvi->frequency > cdmc->threshold)
653   {
654     if (mvi->type != EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME)
655       (void) GNUNET_CONTAINER_meta_data_insert (cdmc->meta, "<children>",
656                                                 mvi->type, mvi->format,
657                                                 mvi->mime_type, mvi->data,
658                                                 mvi->data_size);
659     if ((mvi->format == EXTRACTOR_METAFORMAT_UTF8) ||
660         (mvi->format == EXTRACTOR_METAFORMAT_C_STRING))
661       GNUNET_FS_uri_ksk_add_keyword (cdmc->ksk, mvi->data, GNUNET_NO);
662   }
663   GNUNET_free (mvi);
664   return GNUNET_OK;
665 }
666
667
668 /**
669  * Add keywords that occur in more than the threshold entries of the
670  * directory to the directory itself.
671  *
672  * @param cls the 'struct ComputeDirectoryMetadataContext'
673  * @param key unused
674  * @param value the 'struct Keywordnformation' (to be freed as well)
675  * @return GNUNET_OK
676  */
677 static int
678 compute_directory_keywords (void *cls, const GNUNET_HashCode * key, void *value)
679 {
680   struct ComputeDirectoryMetadataContext *cdmc = cls;
681   struct KeywordInformation *ki = value;
682
683   if (ki->frequency > cdmc->threshold)
684     (void) GNUNET_FS_uri_ksk_add_keyword (cdmc->ksk, ki->keyword, GNUNET_NO);
685   GNUNET_free (ki);
686   return GNUNET_OK;
687 }
688
689
690 /**
691  * Create a publish-structure from an existing file hierarchy, inferring
692  * and organizing keywords and metadata as much as possible.  This
693  * function primarily performs the recursive build and re-organizes
694  * keywords and metadata; for automatically getting metadata
695  * extraction, scanning of directories and creation of the respective
696  * GNUNET_FS_FileInformation entries the default scanner should be
697  * passed (GNUNET_FS_directory_scanner_default).  This is strictly a
698  * convenience function.
699  *
700  * @param h handle to the file sharing subsystem
701  * @param client_info initial value for the client-info value for this entry
702  * @param filename name of the top-level file or directory
703  * @param scanner function used to get a list of files in a directory
704  * @param scanner_cls closure for scanner
705  * @param do_index should files in the hierarchy be indexed?
706  * @param bo block options
707  * @param emsg where to store an error message
708  * @return publish structure entry for the directory, NULL on error
709  */
710 struct GNUNET_FS_FileInformation *
711 GNUNET_FS_file_information_create_from_directory (struct GNUNET_FS_Handle *h,
712                                                   void *client_info,
713                                                   const char *filename,
714                                                   GNUNET_FS_DirectoryScanner
715                                                   scanner, void *scanner_cls,
716                                                   int do_index,
717                                                   const struct
718                                                   GNUNET_FS_BlockOptions *bo,
719                                                   char **emsg)
720 {
721   struct GNUNET_FS_FileInformation *ret;
722   struct ComputeDirectoryMetadataContext cdmc;
723   struct EntryProcCls dc;
724   const char *fn;
725   const char *ss;
726   struct GNUNET_FS_Uri *cksk;
727   char *dn;
728   struct GNUNET_FS_FileInformation *epos;
729   unsigned int i;
730   const char *kw;
731
732   dc.entries = NULL;
733   dc.count = 0;
734   dc.metamap = GNUNET_CONTAINER_multihashmap_create (64);
735   dc.keywordmap = GNUNET_CONTAINER_multihashmap_create (64);
736   /* update children to point to directory and generate statistics
737    * on all meta data in children */
738   scanner (scanner_cls, h, filename, do_index, bo, &dirproc_add, &dc, emsg);
739   cdmc.meta = GNUNET_CONTAINER_meta_data_create ();
740   cdmc.ksk = GNUNET_malloc (sizeof (struct GNUNET_FS_Uri));
741   cdmc.ksk->type = ksk;
742   cdmc.threshold = 1 + dc.count / 2;    /* 50% threshold for now */
743   GNUNET_FS_meta_data_make_directory (cdmc.meta);
744   GNUNET_CONTAINER_multihashmap_iterate (dc.metamap,
745                                          &compute_directory_metadata, &cdmc);
746   GNUNET_CONTAINER_multihashmap_iterate (dc.keywordmap,
747                                          &compute_directory_keywords, &cdmc);
748   GNUNET_CONTAINER_multihashmap_destroy (dc.metamap);
749   GNUNET_CONTAINER_multihashmap_destroy (dc.keywordmap);
750   GNUNET_FS_uri_ksk_add_keyword (cdmc.ksk, GNUNET_FS_DIRECTORY_MIME, GNUNET_NO);
751   cksk = GNUNET_FS_uri_ksk_canonicalize (cdmc.ksk);
752
753   /* remove keywords in children that are already in the
754    * parent */
755   for (epos = dc.entries; NULL != epos; epos = epos->next)
756   {
757     for (i = 0; i < cksk->data.ksk.keywordCount; i++)
758     {
759       kw = cksk->data.ksk.keywords[i];
760       GNUNET_FS_uri_ksk_remove_keyword (epos->keywords, &kw[1]);
761     }
762   }
763   ret =
764       GNUNET_FS_file_information_create_empty_directory (h, client_info, cksk,
765                                                          cdmc.meta, bo);
766   GNUNET_CONTAINER_meta_data_destroy (cdmc.meta);
767   GNUNET_FS_uri_destroy (cdmc.ksk);
768   ret->data.dir.entries = dc.entries;
769   while (dc.entries != NULL)
770   {
771     dc.entries->dir = ret;
772     dc.entries = dc.entries->next;
773   }
774   fn = filename;
775   while ((NULL != (ss = strstr (fn, DIR_SEPARATOR_STR))) && (strlen (ss) > 1))
776     fn = ss + 1;
777   GNUNET_asprintf (&dn, "%s/", fn);
778   GNUNET_CONTAINER_meta_data_insert (ret->meta, "<gnunet>",
779                                      EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME,
780                                      EXTRACTOR_METAFORMAT_C_STRING,
781                                      "text/plain", dn, strlen (dn) + 1);
782   GNUNET_free (dn);
783   ret->filename = GNUNET_strdup (filename);
784   return ret;
785 }
786
787
788 /**
789  * Test if a given entry represents a directory.
790  *
791  * @param ent check if this FI represents a directory
792  * @return GNUNET_YES if so, GNUNET_NO if not
793  */
794 int
795 GNUNET_FS_file_information_is_directory (const struct GNUNET_FS_FileInformation
796                                          *ent)
797 {
798   return ent->is_directory;
799 }
800
801
802 /**
803  * Create an entry for an empty directory in a publish-structure.
804  * This function should be used by applications for which the
805  * use of "GNUNET_FS_file_information_create_from_directory"
806  * is not appropriate.
807  *
808  * @param h handle to the file sharing subsystem
809  * @param client_info initial value for the client-info value for this entry
810  * @param meta metadata for the directory
811  * @param keywords under which keywords should this directory be available
812  *         directly; can be NULL
813  * @param bo block options
814  * @return publish structure entry for the directory , NULL on error
815  */
816 struct GNUNET_FS_FileInformation *
817 GNUNET_FS_file_information_create_empty_directory (struct GNUNET_FS_Handle *h,
818                                                    void *client_info,
819                                                    const struct GNUNET_FS_Uri
820                                                    *keywords,
821                                                    const struct
822                                                    GNUNET_CONTAINER_MetaData
823                                                    *meta,
824                                                    const struct
825                                                    GNUNET_FS_BlockOptions *bo)
826 {
827   struct GNUNET_FS_FileInformation *ret;
828
829   ret = GNUNET_malloc (sizeof (struct GNUNET_FS_FileInformation));
830   ret->h = h;
831   ret->client_info = client_info;
832   ret->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
833   ret->keywords = GNUNET_FS_uri_dup (keywords);
834   ret->bo = *bo;
835   ret->is_directory = GNUNET_YES;
836   return ret;
837 }
838
839
840 /**
841  * Add an entry to a directory in a publish-structure.  Clients
842  * should never modify publish structures that were passed to
843  * "GNUNET_FS_publish_start" already.
844  *
845  * @param dir the directory
846  * @param ent the entry to add; the entry must not have been
847  *            added to any other directory at this point and
848  *            must not include "dir" in its structure
849  * @return GNUNET_OK on success, GNUNET_SYSERR on error
850  */
851 int
852 GNUNET_FS_file_information_add (struct GNUNET_FS_FileInformation *dir,
853                                 struct GNUNET_FS_FileInformation *ent)
854 {
855   if ((ent->dir != NULL) || (ent->next != NULL) || (!dir->is_directory))
856   {
857     GNUNET_break (0);
858     return GNUNET_SYSERR;
859   }
860   ent->dir = dir;
861   ent->next = dir->data.dir.entries;
862   dir->data.dir.entries = ent;
863   dir->data.dir.dir_size = 0;
864   return GNUNET_OK;
865 }
866
867
868 /**
869  * Inspect a file or directory in a publish-structure.  Clients
870  * should never modify publish structures that were passed to
871  * "GNUNET_FS_publish_start" already.  When called on a directory,
872  * this function will FIRST call "proc" with information about
873  * the directory itself and then for each of the files in the
874  * directory (but not for files in subdirectories).  When called
875  * on a file, "proc" will be called exactly once (with information
876  * about the specific file).
877  *
878  * @param dir the directory
879  * @param proc function to call on each entry
880  * @param proc_cls closure for proc
881  */
882 void
883 GNUNET_FS_file_information_inspect (struct GNUNET_FS_FileInformation *dir,
884                                     GNUNET_FS_FileInformationProcessor proc,
885                                     void *proc_cls)
886 {
887   struct GNUNET_FS_FileInformation *pos;
888   int no;
889
890   no = GNUNET_NO;
891   if (GNUNET_OK !=
892       proc (proc_cls, dir,
893             (dir->is_directory) ? dir->data.dir.dir_size : dir->data.
894             file.file_size, dir->meta, &dir->keywords, &dir->bo,
895             (dir->is_directory) ? &no : &dir->data.file.do_index,
896             &dir->client_info))
897     return;
898   if (!dir->is_directory)
899     return;
900   pos = dir->data.dir.entries;
901   while (pos != NULL)
902   {
903     no = GNUNET_NO;
904     if (GNUNET_OK !=
905         proc (proc_cls, pos,
906               (pos->is_directory) ? pos->data.dir.dir_size : pos->data.
907               file.file_size, pos->meta, &pos->keywords, &pos->bo,
908               (dir->is_directory) ? &no : &dir->data.file.do_index,
909               &pos->client_info))
910       break;
911     pos = pos->next;
912   }
913 }
914
915
916 /**
917  * Destroy publish-structure.  Clients should never destroy publish
918  * structures that were passed to "GNUNET_FS_publish_start" already.
919  *
920  * @param fi structure to destroy
921  * @param cleaner function to call on each entry in the structure
922  *        (useful to clean up client_info); can be NULL; return
923  *        values are ignored
924  * @param cleaner_cls closure for cleaner
925  */
926 void
927 GNUNET_FS_file_information_destroy (struct GNUNET_FS_FileInformation *fi,
928                                     GNUNET_FS_FileInformationProcessor cleaner,
929                                     void *cleaner_cls)
930 {
931   struct GNUNET_FS_FileInformation *pos;
932   int no;
933
934   no = GNUNET_NO;
935   if (fi->is_directory)
936   {
937     /* clean up directory */
938     while (NULL != (pos = fi->data.dir.entries))
939     {
940       fi->data.dir.entries = pos->next;
941       GNUNET_FS_file_information_destroy (pos, cleaner, cleaner_cls);
942     }
943     /* clean up client-info */
944     if (NULL != cleaner)
945       cleaner (cleaner_cls, fi, fi->data.dir.dir_size, fi->meta, &fi->keywords,
946                &fi->bo, &no, &fi->client_info);
947     GNUNET_free_non_null (fi->data.dir.dir_data);
948   }
949   else
950   {
951     /* call clean-up function of the reader */
952     if (fi->data.file.reader != NULL)
953       fi->data.file.reader (fi->data.file.reader_cls, 0, 0, NULL, NULL);
954     /* clean up client-info */
955     if (NULL != cleaner)
956       cleaner (cleaner_cls, fi, fi->data.file.file_size, fi->meta,
957                &fi->keywords, &fi->bo, &fi->data.file.do_index,
958                &fi->client_info);
959   }
960   GNUNET_free_non_null (fi->filename);
961   GNUNET_free_non_null (fi->emsg);
962   GNUNET_free_non_null (fi->chk_uri);
963   /* clean up serialization */
964   if ((NULL != fi->serialization) && (0 != UNLINK (fi->serialization)))
965     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink",
966                               fi->serialization);
967   if (NULL != fi->keywords)
968     GNUNET_FS_uri_destroy (fi->keywords);
969   if (NULL != fi->meta)
970     GNUNET_CONTAINER_meta_data_destroy (fi->meta);
971   GNUNET_free_non_null (fi->serialization);
972   if (fi->te != NULL)
973   {
974     GNUNET_FS_tree_encoder_finish (fi->te, NULL, NULL);
975     fi->te = NULL;
976   }
977   GNUNET_free (fi);
978 }
979
980
981 /* end of fs_file_information.c */