dns hijacker code review
[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_api.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 #if !WINDOWS
177   GNUNET_CONTAINER_meta_data_insert (ret->meta, "<gnunet>",
178                                      EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME,
179                                      EXTRACTOR_METAFORMAT_C_STRING,
180                                      "text/plain", fn, strlen (fn) + 1);
181 #else
182   GNUNET_CONTAINER_meta_data_insert (ret->meta, "<gnunet>",
183                                      EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME,
184                                      EXTRACTOR_METAFORMAT_UTF8,
185                                      "text/plain", fn, strlen (fn) + 1);
186 #endif
187   return ret;
188 }
189
190
191 /**
192  * Create an entry for a file in a publish-structure.
193  *
194  * @param h handle to the file sharing subsystem
195  * @param client_info initial value for the client-info value for this entry
196  * @param length length of the file
197  * @param data data for the file (should not be used afterwards by
198  *        the caller; callee will "free")
199  * @param keywords under which keywords should this file be available
200  *         directly; can be NULL
201  * @param meta metadata for the file
202  * @param do_index GNUNET_YES for index, GNUNET_NO for insertion,
203  *                GNUNET_SYSERR for simulation
204  * @param bo block options
205  * @return publish structure entry for the file
206  */
207 struct GNUNET_FS_FileInformation *
208 GNUNET_FS_file_information_create_from_data (struct GNUNET_FS_Handle *h,
209                                              void *client_info, uint64_t length,
210                                              void *data,
211                                              const struct GNUNET_FS_Uri
212                                              *keywords,
213                                              const struct
214                                              GNUNET_CONTAINER_MetaData *meta,
215                                              int do_index,
216                                              const struct GNUNET_FS_BlockOptions
217                                              *bo)
218 {
219   if (GNUNET_YES == do_index)
220   {
221     GNUNET_break (0);
222     return NULL;
223   }
224   return GNUNET_FS_file_information_create_from_reader (h, client_info, length,
225                                                         &GNUNET_FS_data_reader_copy_,
226                                                         data, keywords, meta,
227                                                         do_index, bo);
228 }
229
230
231 /**
232  * Create an entry for a file in a publish-structure.
233  *
234  * @param h handle to the file sharing subsystem
235  * @param client_info initial value for the client-info value for this entry
236  * @param length length of the file
237  * @param reader function that can be used to obtain the data for the file
238  * @param reader_cls closure for "reader"
239  * @param keywords under which keywords should this file be available
240  *         directly; can be NULL
241  * @param meta metadata for the file
242  * @param do_index GNUNET_YES for index, GNUNET_NO for insertion,
243  *                GNUNET_SYSERR for simulation
244  * @param bo block options
245  * @return publish structure entry for the file
246  */
247 struct GNUNET_FS_FileInformation *
248 GNUNET_FS_file_information_create_from_reader (struct GNUNET_FS_Handle *h,
249                                                void *client_info,
250                                                uint64_t length,
251                                                GNUNET_FS_DataReader reader,
252                                                void *reader_cls,
253                                                const struct GNUNET_FS_Uri
254                                                *keywords,
255                                                const struct
256                                                GNUNET_CONTAINER_MetaData *meta,
257                                                int do_index,
258                                                const struct
259                                                GNUNET_FS_BlockOptions *bo)
260 {
261   struct GNUNET_FS_FileInformation *ret;
262
263   if ((GNUNET_YES == do_index) && (reader != &GNUNET_FS_data_reader_file_))
264   {
265     GNUNET_break (0);
266     return NULL;
267   }
268   ret = GNUNET_malloc (sizeof (struct GNUNET_FS_FileInformation));
269   ret->h = h;
270   ret->client_info = client_info;
271   ret->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
272   if (ret->meta == NULL)
273     ret->meta = GNUNET_CONTAINER_meta_data_create ();
274   ret->keywords = (keywords == NULL) ? NULL : GNUNET_FS_uri_dup (keywords);
275   ret->data.file.reader = reader;
276   ret->data.file.reader_cls = reader_cls;
277   ret->data.file.do_index = do_index;
278   ret->data.file.file_size = length;
279   ret->bo = *bo;
280   return ret;
281 }
282
283
284 /**
285  * Closure for "dir_scan_cb".
286  */
287 struct DirScanCls
288 {
289   /**
290    * Metadata extractors to use.
291    */
292   struct EXTRACTOR_PluginList *extractors;
293
294   /**
295    * Master context.
296    */
297   struct GNUNET_FS_Handle *h;
298
299   /**
300    * Function to call on each directory entry.
301    */
302   GNUNET_FS_FileProcessor proc;
303
304   /**
305    * Closure for proc.
306    */
307   void *proc_cls;
308
309   /**
310    * Scanner to use for subdirectories.
311    */
312   GNUNET_FS_DirectoryScanner scanner;
313
314   /**
315    * Closure for scanner.
316    */
317   void *scanner_cls;
318
319   /**
320    * Set to an error message (if any).
321    */
322   char *emsg;
323
324   /**
325    * Block options.
326    */
327   const struct GNUNET_FS_BlockOptions *bo;
328
329   /**
330    * Should files be indexed?
331    */
332   int do_index;
333
334 };
335
336
337 /**
338  * Function called on each entry in a file to cause
339  * default-publishing.
340  *
341  * @param cls closure (struct DirScanCls)
342  * @param filename name of the file to be published
343  * @return GNUNET_OK on success, GNUNET_SYSERR to abort
344  */
345 static int
346 dir_scan_cb (void *cls, const char *filename)
347 {
348   struct DirScanCls *dsc = cls;
349   struct stat sbuf;
350   struct GNUNET_FS_FileInformation *fi;
351   struct GNUNET_FS_Uri *keywords;
352   struct GNUNET_CONTAINER_MetaData *meta;
353
354   if (0 != STAT (filename, &sbuf))
355   {
356     GNUNET_asprintf (&dsc->emsg, _("`%s' failed on file `%s': %s"), "stat",
357                      filename, STRERROR (errno));
358     return GNUNET_SYSERR;
359   }
360   if (S_ISDIR (sbuf.st_mode))
361   {
362     fi = GNUNET_FS_file_information_create_from_directory (dsc->h, NULL,
363                                                            filename,
364                                                            dsc->scanner,
365                                                            dsc->scanner_cls,
366                                                            dsc->do_index,
367                                                            dsc->bo, &dsc->emsg);
368     if (NULL == fi)
369     {
370       GNUNET_assert (NULL != dsc->emsg);
371       return GNUNET_SYSERR;
372     }
373   }
374   else
375   {
376     meta = GNUNET_CONTAINER_meta_data_create ();
377     GNUNET_FS_meta_data_extract_from_file (meta, filename, dsc->extractors);
378     keywords = GNUNET_FS_uri_ksk_create_from_meta_data (meta);
379     fi = GNUNET_FS_file_information_create_from_file (dsc->h, NULL, filename,
380                                                       keywords, meta,
381                                                       dsc->do_index, dsc->bo);
382     GNUNET_CONTAINER_meta_data_destroy (meta);
383     GNUNET_FS_uri_destroy (keywords);
384   }
385   dsc->proc (dsc->proc_cls, filename, fi);
386   return GNUNET_OK;
387 }
388
389
390 /**
391  * Simple, useful default implementation of a directory scanner
392  * (GNUNET_FS_DirectoryScanner).  This implementation expects to get a
393  * UNIX filename, will publish all files in the directory except hidden
394  * files (those starting with a ".").  Metadata will be extracted
395  * using GNU libextractor; the specific list of plugins should be
396  * specified in "cls", passing NULL will disable (!)  metadata
397  * extraction.  Keywords will be derived from the metadata and be
398  * subject to default canonicalization.  This is strictly a
399  * convenience function.
400  *
401  * @param cls must be of type "struct EXTRACTOR_Extractor*"
402  * @param h handle to the file sharing subsystem
403  * @param dirname name of the directory to scan
404  * @param do_index should files be indexed or inserted
405  * @param bo block options
406  * @param proc function called on each entry
407  * @param proc_cls closure for proc
408  * @param emsg where to store an error message (on errors)
409  * @return GNUNET_OK on success
410  */
411 int
412 GNUNET_FS_directory_scanner_default (void *cls, struct GNUNET_FS_Handle *h,
413                                      const char *dirname, int do_index,
414                                      const struct GNUNET_FS_BlockOptions *bo,
415                                      GNUNET_FS_FileProcessor proc,
416                                      void *proc_cls, char **emsg)
417 {
418   struct EXTRACTOR_PluginList *ex = cls;
419   struct DirScanCls dsc;
420
421   dsc.h = h;
422   dsc.extractors = ex;
423   dsc.proc = proc;
424   dsc.proc_cls = proc_cls;
425   dsc.scanner = &GNUNET_FS_directory_scanner_default;
426   dsc.scanner_cls = cls;
427   dsc.do_index = do_index;
428   dsc.bo = bo;
429   if (-1 == GNUNET_DISK_directory_scan (dirname, &dir_scan_cb, &dsc))
430   {
431     GNUNET_assert (NULL != dsc.emsg);
432     *emsg = dsc.emsg;
433     return GNUNET_SYSERR;
434   }
435   return GNUNET_OK;
436 }
437
438
439 /**
440  * Aggregate information we keep for meta data in each directory.
441  */
442 struct MetaValueInformation
443 {
444
445   /**
446    * Mime-type of data.
447    */
448   const char *mime_type;
449
450   /**
451    * The actual meta data.
452    */
453   const char *data;
454
455   /**
456    * Number of bytes in 'data'.
457    */
458   size_t data_size;
459
460   /**
461    * Type of the meta data.
462    */
463   enum EXTRACTOR_MetaType type;
464
465   /**
466    * Format of the meta data.
467    */
468   enum EXTRACTOR_MetaFormat format;
469
470   /**
471    * How often does this meta value occur in this directory?
472    */
473   unsigned int frequency;
474
475 };
476
477
478 /**
479  * Type of a function that libextractor calls for each
480  * meta data item found.
481  *
482  * @param cls the container multihashmap to update
483  * @param plugin_name name of the plugin that produced this value;
484  *        special values can be used (i.e. '&lt;zlib&gt;' for zlib being
485  *        used in the main libextractor library and yielding
486  *        meta data).
487  * @param type libextractor-type describing the meta data
488  * @param format basic format information about data
489  * @param data_mime_type mime-type of data (not of the original file);
490  *        can be NULL (if mime-type is not known)
491  * @param data actual meta-data found
492  * @param data_len number of bytes in data
493  * @return 0 to continue extracting / iterating
494  */
495 static int
496 update_metamap (void *cls, const char *plugin_name,
497                 enum EXTRACTOR_MetaType type, enum EXTRACTOR_MetaFormat format,
498                 const char *data_mime_type, const char *data, 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, &update_metamap, dc->metamap);
600   for (i = 0; i < fi->keywords->data.ksk.keywordCount; i++)
601   {
602     kw = fi->keywords->data.ksk.keywords[i];
603     GNUNET_CRYPTO_hash (kw, strlen (kw), &key);
604     ki = GNUNET_CONTAINER_multihashmap_get (dc->keywordmap, &key);
605     if (ki == NULL)
606     {
607       ki = GNUNET_malloc (sizeof (struct KeywordInformation));
608       ki->keyword = &kw[1];
609       GNUNET_CONTAINER_multihashmap_put (dc->keywordmap, &key, ki,
610                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
611     }
612     ki->frequency++;
613   }
614 }
615
616
617 /**
618  * Closure for 'compute_directory_metadata'.
619  */
620 struct ComputeDirectoryMetadataContext
621 {
622   /**
623    * Where to store the extracted keywords.
624    */
625   struct GNUNET_FS_Uri *ksk;
626
627   /**
628    * Where to store the extracted meta data.
629    */
630   struct GNUNET_CONTAINER_MetaData *meta;
631
632   /**
633    * Threshold to apply for adding meta data.
634    */
635   unsigned int threshold;
636 };
637
638
639 /**
640  * Add metadata that occurs in more than the threshold entries of the
641  * directory to the directory itself.  For example, if most files in a
642  * directory are of the same mime-type, the directory should have that
643  * mime-type as a keyword.
644  *
645  * @param cls the 'struct ComputeDirectoryMetadataContext'
646  * @param key unused
647  * @param value the 'struct MetaValueInformation' (to be freed as well)
648  * @return GNUNET_OK
649  */
650 static int
651 compute_directory_metadata (void *cls, const GNUNET_HashCode * key, void *value)
652 {
653   struct ComputeDirectoryMetadataContext *cdmc = cls;
654   struct MetaValueInformation *mvi = value;
655
656   if (mvi->frequency > cdmc->threshold)
657   {
658     if (mvi->type != EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME)
659       (void) GNUNET_CONTAINER_meta_data_insert (cdmc->meta, "<children>",
660                                                 mvi->type, mvi->format,
661                                                 mvi->mime_type, mvi->data,
662                                                 mvi->data_size);
663     if ((mvi->format == EXTRACTOR_METAFORMAT_UTF8) ||
664         (mvi->format == EXTRACTOR_METAFORMAT_C_STRING))
665       GNUNET_FS_uri_ksk_add_keyword (cdmc->ksk, mvi->data, GNUNET_NO);
666   }
667   GNUNET_free (mvi);
668   return GNUNET_OK;
669 }
670
671
672 /**
673  * Add keywords that occur in more than the threshold entries of the
674  * directory to the directory itself.
675  *
676  * @param cls the 'struct ComputeDirectoryMetadataContext'
677  * @param key unused
678  * @param value the 'struct Keywordnformation' (to be freed as well)
679  * @return GNUNET_OK
680  */
681 static int
682 compute_directory_keywords (void *cls, const GNUNET_HashCode * key, void *value)
683 {
684   struct ComputeDirectoryMetadataContext *cdmc = cls;
685   struct KeywordInformation *ki = value;
686
687   if (ki->frequency > cdmc->threshold)
688     (void) GNUNET_FS_uri_ksk_add_keyword (cdmc->ksk, ki->keyword, GNUNET_NO);
689   GNUNET_free (ki);
690   return GNUNET_OK;
691 }
692
693
694 /**
695  * Create a publish-structure from an existing file hierarchy, inferring
696  * and organizing keywords and metadata as much as possible.  This
697  * function primarily performs the recursive build and re-organizes
698  * keywords and metadata; for automatically getting metadata
699  * extraction, scanning of directories and creation of the respective
700  * GNUNET_FS_FileInformation entries the default scanner should be
701  * passed (GNUNET_FS_directory_scanner_default).  This is strictly a
702  * convenience function.
703  *
704  * @param h handle to the file sharing subsystem
705  * @param client_info initial value for the client-info value for this entry
706  * @param filename name of the top-level file or directory
707  * @param scanner function used to get a list of files in a directory
708  * @param scanner_cls closure for scanner
709  * @param do_index should files in the hierarchy be indexed?
710  * @param bo block options
711  * @param emsg where to store an error message
712  * @return publish structure entry for the directory, NULL on error
713  */
714 struct GNUNET_FS_FileInformation *
715 GNUNET_FS_file_information_create_from_directory (struct GNUNET_FS_Handle *h,
716                                                   void *client_info,
717                                                   const char *filename,
718                                                   GNUNET_FS_DirectoryScanner
719                                                   scanner, void *scanner_cls,
720                                                   int do_index,
721                                                   const struct
722                                                   GNUNET_FS_BlockOptions *bo,
723                                                   char **emsg)
724 {
725   struct GNUNET_FS_FileInformation *ret;
726   struct ComputeDirectoryMetadataContext cdmc;
727   struct EntryProcCls dc;
728   const char *fn;
729   const char *ss;
730   char *dn;
731   struct GNUNET_FS_FileInformation *epos;
732   unsigned int i;
733   const char *kw;
734
735   dc.entries = NULL;
736   dc.count = 0;
737   dc.metamap = GNUNET_CONTAINER_multihashmap_create (64);
738   dc.keywordmap = GNUNET_CONTAINER_multihashmap_create (64);
739   /* update children to point to directory and generate statistics
740    * on all meta data in children */
741   scanner (scanner_cls, h, filename, do_index, bo, &dirproc_add, &dc, emsg);
742   cdmc.meta = GNUNET_CONTAINER_meta_data_create ();
743   cdmc.ksk = GNUNET_malloc (sizeof (struct GNUNET_FS_Uri));
744   cdmc.ksk->type = ksk;
745   cdmc.threshold = 1 + dc.count / 2;    /* 50% threshold for now */
746   GNUNET_FS_meta_data_make_directory (cdmc.meta);
747   GNUNET_CONTAINER_multihashmap_iterate (dc.metamap,
748                                          &compute_directory_metadata, &cdmc);
749   GNUNET_CONTAINER_multihashmap_iterate (dc.keywordmap,
750                                          &compute_directory_keywords, &cdmc);
751   GNUNET_CONTAINER_multihashmap_destroy (dc.metamap);
752   GNUNET_CONTAINER_multihashmap_destroy (dc.keywordmap);
753
754   /* remove keywords in children that are already in the
755    * parent */
756   for (epos = dc.entries; NULL != epos; epos = epos->next)
757   {
758     for (i = 0; i < cdmc.ksk->data.ksk.keywordCount; i++)
759     {
760       kw = cdmc.ksk->data.ksk.keywords[i];
761       GNUNET_FS_uri_ksk_remove_keyword (epos->keywords, &kw[1]);
762     }
763   }
764   GNUNET_FS_uri_ksk_add_keyword (cdmc.ksk, GNUNET_FS_DIRECTORY_MIME, GNUNET_NO);
765   ret =
766       GNUNET_FS_file_information_create_empty_directory (h, client_info, cdmc.ksk,
767                                                          cdmc.meta, bo);
768   GNUNET_CONTAINER_meta_data_destroy (cdmc.meta);
769   GNUNET_FS_uri_destroy (cdmc.ksk);
770   ret->data.dir.entries = dc.entries;
771   while (dc.entries != NULL)
772   {
773     dc.entries->dir = ret;
774     dc.entries = dc.entries->next;
775   }
776   fn = filename;
777   while ((NULL != (ss = strstr (fn, DIR_SEPARATOR_STR))) && (strlen (ss) > 1))
778     fn = ss + 1;
779   GNUNET_asprintf (&dn, "%s/", fn);
780 #if !WINDOWS
781   GNUNET_CONTAINER_meta_data_insert (ret->meta, "<gnunet>",
782                                      EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME,
783                                      EXTRACTOR_METAFORMAT_C_STRING,
784                                      "text/plain", dn, strlen (dn) + 1);
785 #else
786   GNUNET_CONTAINER_meta_data_insert (ret->meta, "<gnunet>",
787                                      EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME,
788                                      EXTRACTOR_METAFORMAT_UTF8,
789                                      "text/plain", dn, strlen (dn) + 1);
790 #endif
791   GNUNET_free (dn);
792   ret->filename = GNUNET_strdup (filename);
793   return ret;
794 }
795
796
797 /**
798  * Test if a given entry represents a directory.
799  *
800  * @param ent check if this FI represents a directory
801  * @return GNUNET_YES if so, GNUNET_NO if not
802  */
803 int
804 GNUNET_FS_file_information_is_directory (const struct GNUNET_FS_FileInformation
805                                          *ent)
806 {
807   return ent->is_directory;
808 }
809
810
811 /**
812  * Create an entry for an empty directory in a publish-structure.
813  * This function should be used by applications for which the
814  * use of "GNUNET_FS_file_information_create_from_directory"
815  * is not appropriate.
816  *
817  * @param h handle to the file sharing subsystem
818  * @param client_info initial value for the client-info value for this entry
819  * @param meta metadata for the directory
820  * @param keywords under which keywords should this directory be available
821  *         directly; can be NULL
822  * @param bo block options
823  * @return publish structure entry for the directory , NULL on error
824  */
825 struct GNUNET_FS_FileInformation *
826 GNUNET_FS_file_information_create_empty_directory (struct GNUNET_FS_Handle *h,
827                                                    void *client_info,
828                                                    const struct GNUNET_FS_Uri
829                                                    *keywords,
830                                                    const struct
831                                                    GNUNET_CONTAINER_MetaData
832                                                    *meta,
833                                                    const struct
834                                                    GNUNET_FS_BlockOptions *bo)
835 {
836   struct GNUNET_FS_FileInformation *ret;
837
838   ret = GNUNET_malloc (sizeof (struct GNUNET_FS_FileInformation));
839   ret->h = h;
840   ret->client_info = client_info;
841   ret->meta = GNUNET_CONTAINER_meta_data_duplicate (meta);
842   ret->keywords = GNUNET_FS_uri_dup (keywords);
843   ret->bo = *bo;
844   ret->is_directory = GNUNET_YES;
845   return ret;
846 }
847
848
849 /**
850  * Add an entry to a directory in a publish-structure.  Clients
851  * should never modify publish structures that were passed to
852  * "GNUNET_FS_publish_start" already.
853  *
854  * @param dir the directory
855  * @param ent the entry to add; the entry must not have been
856  *            added to any other directory at this point and
857  *            must not include "dir" in its structure
858  * @return GNUNET_OK on success, GNUNET_SYSERR on error
859  */
860 int
861 GNUNET_FS_file_information_add (struct GNUNET_FS_FileInformation *dir,
862                                 struct GNUNET_FS_FileInformation *ent)
863 {
864   if ((ent->dir != NULL) || (ent->next != NULL) || (!dir->is_directory))
865   {
866     GNUNET_break (0);
867     return GNUNET_SYSERR;
868   }
869   ent->dir = dir;
870   ent->next = dir->data.dir.entries;
871   dir->data.dir.entries = ent;
872   dir->data.dir.dir_size = 0;
873   return GNUNET_OK;
874 }
875
876
877 /**
878  * Inspect a file or directory in a publish-structure.  Clients
879  * should never modify publish structures that were passed to
880  * "GNUNET_FS_publish_start" already.  When called on a directory,
881  * this function will FIRST call "proc" with information about
882  * the directory itself and then for each of the files in the
883  * directory (but not for files in subdirectories).  When called
884  * on a file, "proc" will be called exactly once (with information
885  * about the specific file).
886  *
887  * @param dir the directory
888  * @param proc function to call on each entry
889  * @param proc_cls closure for proc
890  */
891 void
892 GNUNET_FS_file_information_inspect (struct GNUNET_FS_FileInformation *dir,
893                                     GNUNET_FS_FileInformationProcessor proc,
894                                     void *proc_cls)
895 {
896   struct GNUNET_FS_FileInformation *pos;
897   int no;
898
899   no = GNUNET_NO;
900   if (GNUNET_OK !=
901       proc (proc_cls, dir,
902             (dir->is_directory) ? dir->data.dir.dir_size : dir->data.
903             file.file_size, dir->meta, &dir->keywords, &dir->bo,
904             (dir->is_directory) ? &no : &dir->data.file.do_index,
905             &dir->client_info))
906     return;
907   if (!dir->is_directory)
908     return;
909   pos = dir->data.dir.entries;
910   while (pos != NULL)
911   {
912     no = GNUNET_NO;
913     if (GNUNET_OK !=
914         proc (proc_cls, pos,
915               (pos->is_directory) ? pos->data.dir.dir_size : pos->data.
916               file.file_size, pos->meta, &pos->keywords, &pos->bo,
917               (dir->is_directory) ? &no : &dir->data.file.do_index,
918               &pos->client_info))
919       break;
920     pos = pos->next;
921   }
922 }
923
924
925 /**
926  * Destroy publish-structure.  Clients should never destroy publish
927  * structures that were passed to "GNUNET_FS_publish_start" already.
928  *
929  * @param fi structure to destroy
930  * @param cleaner function to call on each entry in the structure
931  *        (useful to clean up client_info); can be NULL; return
932  *        values are ignored
933  * @param cleaner_cls closure for cleaner
934  */
935 void
936 GNUNET_FS_file_information_destroy (struct GNUNET_FS_FileInformation *fi,
937                                     GNUNET_FS_FileInformationProcessor cleaner,
938                                     void *cleaner_cls)
939 {
940   struct GNUNET_FS_FileInformation *pos;
941   int no;
942
943   no = GNUNET_NO;
944   if (fi->is_directory)
945   {
946     /* clean up directory */
947     while (NULL != (pos = fi->data.dir.entries))
948     {
949       fi->data.dir.entries = pos->next;
950       GNUNET_FS_file_information_destroy (pos, cleaner, cleaner_cls);
951     }
952     /* clean up client-info */
953     if (NULL != cleaner)
954       cleaner (cleaner_cls, fi, fi->data.dir.dir_size, fi->meta, &fi->keywords,
955                &fi->bo, &no, &fi->client_info);
956     GNUNET_free_non_null (fi->data.dir.dir_data);
957   }
958   else
959   {
960     /* call clean-up function of the reader */
961     if (fi->data.file.reader != NULL)
962       fi->data.file.reader (fi->data.file.reader_cls, 0, 0, NULL, NULL);
963     /* clean up client-info */
964     if (NULL != cleaner)
965       cleaner (cleaner_cls, fi, fi->data.file.file_size, fi->meta,
966                &fi->keywords, &fi->bo, &fi->data.file.do_index,
967                &fi->client_info);
968   }
969   GNUNET_free_non_null (fi->filename);
970   GNUNET_free_non_null (fi->emsg);
971   GNUNET_free_non_null (fi->chk_uri);
972   /* clean up serialization */
973   if ((NULL != fi->serialization) && (0 != UNLINK (fi->serialization)))
974     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink",
975                               fi->serialization);
976   if (NULL != fi->keywords)
977     GNUNET_FS_uri_destroy (fi->keywords);
978   if (NULL != fi->meta)
979     GNUNET_CONTAINER_meta_data_destroy (fi->meta);
980   GNUNET_free_non_null (fi->serialization);
981   if (fi->te != NULL)
982   {
983     GNUNET_FS_tree_encoder_finish (fi->te, NULL, NULL);
984     fi->te = NULL;
985   }
986   GNUNET_free (fi);
987 }
988
989
990 /* end of fs_file_information.c */