ce4f189a91ee6a718c425a2e72924427459ba0d1
[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,
493                 const char *plugin_name,
494                 enum EXTRACTOR_MetaType type,
495                 enum EXTRACTOR_MetaFormat format,
496                 const char *data_mime_type,
497                 const char *data,
498                 size_t data_len)
499 {
500   struct GNUNET_CONTAINER_MultiHashMap *map = cls;
501   GNUNET_HashCode key;
502   struct MetaValueInformation *mvi;
503
504   GNUNET_CRYPTO_hash (data, data_len, &key);
505   mvi = GNUNET_CONTAINER_multihashmap_get (map, &key);
506   if (mvi == NULL)
507   {
508     mvi = GNUNET_malloc (sizeof (struct MetaValueInformation));
509     mvi->mime_type = data_mime_type;
510     mvi->data = data;
511     mvi->data_size = data_len;
512     mvi->type = type;
513     mvi->format = format;
514     GNUNET_CONTAINER_multihashmap_put (map, &key, mvi,
515                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
516   }
517   mvi->frequency++;  
518   return 0; 
519 }
520
521
522 /**
523  * Aggregate information we keep for keywords in each directory.
524  */
525 struct KeywordInformation
526 {
527   
528   /**
529    * Mime-type of keyword.
530    */
531   const char *keyword;
532
533   /**
534    * How often does this meta value occur in this directory?
535    */
536   unsigned int frequency;
537
538 };
539
540
541 /**
542  * Closure for dirproc function.
543  */
544 struct EntryProcCls
545 {
546   /**
547    * Linked list of directory entries that is being
548    * created.
549    */
550   struct GNUNET_FS_FileInformation *entries;
551
552   /**
553    * Map describing the meta data for all entries in the
554    * directory.  Keys are the hash of the meta-value,
555    * values are of type 'struct MetaValueInformation'.
556    */
557   struct GNUNET_CONTAINER_MultiHashMap *metamap;
558
559   /**
560    * Map describing the keywords for all entries in the
561    * directory.  Keys are the hash of the keyword,
562    * values are of type 'struct KeywordInformation'.
563    */
564   struct GNUNET_CONTAINER_MultiHashMap *keywordmap;
565
566   /**
567    * Number of entries in 'entries'.
568    */
569   unsigned int count;
570
571 };
572
573
574 /**
575  * Function that processes a directory entry that
576  * was obtained from the scanner.  Adds each entry to
577  * the directory and computes directroy meta map.
578  *
579  * @param cls our closure
580  * @param filename name of the file (unused, why there???)
581  * @param fi information for publishing the file
582  */
583 static void
584 dirproc_add (void *cls, const char *filename, 
585              struct GNUNET_FS_FileInformation *fi)
586 {
587   struct EntryProcCls *dc = cls;
588   unsigned int i;
589   const char *kw;
590   struct KeywordInformation *ki;
591   GNUNET_HashCode key;
592  
593   GNUNET_assert (fi->next == NULL);
594   GNUNET_assert (fi->dir == NULL);
595   fi->next = dc->entries;
596   dc->entries = fi;
597   dc->count++;
598   if (NULL != fi->meta)
599     GNUNET_CONTAINER_meta_data_iterate (fi->meta,
600                                         &update_metamap,
601                                         dc->metamap);
602   for (i=0;i<fi->keywords->data.ksk.keywordCount;i++)
603   {
604     kw = fi->keywords->data.ksk.keywords[i];   
605     GNUNET_CRYPTO_hash (kw, strlen(kw), &key);
606     ki = GNUNET_CONTAINER_multihashmap_get (dc->keywordmap, &key);
607     if (ki == NULL)
608     {
609       ki = GNUNET_malloc (sizeof (struct KeywordInformation));
610       ki->keyword = &kw[1];
611       GNUNET_CONTAINER_multihashmap_put (dc->keywordmap, &key, ki,
612                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
613     }
614     ki->frequency++;  
615   }
616 }
617
618
619 /**
620  * Closure for 'compute_directory_metadata'.
621  */
622 struct ComputeDirectoryMetadataContext
623 {
624   /**
625    * Where to store the extracted keywords.
626    */
627   struct GNUNET_FS_Uri *ksk;
628
629   /**
630    * Where to store the extracted meta data.
631    */
632   struct GNUNET_CONTAINER_MetaData *meta;
633
634   /**
635    * Threshold to apply for adding meta data.
636    */ 
637   unsigned int threshold;
638 };
639
640
641 /**
642  * Add metadata that occurs in more than the threshold entries of the
643  * directory to the directory itself.  For example, if most files in a
644  * directory are of the same mime-type, the directory should have that
645  * mime-type as a keyword.
646  *
647  * @param cls the 'struct ComputeDirectoryMetadataContext'
648  * @param key unused
649  * @param value the 'struct MetaValueInformation' (to be freed as well)
650  * @return GNUNET_OK
651  */
652 static int
653 compute_directory_metadata (void *cls,
654                             const GNUNET_HashCode *key,
655                             void *value)
656 {
657   struct ComputeDirectoryMetadataContext *cdmc = cls;
658   struct MetaValueInformation *mvi = value;
659
660   if (mvi->frequency > cdmc->threshold) 
661   {
662     if (mvi->type != EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME)
663       (void) GNUNET_CONTAINER_meta_data_insert (cdmc->meta,
664                                                 "<children>",
665                                                 mvi->type,
666                                                 mvi->format,
667                                                 mvi->mime_type,
668                                                 mvi->data,
669                                                 mvi->data_size);
670     if ( (mvi->format == EXTRACTOR_METAFORMAT_UTF8) ||
671          (mvi->format == EXTRACTOR_METAFORMAT_C_STRING) )
672       GNUNET_FS_uri_ksk_add_keyword (cdmc->ksk,
673                                      mvi->data,
674                                      GNUNET_NO);
675   } 
676   GNUNET_free (mvi);
677   return GNUNET_OK;
678 }
679
680
681 /**
682  * Add keywords that occur in more than the threshold entries of the
683  * directory to the directory itself.  
684  *
685  * @param cls the 'struct ComputeDirectoryMetadataContext'
686  * @param key unused
687  * @param value the 'struct Keywordnformation' (to be freed as well)
688  * @return GNUNET_OK
689  */
690 static int
691 compute_directory_keywords (void *cls,
692                             const GNUNET_HashCode *key,
693                             void *value)
694 {
695   struct ComputeDirectoryMetadataContext *cdmc = cls;
696   struct KeywordInformation *ki = value;
697
698   if (ki->frequency > cdmc->threshold)       
699     (void) GNUNET_FS_uri_ksk_add_keyword (cdmc->ksk,
700                                           ki->keyword,
701                                           GNUNET_NO);
702   GNUNET_free (ki);
703   return GNUNET_OK;
704 }
705
706
707 /**
708  * Create a publish-structure from an existing file hierarchy, inferring
709  * and organizing keywords and metadata as much as possible.  This
710  * function primarily performs the recursive build and re-organizes
711  * keywords and metadata; for automatically getting metadata
712  * extraction, scanning of directories and creation of the respective
713  * GNUNET_FS_FileInformation entries the default scanner should be
714  * passed (GNUNET_FS_directory_scanner_default).  This is strictly a
715  * convenience function.
716  *
717  * @param h handle to the file sharing subsystem
718  * @param client_info initial value for the client-info value for this entry
719  * @param filename name of the top-level file or directory
720  * @param scanner function used to get a list of files in a directory
721  * @param scanner_cls closure for scanner
722  * @param do_index should files in the hierarchy be indexed?
723  * @param bo block options
724  * @param emsg where to store an error message
725  * @return publish structure entry for the directory, NULL on error
726  */
727 struct GNUNET_FS_FileInformation *
728 GNUNET_FS_file_information_create_from_directory (struct GNUNET_FS_Handle *h,
729                                                   void *client_info,
730                                                   const char *filename,
731                                                   GNUNET_FS_DirectoryScanner
732                                                   scanner, void *scanner_cls,
733                                                   int do_index,
734                                                   const struct
735                                                   GNUNET_FS_BlockOptions *bo,
736                                                   char **emsg)
737 {
738   struct GNUNET_FS_FileInformation *ret;
739   struct ComputeDirectoryMetadataContext cdmc;
740   struct EntryProcCls dc;
741   const char *fn;
742   const char *ss;
743   struct GNUNET_FS_Uri *cksk;
744   char *dn;
745   struct GNUNET_FS_FileInformation *epos;
746   unsigned int i;
747   const char *kw;
748
749   dc.entries = NULL;
750   dc.count = 0;
751   dc.metamap = GNUNET_CONTAINER_multihashmap_create (64);
752   dc.keywordmap = GNUNET_CONTAINER_multihashmap_create (64);
753   /* update children to point to directory and generate statistics
754      on all meta data in children */
755   scanner (scanner_cls, h, filename, do_index, bo, &dirproc_add, &dc, emsg);
756   cdmc.meta = GNUNET_CONTAINER_meta_data_create ();
757   cdmc.ksk = GNUNET_malloc (sizeof (struct GNUNET_FS_Uri));
758   cdmc.ksk->type = ksk;
759   cdmc.threshold = 1 + dc.count / 2; /* 50% threshold for now */
760   GNUNET_FS_meta_data_make_directory (cdmc.meta);
761   GNUNET_CONTAINER_multihashmap_iterate (dc.metamap,
762                                          &compute_directory_metadata,
763                                          &cdmc);
764   GNUNET_CONTAINER_multihashmap_iterate (dc.keywordmap,
765                                          &compute_directory_keywords,
766                                          &cdmc);
767   GNUNET_CONTAINER_multihashmap_destroy (dc.metamap);
768   GNUNET_CONTAINER_multihashmap_destroy (dc.keywordmap);
769   GNUNET_FS_uri_ksk_add_keyword (cdmc.ksk,
770                                  GNUNET_FS_DIRECTORY_MIME,
771                                  GNUNET_NO);
772   cksk = GNUNET_FS_uri_ksk_canonicalize (cdmc.ksk);
773
774   /* remove keywords in children that are already in the
775      parent */
776   for (epos = dc.entries; NULL != epos; epos = epos->next)
777   {
778     for (i=0;i<cksk->data.ksk.keywordCount;i++)
779       {
780         kw = cksk->data.ksk.keywords[i];
781         GNUNET_FS_uri_ksk_remove_keyword (epos->keywords,
782                                           &kw[1]);
783       }
784   }
785   ret =
786       GNUNET_FS_file_information_create_empty_directory (h, client_info, cksk,
787                                                          cdmc.meta, bo);
788   GNUNET_CONTAINER_meta_data_destroy (cdmc.meta);
789   GNUNET_FS_uri_destroy (cdmc.ksk);
790   ret->data.dir.entries = dc.entries;
791   while (dc.entries != NULL)
792   {
793     dc.entries->dir = ret;
794     dc.entries = dc.entries->next;
795   }
796   fn = filename;
797   while ((NULL != (ss = strstr (fn, DIR_SEPARATOR_STR))) && (strlen (ss) > 1))
798     fn = ss + 1;
799   GNUNET_asprintf (&dn, "%s/", fn);
800   GNUNET_CONTAINER_meta_data_insert (ret->meta, "<gnunet>",
801                                      EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME,
802                                      EXTRACTOR_METAFORMAT_C_STRING,
803                                      "text/plain", dn, strlen (dn) + 1);
804   GNUNET_free (dn);
805   ret->filename = GNUNET_strdup (filename);
806   return ret;
807 }
808
809
810 /**
811  * Test if a given entry represents a directory.
812  *
813  * @param ent check if this FI represents a directory
814  * @return GNUNET_YES if so, GNUNET_NO if not
815  */
816 int
817 GNUNET_FS_file_information_is_directory (const struct GNUNET_FS_FileInformation
818                                          *ent)
819 {
820   return ent->is_directory;
821 }
822
823
824 /**
825  * Create an entry for an empty directory in a publish-structure.
826  * This function should be used by applications for which the
827  * use of "GNUNET_FS_file_information_create_from_directory"
828  * is not appropriate.
829  *
830  * @param h handle to the file sharing subsystem
831  * @param client_info initial value for the client-info value for this entry
832  * @param meta metadata for the directory
833  * @param keywords under which keywords should this directory be available
834  *         directly; can be NULL
835  * @param bo block options
836  * @return publish structure entry for the directory , NULL on error
837  */
838 struct GNUNET_FS_FileInformation *
839 GNUNET_FS_file_information_create_empty_directory (struct GNUNET_FS_Handle *h,
840                                                    void *client_info,
841                                                    const struct GNUNET_FS_Uri
842                                                    *keywords,
843                                                    const struct
844                                                    GNUNET_CONTAINER_MetaData
845                                                    *meta,
846                                                    const struct
847                                                    GNUNET_FS_BlockOptions *bo)
848 {
849   struct GNUNET_FS_FileInformation *ret;
850
851   ret = GNUNET_malloc (sizeof (struct GNUNET_FS_FileInformation));
852   ret->h = h;
853   ret->client_info = client_info;
854   ret->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
855   ret->keywords = GNUNET_FS_uri_dup (keywords);
856   ret->bo = *bo;
857   ret->is_directory = GNUNET_YES;
858   return ret;
859 }
860
861
862 /**
863  * Add an entry to a directory in a publish-structure.  Clients
864  * should never modify publish structures that were passed to
865  * "GNUNET_FS_publish_start" already.
866  *
867  * @param dir the directory
868  * @param ent the entry to add; the entry must not have been
869  *            added to any other directory at this point and
870  *            must not include "dir" in its structure
871  * @return GNUNET_OK on success, GNUNET_SYSERR on error
872  */
873 int
874 GNUNET_FS_file_information_add (struct GNUNET_FS_FileInformation *dir,
875                                 struct GNUNET_FS_FileInformation *ent)
876 {
877   if ((ent->dir != NULL) || (ent->next != NULL) || (!dir->is_directory))
878   {
879     GNUNET_break (0);
880     return GNUNET_SYSERR;
881   }
882   ent->dir = dir;
883   ent->next = dir->data.dir.entries;
884   dir->data.dir.entries = ent;
885   dir->data.dir.dir_size = 0;
886   return GNUNET_OK;
887 }
888
889
890 /**
891  * Inspect a file or directory in a publish-structure.  Clients
892  * should never modify publish structures that were passed to
893  * "GNUNET_FS_publish_start" already.  When called on a directory,
894  * this function will FIRST call "proc" with information about
895  * the directory itself and then for each of the files in the
896  * directory (but not for files in subdirectories).  When called
897  * on a file, "proc" will be called exactly once (with information
898  * about the specific file).
899  *
900  * @param dir the directory
901  * @param proc function to call on each entry
902  * @param proc_cls closure for proc
903  */
904 void
905 GNUNET_FS_file_information_inspect (struct GNUNET_FS_FileInformation *dir,
906                                     GNUNET_FS_FileInformationProcessor proc,
907                                     void *proc_cls)
908 {
909   struct GNUNET_FS_FileInformation *pos;
910   int no;
911
912   no = GNUNET_NO;
913   if (GNUNET_OK !=
914       proc (proc_cls, dir,
915             (dir->is_directory) ? dir->data.dir.dir_size : dir->data.
916             file.file_size, dir->meta, &dir->keywords, &dir->bo,
917             (dir->is_directory) ? &no : &dir->data.file.do_index,
918             &dir->client_info))
919     return;
920   if (!dir->is_directory)
921     return;
922   pos = dir->data.dir.entries;
923   while (pos != NULL)
924   {
925     no = GNUNET_NO;
926     if (GNUNET_OK !=
927         proc (proc_cls, pos,
928               (pos->is_directory) ? pos->data.dir.dir_size : pos->data.
929               file.file_size, pos->meta, &pos->keywords, &pos->bo,
930               (dir->is_directory) ? &no : &dir->data.file.do_index,
931               &pos->client_info))
932       break;
933     pos = pos->next;
934   }
935 }
936
937
938 /**
939  * Destroy publish-structure.  Clients should never destroy publish
940  * structures that were passed to "GNUNET_FS_publish_start" already.
941  *
942  * @param fi structure to destroy
943  * @param cleaner function to call on each entry in the structure
944  *        (useful to clean up client_info); can be NULL; return
945  *        values are ignored
946  * @param cleaner_cls closure for cleaner
947  */
948 void
949 GNUNET_FS_file_information_destroy (struct GNUNET_FS_FileInformation *fi,
950                                     GNUNET_FS_FileInformationProcessor cleaner,
951                                     void *cleaner_cls)
952 {
953   struct GNUNET_FS_FileInformation *pos;
954   int no;
955
956   no = GNUNET_NO;
957   if (fi->is_directory)
958   {
959     /* clean up directory */
960     while (NULL != (pos = fi->data.dir.entries))
961     {
962       fi->data.dir.entries = pos->next;
963       GNUNET_FS_file_information_destroy (pos, cleaner, cleaner_cls);
964     }
965     /* clean up client-info */
966     if (NULL != cleaner)
967       cleaner (cleaner_cls, fi, fi->data.dir.dir_size, fi->meta, &fi->keywords,
968                &fi->bo, &no, &fi->client_info);
969     GNUNET_free_non_null (fi->data.dir.dir_data);
970   }
971   else
972   {
973     /* call clean-up function of the reader */
974     if (fi->data.file.reader != NULL)
975       fi->data.file.reader (fi->data.file.reader_cls, 0, 0, NULL, NULL);
976     /* clean up client-info */
977     if (NULL != cleaner)
978       cleaner (cleaner_cls, fi, fi->data.file.file_size, fi->meta,
979                &fi->keywords, &fi->bo, &fi->data.file.do_index,
980                &fi->client_info);
981   }
982   GNUNET_free_non_null (fi->filename);
983   GNUNET_free_non_null (fi->emsg);
984   GNUNET_free_non_null (fi->chk_uri);
985   /* clean up serialization */
986   if ((NULL != fi->serialization) && (0 != UNLINK (fi->serialization)))
987     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink",
988                               fi->serialization);
989   if (NULL != fi->keywords)
990     GNUNET_FS_uri_destroy (fi->keywords);
991   if (NULL != fi->meta)
992     GNUNET_CONTAINER_meta_data_destroy (fi->meta);
993   GNUNET_free_non_null (fi->serialization);
994   if (fi->te != NULL)
995   {
996     GNUNET_FS_tree_encoder_finish (fi->te, NULL, NULL);
997     fi->te = NULL;
998   }
999   GNUNET_free (fi);
1000 }
1001
1002
1003 /* end of fs_file_information.c */