global reindent, now with uncrustify hook enabled
[oweals/gnunet.git] / src / fs / fs_directory.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2003, 2004, 2006, 2009 GNUnet e.V.
4
5      GNUnet is free software: you can redistribute it and/or modify it
6      under the terms of the GNU Affero General Public License as published
7      by the Free Software Foundation, either version 3 of the License,
8      or (at your 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      Affero General Public License for more details.
14
15      You should have received a copy of the GNU Affero General Public License
16      along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18      SPDX-License-Identifier: AGPL3.0-or-later
19  */
20
21 /**
22  * @file fs/fs_directory.c
23  * @brief Helper functions for building directories.
24  * @author Christian Grothoff
25  *
26  * TODO:
27  * - modify directory builder API to support incremental
28  *   generation of directories (to allow directories that
29  *   would not fit into memory to be created)
30  * - modify directory processor API to support incremental
31  *   iteration over FULL directories (without missing entries)
32  *   to allow access to directories that do not fit entirely
33  *   into memory
34  */
35 #include "platform.h"
36 #include "gnunet_fs_service.h"
37 #include "fs_api.h"
38
39 /**
40  * String that is used to indicate that a file
41  * is a GNUnet directory.
42  */
43 #define GNUNET_DIRECTORY_MAGIC "\211GND\r\n\032\n"
44
45
46 /**
47  * Does the meta-data claim that this is a directory?
48  * Checks if the mime-type is that of a GNUnet directory.
49  *
50  * @return #GNUNET_YES if it is, #GNUNET_NO if it is not, #GNUNET_SYSERR if
51  *  we have no mime-type information (treat as #GNUNET_NO)
52  */
53 int
54 GNUNET_FS_meta_data_test_for_directory (const struct
55                                         GNUNET_CONTAINER_MetaData *md)
56 {
57   char *mime;
58   int ret;
59
60   if (NULL == md)
61     return GNUNET_SYSERR;
62   mime = GNUNET_CONTAINER_meta_data_get_by_type (md,
63                                                  EXTRACTOR_METATYPE_MIMETYPE);
64   if (NULL == mime)
65     return GNUNET_SYSERR;
66   ret = (0 == strcasecmp (mime, GNUNET_FS_DIRECTORY_MIME)) ? GNUNET_YES :
67         GNUNET_NO;
68   GNUNET_free (mime);
69   return ret;
70 }
71
72
73 /**
74  * Set the MIMETYPE information for the given
75  * metadata to "application/gnunet-directory".
76  *
77  * @param md metadata to add mimetype to
78  */
79 void
80 GNUNET_FS_meta_data_make_directory (struct GNUNET_CONTAINER_MetaData *md)
81 {
82   char *mime;
83
84   mime =
85     GNUNET_CONTAINER_meta_data_get_by_type (md, EXTRACTOR_METATYPE_MIMETYPE);
86   if (mime != NULL)
87   {
88     GNUNET_break (0 == strcmp (mime, GNUNET_FS_DIRECTORY_MIME));
89     GNUNET_free (mime);
90     return;
91   }
92   GNUNET_CONTAINER_meta_data_insert (md, "<gnunet>",
93                                      EXTRACTOR_METATYPE_MIMETYPE,
94                                      EXTRACTOR_METAFORMAT_UTF8, "text/plain",
95                                      GNUNET_FS_DIRECTORY_MIME,
96                                      strlen (GNUNET_FS_DIRECTORY_MIME) + 1);
97 }
98
99
100 /**
101  * Closure for 'find_full_data'.
102  */
103 struct GetFullDataClosure
104 {
105   /**
106    * Extracted binary meta data.
107    */
108   void *data;
109
110   /**
111    * Number of bytes stored in data.
112    */
113   size_t size;
114 };
115
116
117 /**
118  * Type of a function that libextractor calls for each
119  * meta data item found.
120  *
121  * @param cls closure (user-defined)
122  * @param plugin_name name of the plugin that produced this value;
123  *        special values can be used (i.e. '&lt;zlib&gt;' for zlib being
124  *        used in the main libextractor library and yielding
125  *        meta data).
126  * @param type libextractor-type describing the meta data
127  * @param format basic format information about data
128  * @param data_mime_type mime-type of data (not of the original file);
129  *        can be NULL (if mime-type is not known)
130  * @param data actual meta-data found
131  * @param data_len number of bytes in data
132  * @return 0 to continue extracting, 1 to abort
133  */
134 static int
135 find_full_data (void *cls, const char *plugin_name,
136                 enum EXTRACTOR_MetaType type, enum EXTRACTOR_MetaFormat format,
137                 const char *data_mime_type, const char *data, size_t data_len)
138 {
139   struct GetFullDataClosure *gfdc = cls;
140
141   if (type == EXTRACTOR_METATYPE_GNUNET_FULL_DATA)
142   {
143     gfdc->size = data_len;
144     if (data_len > 0)
145     {
146       gfdc->data = GNUNET_malloc (data_len);
147       GNUNET_memcpy (gfdc->data, data, data_len);
148     }
149     return 1;
150   }
151   return 0;
152 }
153
154
155 /**
156  * Iterate over all entries in a directory.  Note that directories
157  * are structured such that it is possible to iterate over the
158  * individual blocks as well as over the entire directory.  Thus
159  * a client can call this function on the buffer in the
160  * GNUNET_FS_ProgressCallback.  Also, directories can optionally
161  * include the contents of (small) files embedded in the directory
162  * itself; for those files, the processor may be given the
163  * contents of the file directly by this function.
164  * <p>
165  *
166  * Note that this function maybe called on parts of directories.  Thus
167  * parser errors should not be reported _at all_ (with GNUNET_break).
168  * Still, if some entries can be recovered despite these parsing
169  * errors, the function should try to do this.
170  *
171  * @param size number of bytes in data
172  * @param data pointer to the beginning of the directory
173  * @param offset offset of data in the directory
174  * @param dep function to call on each entry
175  * @param dep_cls closure for @a dep
176  * @return #GNUNET_OK if this could be a block in a directory,
177  *         #GNUNET_NO if this could be part of a directory (but not 100% OK)
178  *         #GNUNET_SYSERR if @a data does not represent a directory
179  */
180 int
181 GNUNET_FS_directory_list_contents (size_t size,
182                                    const void *data,
183                                    uint64_t offset,
184                                    GNUNET_FS_DirectoryEntryProcessor dep,
185                                    void *dep_cls)
186 {
187   struct GetFullDataClosure full_data;
188   const char *cdata = data;
189   char *emsg;
190   uint64_t pos;
191   uint64_t align;
192   uint32_t mdSize;
193   uint64_t epos;
194   struct GNUNET_FS_Uri *uri;
195   struct GNUNET_CONTAINER_MetaData *md;
196   char *filename;
197
198   if ((offset == 0) &&
199       ((size < 8 + sizeof(uint32_t)) ||
200        (0 != memcmp (cdata,
201                      GNUNET_FS_DIRECTORY_MAGIC,
202                      8))))
203     return GNUNET_SYSERR;
204   pos = offset;
205   if (offset == 0)
206   {
207     GNUNET_memcpy (&mdSize,
208                    &cdata[8],
209                    sizeof(uint32_t));
210     mdSize = ntohl (mdSize);
211     if (mdSize > size - 8 - sizeof(uint32_t))
212     {
213       /* invalid size */
214       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
215                   _ ("MAGIC mismatch.  This is not a GNUnet directory.\n"));
216       return GNUNET_SYSERR;
217     }
218     md = GNUNET_CONTAINER_meta_data_deserialize (&cdata[8 + sizeof(uint32_t)],
219                                                  mdSize);
220     if (md == NULL)
221     {
222       GNUNET_break (0);
223       return GNUNET_SYSERR;     /* malformed ! */
224     }
225     dep (dep_cls,
226          NULL,
227          NULL,
228          md,
229          0,
230          NULL);
231     GNUNET_CONTAINER_meta_data_destroy (md);
232     pos = 8 + sizeof(uint32_t) + mdSize;
233   }
234   while (pos < size)
235   {
236     /* find end of URI */
237     if (cdata[pos] == '\0')
238     {
239       /* URI is never empty, must be end of block,
240        * skip to next alignment */
241       align = ((pos / DBLOCK_SIZE) + 1) * DBLOCK_SIZE;
242       if (align == pos)
243       {
244         /* if we were already aligned, still skip a block! */
245         align += DBLOCK_SIZE;
246       }
247       pos = align;
248       if (pos >= size)
249       {
250         /* malformed - or partial download... */
251         break;
252       }
253     }
254     epos = pos;
255     while ((epos < size) && (cdata[epos] != '\0'))
256       epos++;
257     if (epos >= size)
258       return GNUNET_NO;         /* malformed - or partial download */
259
260     uri = GNUNET_FS_uri_parse (&cdata[pos], &emsg);
261     pos = epos + 1;
262     if (NULL == uri)
263     {
264       GNUNET_free (emsg);
265       pos--;                    /* go back to '\0' to force going to next alignment */
266       continue;
267     }
268     if (GNUNET_FS_uri_test_ksk (uri))
269     {
270       GNUNET_FS_uri_destroy (uri);
271       GNUNET_break (0);
272       return GNUNET_NO;         /* illegal in directory! */
273     }
274
275     GNUNET_memcpy (&mdSize,
276                    &cdata[pos],
277                    sizeof(uint32_t));
278     mdSize = ntohl (mdSize);
279     pos += sizeof(uint32_t);
280     if (pos + mdSize > size)
281     {
282       GNUNET_FS_uri_destroy (uri);
283       return GNUNET_NO;         /* malformed - or partial download */
284     }
285
286     md = GNUNET_CONTAINER_meta_data_deserialize (&cdata[pos],
287                                                  mdSize);
288     if (NULL == md)
289     {
290       GNUNET_FS_uri_destroy (uri);
291       GNUNET_break (0);
292       return GNUNET_NO;         /* malformed ! */
293     }
294     pos += mdSize;
295     filename =
296       GNUNET_CONTAINER_meta_data_get_by_type (md,
297                                               EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME);
298     full_data.size = 0;
299     full_data.data = NULL;
300     GNUNET_CONTAINER_meta_data_iterate (md,
301                                         &find_full_data,
302                                         &full_data);
303     if (NULL != dep)
304     {
305       dep (dep_cls,
306            filename,
307            uri,
308            md,
309            full_data.size,
310            full_data.data);
311     }
312     GNUNET_free_non_null (full_data.data);
313     GNUNET_free_non_null (filename);
314     GNUNET_CONTAINER_meta_data_destroy (md);
315     GNUNET_FS_uri_destroy (uri);
316   }
317   return GNUNET_OK;
318 }
319
320 /**
321  * Entries in the directory (builder).
322  */
323 struct BuilderEntry
324 {
325   /**
326    * This is a linked list.
327    */
328   struct BuilderEntry *next;
329
330   /**
331    * Length of this entry.
332    */
333   size_t len;
334 };
335
336 /**
337  * Internal state of a directory builder.
338  */
339 struct GNUNET_FS_DirectoryBuilder
340 {
341   /**
342    * Meta-data for the directory itself.
343    */
344   struct GNUNET_CONTAINER_MetaData *meta;
345
346   /**
347    * Head of linked list of entries.
348    */
349   struct BuilderEntry *head;
350
351   /**
352    * Number of entires in the directory.
353    */
354   unsigned int count;
355 };
356
357
358 /**
359  * Create a directory builder.
360  *
361  * @param mdir metadata for the directory
362  */
363 struct GNUNET_FS_DirectoryBuilder *
364 GNUNET_FS_directory_builder_create (const struct GNUNET_CONTAINER_MetaData
365                                     *mdir)
366 {
367   struct GNUNET_FS_DirectoryBuilder *ret;
368
369   ret = GNUNET_new (struct GNUNET_FS_DirectoryBuilder);
370   if (mdir != NULL)
371     ret->meta = GNUNET_CONTAINER_meta_data_duplicate (mdir);
372   else
373     ret->meta = GNUNET_CONTAINER_meta_data_create ();
374   GNUNET_FS_meta_data_make_directory (ret->meta);
375   return ret;
376 }
377
378
379 /**
380  * Add an entry to a directory.
381  *
382  * @param bld directory to extend
383  * @param uri uri of the entry (must not be a KSK)
384  * @param md metadata of the entry
385  * @param data raw data of the entry, can be NULL, otherwise
386  *        data must point to exactly the number of bytes specified
387  *        by the uri which must be of type LOC or CHK
388  */
389 void
390 GNUNET_FS_directory_builder_add (struct GNUNET_FS_DirectoryBuilder *bld,
391                                  const struct GNUNET_FS_Uri *uri,
392                                  const struct GNUNET_CONTAINER_MetaData *md,
393                                  const void *data)
394 {
395   struct GNUNET_FS_Uri *curi;
396   struct BuilderEntry *e;
397   uint64_t fsize;
398   uint32_t big;
399   ssize_t ret;
400   size_t mds;
401   size_t mdxs;
402   char *uris;
403   char *ser;
404   char *sptr;
405   size_t slen;
406   struct GNUNET_CONTAINER_MetaData *meta;
407   const struct GNUNET_CONTAINER_MetaData *meta_use;
408
409   GNUNET_assert (! GNUNET_FS_uri_test_ksk (uri));
410   if (NULL != data)
411   {
412     GNUNET_assert (! GNUNET_FS_uri_test_sks (uri));
413     if (GNUNET_FS_uri_test_chk (uri))
414     {
415       fsize = GNUNET_FS_uri_chk_get_file_size (uri);
416     }
417     else
418     {
419       curi = GNUNET_FS_uri_loc_get_uri (uri);
420       GNUNET_assert (NULL != curi);
421       fsize = GNUNET_FS_uri_chk_get_file_size (curi);
422       GNUNET_FS_uri_destroy (curi);
423     }
424   }
425   else
426   {
427     fsize = 0;                  /* not given */
428   }
429   if (fsize > MAX_INLINE_SIZE)
430     fsize = 0;                  /* too large */
431   uris = GNUNET_FS_uri_to_string (uri);
432   slen = strlen (uris) + 1;
433   mds = GNUNET_CONTAINER_meta_data_get_serialized_size (md);
434   meta_use = md;
435   meta = NULL;
436   if (fsize > 0)
437   {
438     meta = GNUNET_CONTAINER_meta_data_duplicate (md);
439     GNUNET_CONTAINER_meta_data_insert (meta, "<gnunet>",
440                                        EXTRACTOR_METATYPE_GNUNET_FULL_DATA,
441                                        EXTRACTOR_METAFORMAT_BINARY, NULL, data,
442                                        fsize);
443     mdxs = GNUNET_CONTAINER_meta_data_get_serialized_size (meta);
444     if ((slen + sizeof(uint32_t) + mdxs - 1) / DBLOCK_SIZE ==
445         (slen + sizeof(uint32_t) + mds - 1) / DBLOCK_SIZE)
446     {
447       /* adding full data would not cause us to cross
448        * additional blocks, so add it! */
449       meta_use = meta;
450       mds = mdxs;
451     }
452   }
453
454   if (mds > GNUNET_MAX_MALLOC_CHECKED / 2)
455     mds = GNUNET_MAX_MALLOC_CHECKED / 2;
456   e = GNUNET_malloc (sizeof(struct BuilderEntry) + slen + mds
457                      + sizeof(uint32_t));
458   ser = (char *) &e[1];
459   GNUNET_memcpy (ser, uris, slen);
460   GNUNET_free (uris);
461   sptr = &ser[slen + sizeof(uint32_t)];
462   ret =
463     GNUNET_CONTAINER_meta_data_serialize (meta_use, &sptr, mds,
464                                           GNUNET_CONTAINER_META_DATA_SERIALIZE_PART);
465   if (NULL != meta)
466     GNUNET_CONTAINER_meta_data_destroy (meta);
467   if (ret == -1)
468     mds = 0;
469   else
470     mds = ret;
471   big = htonl (mds);
472   GNUNET_memcpy (&ser[slen], &big, sizeof(uint32_t));
473   e->len = slen + sizeof(uint32_t) + mds;
474   e->next = bld->head;
475   bld->head = e;
476   bld->count++;
477 }
478
479
480 /**
481  * Given the start and end position of a block of
482  * data, return the end position of that data
483  * after alignment to the DBLOCK_SIZE.
484  */
485 static size_t
486 do_align (size_t start_position, size_t end_position)
487 {
488   size_t align;
489
490   align = (end_position / DBLOCK_SIZE) * DBLOCK_SIZE;
491   if ((start_position < align) && (end_position > align))
492     return align + end_position - start_position;
493   return end_position;
494 }
495
496
497 /**
498  * Compute a permuation of the blocks to
499  * minimize the cost of alignment.  Greedy packer.
500  *
501  * @param start starting position for the first block
502  * @param count size of the two arrays
503  * @param sizes the sizes of the individual blocks
504  * @param perm the permutation of the blocks (updated)
505  */
506 static void
507 block_align (size_t start, unsigned int count, const size_t *sizes,
508              unsigned int *perm)
509 {
510   unsigned int i;
511   unsigned int j;
512   unsigned int tmp;
513   unsigned int best;
514   ssize_t badness;
515   size_t cpos;
516   size_t cend;
517   ssize_t cbad;
518   unsigned int cval;
519
520   cpos = start;
521   for (i = 0; i < count; i++)
522   {
523     start = cpos;
524     badness = 0x7FFFFFFF;
525     best = -1;
526     for (j = i; j < count; j++)
527     {
528       cval = perm[j];
529       cend = cpos + sizes[cval];
530       if (cpos % DBLOCK_SIZE == 0)
531       {
532         /* prefer placing the largest blocks first */
533         cbad = -(cend % DBLOCK_SIZE);
534       }
535       else
536       {
537         if (cpos / DBLOCK_SIZE == cend / DBLOCK_SIZE)
538         {
539           /* Data fits into the same block! Prefer small left-overs! */
540           cbad = DBLOCK_SIZE - cend % DBLOCK_SIZE;
541         }
542         else
543         {
544           /* Would have to waste space to re-align, add big factor, this
545            * case is a real loss (proportional to space wasted)! */
546           cbad = DBLOCK_SIZE * (DBLOCK_SIZE - cpos % DBLOCK_SIZE);
547         }
548       }
549       if (cbad < badness)
550       {
551         best = j;
552         badness = cbad;
553       }
554     }
555     GNUNET_assert (best != -1);
556     tmp = perm[i];
557     perm[i] = perm[best];
558     perm[best] = tmp;
559     cpos += sizes[perm[i]];
560     cpos = do_align (start, cpos);
561   }
562 }
563
564
565 /**
566  * Finish building the directory.  Frees the
567  * builder context and returns the directory
568  * in-memory.
569  *
570  * @param bld directory to finish
571  * @param rsize set to the number of bytes needed
572  * @param rdata set to the encoded directory
573  * @return #GNUNET_OK on success
574  */
575 int
576 GNUNET_FS_directory_builder_finish (struct GNUNET_FS_DirectoryBuilder *bld,
577                                     size_t *rsize,
578                                     void **rdata)
579 {
580   char *data;
581   char *sptr;
582   size_t *sizes;
583   unsigned int *perm;
584   unsigned int i;
585   unsigned int j;
586   struct BuilderEntry *pos;
587   struct BuilderEntry **bes;
588   size_t size;
589   size_t psize;
590   size_t off;
591   ssize_t ret;
592   uint32_t big;
593
594   size = strlen (GNUNET_DIRECTORY_MAGIC) + sizeof(uint32_t);
595   size += GNUNET_CONTAINER_meta_data_get_serialized_size (bld->meta);
596   sizes = NULL;
597   perm = NULL;
598   bes = NULL;
599   if (0 < bld->count)
600   {
601     sizes = GNUNET_new_array (bld->count,
602                               size_t);
603     perm = GNUNET_new_array (bld->count,
604                              unsigned int);
605     bes = GNUNET_new_array (bld->count,
606                             struct BuilderEntry *);
607     pos = bld->head;
608     for (i = 0; i < bld->count; i++)
609     {
610       perm[i] = i;
611       bes[i] = pos;
612       sizes[i] = pos->len;
613       pos = pos->next;
614     }
615     block_align (size, bld->count, sizes, perm);
616     /* compute final size with alignment */
617     for (i = 0; i < bld->count; i++)
618     {
619       psize = size;
620       size += sizes[perm[i]];
621       size = do_align (psize, size);
622     }
623   }
624   *rsize = size;
625   data = GNUNET_malloc_large (size);
626   if (data == NULL)
627   {
628     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
629                          "malloc");
630     *rsize = 0;
631     *rdata = NULL;
632     GNUNET_free_non_null (sizes);
633     GNUNET_free_non_null (perm);
634     GNUNET_free_non_null (bes);
635     return GNUNET_SYSERR;
636   }
637   *rdata = data;
638   GNUNET_memcpy (data,
639                  GNUNET_DIRECTORY_MAGIC,
640                  strlen (GNUNET_DIRECTORY_MAGIC));
641   off = strlen (GNUNET_DIRECTORY_MAGIC);
642
643   sptr = &data[off + sizeof(uint32_t)];
644   ret =
645     GNUNET_CONTAINER_meta_data_serialize (bld->meta,
646                                           &sptr,
647                                           size - off - sizeof(uint32_t),
648                                           GNUNET_CONTAINER_META_DATA_SERIALIZE_FULL);
649   GNUNET_assert (ret != -1);
650   big = htonl (ret);
651   GNUNET_memcpy (&data[off],
652                  &big,
653                  sizeof(uint32_t));
654   off += sizeof(uint32_t) + ret;
655   for (j = 0; j < bld->count; j++)
656   {
657     i = perm[j];
658     psize = off;
659     off += sizes[i];
660     off = do_align (psize, off);
661     GNUNET_memcpy (&data[off - sizes[i]], &(bes[i])[1], sizes[i]);
662     GNUNET_free (bes[i]);
663   }
664   GNUNET_free_non_null (sizes);
665   GNUNET_free_non_null (perm);
666   GNUNET_free_non_null (bes);
667   GNUNET_assert (off == size);
668   GNUNET_CONTAINER_meta_data_destroy (bld->meta);
669   GNUNET_free (bld);
670   return GNUNET_OK;
671 }
672
673
674 /* end of fs_directory.c */