e037130c81ff53e8382fe68d1ecafaa5f2b14b38
[oweals/gnunet.git] / src / fs / fs_directory.c
1 /*
2      This file is part of GNUnet.
3      (C) 2003, 2004, 2006, 2009 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 2, 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_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.h"
38
39 #ifndef EXTRACTOR_GNUNET_FULL_DATA
40 #define EXTRACTOR_GNUNET_FULL_DATA 137
41 #endif
42
43 /**
44  * String that is used to indicate that a file
45  * is a GNUnet directory.
46  */
47 #define GNUNET_DIRECTORY_MAGIC "\211GND\r\n\032\n"
48
49
50 /**
51  * Does the meta-data claim that this is a directory?
52  * Checks if the mime-type is that of a GNUnet directory.
53  *
54  * @return GNUNET_YES if it is, GNUNET_NO if it is not, GNUNET_SYSERR if
55  *  we have no mime-type information (treat as 'GNUNET_NO')
56  */
57 int 
58 GNUNET_FS_meta_data_test_for_directory (const struct GNUNET_CONTAINER_MetaData *md)
59 {
60   char *mime;
61   int ret;
62   
63   mime = GNUNET_CONTAINER_meta_data_get_by_type (md, EXTRACTOR_MIMETYPE);
64   if (mime == NULL)
65     return GNUNET_SYSERR;
66   ret = (0 == strcmp (mime, GNUNET_FS_DIRECTORY_MIME)) ? GNUNET_YES : GNUNET_NO;
67   GNUNET_free (mime);
68   return ret; 
69 }
70
71
72 /**
73  * Set the MIMETYPE information for the given
74  * metadata to "application/gnunet-directory".
75  * 
76  * @param md metadata to add mimetype to
77  */
78 void
79 GNUNET_FS_meta_data_make_directory (struct GNUNET_CONTAINER_MetaData *md)
80 {
81   char *mime;
82   
83   mime = GNUNET_CONTAINER_meta_data_get_by_type (md, EXTRACTOR_MIMETYPE);
84   if (mime != NULL)
85     {
86       GNUNET_break (0 == strcmp (mime,
87                                  GNUNET_FS_DIRECTORY_MIME));
88       GNUNET_free (mime);
89       return;
90     }
91   GNUNET_CONTAINER_meta_data_insert (md, 
92                                      EXTRACTOR_MIMETYPE,
93                                      GNUNET_FS_DIRECTORY_MIME);
94 }
95
96
97 /**
98  * Iterate over all entries in a directory.  Note that directories
99  * are structured such that it is possible to iterate over the
100  * individual blocks as well as over the entire directory.  Thus
101  * a client can call this function on the buffer in the
102  * GNUNET_FS_ProgressCallback.  Also, directories can optionally
103  * include the contents of (small) files embedded in the directory
104  * itself; for those files, the processor may be given the
105  * contents of the file directly by this function.
106  * <p>
107  *
108  * Note that this function maybe called on parts of directories.  Thus
109  * parser errors should not be reported _at all_ (with GNUNET_break).
110  * Still, if some entries can be recovered despite these parsing
111  * errors, the function should try to do this.
112  *
113  * @param size number of bytes in data
114  * @param data pointer to the beginning of the directory
115  * @param offset offset of data in the directory
116  * @param dep function to call on each entry
117  * @param dep_cls closure for dep
118  */
119 void 
120 GNUNET_FS_directory_list_contents (size_t size,
121                                    const void *data,
122                                    uint64_t offset,
123                                    GNUNET_FS_DirectoryEntryProcessor dep, 
124                                    void *dep_cls)
125 {
126   const char *cdata = data;
127   char *file_data;
128   char *emsg;
129   uint64_t pos;
130   uint64_t align;
131   uint32_t mdSize;
132   uint64_t epos;
133   struct GNUNET_FS_Uri *uri;
134   struct GNUNET_CONTAINER_MetaData *md;
135   char *filename;
136
137   pos = offset;
138   if ( (pos == 0) && 
139        (size >= 8 + sizeof (uint32_t)) &&
140        (0 == memcmp (cdata, GNUNET_FS_DIRECTORY_MAGIC, 8)) )
141     {
142       memcpy (&mdSize, &cdata[8], sizeof (uint32_t));
143       mdSize = ntohl (mdSize);
144       if (mdSize > size - 8 - sizeof (uint32_t))
145         {
146           /* invalid size */
147           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
148                       _("Not a GNUnet directory.\n"));
149           return;
150         }
151       md = GNUNET_CONTAINER_meta_data_deserialize (&cdata[8 +
152                                                          sizeof (uint32_t)],
153                                                    mdSize);
154       if (md == NULL)
155         {
156           GNUNET_break (0);
157           return; /* malformed ! */
158         }
159       dep (dep_cls,
160            NULL,
161            NULL,                                
162            md,
163            0,
164            NULL);
165       GNUNET_CONTAINER_meta_data_destroy (md);
166       pos = 8 + sizeof (uint32_t) + mdSize;
167     }
168   while (pos < size)
169     {
170       /* find end of URI */
171       if (cdata[pos] == '\0')
172         {
173           /* URI is never empty, must be end of block,
174              skip to next alignment */
175           align =
176             ((pos / DBLOCK_SIZE) + 1) * DBLOCK_SIZE;
177           if (align == pos)
178             {
179               /* if we were already aligned, still skip a block! */
180               align += DBLOCK_SIZE;
181             }
182           pos = align;
183           if (pos >= size)
184             {
185               /* malformed - or partial download... */
186               break;
187             }
188         }
189       epos = pos;
190       while ((epos < size) && (cdata[epos] != '\0'))
191         epos++;
192       if (epos >= size)
193         return;   /* malformed - or partial download */
194       
195       uri = GNUNET_FS_uri_parse (&cdata[pos], &emsg);
196       pos = epos + 1;
197       if (uri == NULL)
198         {
199           GNUNET_free (emsg);
200           pos--;                /* go back to '\0' to force going to next alignment */
201           continue;
202         }
203       if (GNUNET_FS_uri_test_ksk (uri))
204         {
205           GNUNET_FS_uri_destroy (uri);
206           GNUNET_break (0);
207           return; /* illegal in directory! */
208         }
209
210       memcpy (&mdSize, &cdata[pos], sizeof (uint32_t));
211       mdSize = ntohl (mdSize);
212       pos += sizeof (uint32_t);
213       if (pos + mdSize > size)
214         {
215           GNUNET_FS_uri_destroy (uri);
216           return; /* malformed - or partial download */
217         }
218
219       md = GNUNET_CONTAINER_meta_data_deserialize (&cdata[pos], mdSize);
220       if (md == NULL)
221         {
222           GNUNET_FS_uri_destroy (uri);
223           GNUNET_break (0);
224           return; /* malformed ! */
225         }
226       pos += mdSize;
227       filename = GNUNET_CONTAINER_meta_data_get_by_type (md,
228                                                          EXTRACTOR_FILENAME);
229       file_data = GNUNET_CONTAINER_meta_data_get_by_type (md,
230                                                           EXTRACTOR_GNUNET_FULL_DATA);
231       if (dep != NULL) 
232          dep (dep_cls,
233               filename,
234               uri,
235               md,
236               (file_data != NULL) ? strlen(file_data) : 0,
237               file_data);
238       GNUNET_free_non_null (file_data);
239       GNUNET_free_non_null (filename);
240       GNUNET_CONTAINER_meta_data_destroy (md);
241       GNUNET_FS_uri_destroy (uri);
242     }
243 }
244
245 /**
246  * Entries in the directory (builder).
247  */
248 struct BuilderEntry
249 {
250   /**
251    * This is a linked list.
252    */
253   struct BuilderEntry *next;
254   
255   /**
256    * Length of this entry.
257    */
258   size_t len;
259 };
260
261 /**
262  * Internal state of a directory builder.
263  */
264 struct GNUNET_FS_DirectoryBuilder
265 {
266   /**
267    * Meta-data for the directory itself.
268    */
269   struct GNUNET_CONTAINER_MetaData *meta;
270
271   /**
272    * Head of linked list of entries.
273    */
274   struct BuilderEntry *head;
275
276   /**
277    * Number of entires in the directory.
278    */
279   unsigned int count;
280 };
281
282
283 /**
284  * Create a directory builder.
285  * 
286  * @param mdir metadata for the directory
287  */
288 struct GNUNET_FS_DirectoryBuilder *
289 GNUNET_FS_directory_builder_create (const struct GNUNET_CONTAINER_MetaData *mdir)
290 {
291   struct GNUNET_FS_DirectoryBuilder *ret;
292
293   ret = GNUNET_malloc(sizeof(struct GNUNET_FS_DirectoryBuilder));
294   ret->meta = GNUNET_CONTAINER_meta_data_duplicate (mdir);
295   GNUNET_FS_meta_data_make_directory (ret->meta);
296   return ret;
297 }
298
299
300 /**
301  * Add an entry to a directory.
302  * 
303  * @param bld directory to extend
304  * @param uri uri of the entry (must not be a KSK)
305  * @param md metadata of the entry
306  * @param data raw data of the entry, can be NULL, otherwise
307  *        data must point to exactly the number of bytes specified
308  *        by the uri which must be of type LOC or CHK
309  */
310 void
311 GNUNET_FS_directory_builder_add (struct GNUNET_FS_DirectoryBuilder *bld,
312                                  const struct GNUNET_FS_Uri *uri,
313                                  const struct GNUNET_CONTAINER_MetaData *md,
314                                  const void *data)
315 {
316   struct GNUNET_FS_Uri *curi;
317   struct BuilderEntry *e;
318   uint64_t fsize;
319   uint32_t big;
320   ssize_t ret;
321   size_t mds;
322   size_t mdxs;
323   char *uris;
324   char *ser;
325   size_t slen;
326   struct GNUNET_CONTAINER_MetaData *meta;
327   const struct GNUNET_CONTAINER_MetaData *meta_use;
328
329   GNUNET_assert (! GNUNET_FS_uri_test_ksk (uri));
330   if (NULL != data)
331     if (GNUNET_FS_uri_test_chk (uri))
332       fsize = GNUNET_FS_uri_chk_get_file_size (uri);
333     else
334       {
335         curi = GNUNET_FS_uri_loc_get_uri (uri);
336         fsize = GNUNET_FS_uri_chk_get_file_size (curi);
337         GNUNET_FS_uri_destroy (curi);
338       }
339   else
340     fsize = 0; /* not given */
341   if (fsize > MAX_INLINE_SIZE)
342     fsize = 0; /* too large */
343   if ( (NULL == data) ||
344        (NULL != memchr (data, 0, fsize)) )
345     fsize = 0; /* must not have 0's in data! */
346   uris = GNUNET_FS_uri_to_string (uri);
347   slen = strlen (uris) + 1;
348   mds =
349     GNUNET_CONTAINER_meta_data_get_serialized_size (md,
350                                                     GNUNET_CONTAINER_META_DATA_SERIALIZE_FULL);  
351   meta_use = md;
352   meta = NULL;
353   if (fsize > 0)
354     {
355       meta = GNUNET_CONTAINER_meta_data_duplicate (md);
356       GNUNET_CONTAINER_meta_data_insert (meta,
357                                          EXTRACTOR_GNUNET_FULL_DATA,
358                                          data);
359       mdxs =
360         GNUNET_CONTAINER_meta_data_get_serialized_size (meta,
361                                                         GNUNET_CONTAINER_META_DATA_SERIALIZE_FULL);  
362       if ( (slen + sizeof (uint32_t) + mdxs - 1) / DBLOCK_SIZE ==
363            (slen + sizeof (uint32_t) + mds - 1) / DBLOCK_SIZE)
364         {
365           /* adding full data would not cause us to cross
366              additional blocks, so add it! */
367           meta_use = meta;
368           mds = mdxs;
369         }
370     }
371
372   if (mds > GNUNET_MAX_MALLOC_CHECKED / 2)
373     mds = GNUNET_MAX_MALLOC_CHECKED / 2;
374   e = GNUNET_malloc (sizeof(struct BuilderEntry) + 
375                      slen + mds + sizeof (uint32_t));
376   ser = (char*) &e[1];
377   memcpy (ser, uris, slen);
378   GNUNET_free (uris);
379   ret = GNUNET_CONTAINER_meta_data_serialize (meta_use,
380                                               &ser[slen + sizeof(uint32_t)],
381                                               mds,
382                                               GNUNET_CONTAINER_META_DATA_SERIALIZE_PART);
383   if (NULL != meta)
384     GNUNET_CONTAINER_meta_data_destroy (meta);
385   if (ret == -1)
386     mds = 0;
387   else
388     mds = ret;
389   big = htonl (mds);
390   memcpy (&ser[slen], &big, sizeof (uint32_t));
391   e->len = slen + sizeof (uint32_t) + mds;
392   e->next = bld->head;
393   bld->head = e;
394   bld->count++;
395 }
396
397
398 /**
399  * Given the start and end position of a block of
400  * data, return the end position of that data
401  * after alignment to the DBLOCK_SIZE.
402  */
403 static size_t
404 do_align (size_t start_position, 
405           size_t end_position)
406 {
407   size_t align;
408   
409   align = (end_position / DBLOCK_SIZE) * DBLOCK_SIZE;
410   if ((start_position < align) && (end_position > align))
411     return align + end_position - start_position;
412   return end_position;
413 }
414
415
416 /**
417  * Compute a permuation of the blocks to
418  * minimize the cost of alignment.  Greedy packer.
419  *
420  * @param start starting position for the first block
421  * @param count size of the two arrays
422  * @param sizes the sizes of the individual blocks
423  * @param perm the permutation of the blocks (updated)
424  */
425 static void
426 block_align (size_t start,
427              unsigned int count, 
428              const size_t *sizes,
429              unsigned int *perm)
430 {
431   unsigned int i;
432   unsigned int j;
433   unsigned int tmp;
434   unsigned int best;
435   ssize_t badness;
436   size_t cpos;
437   size_t cend;
438   ssize_t cbad;
439   unsigned int cval;
440
441   cpos = start;
442   for (i = 0; i < count; i++)
443     {
444       start = cpos;
445       badness = 0x7FFFFFFF;
446       best = -1;
447       for (j = i; j < count; j++)
448         {
449           cval = perm[j];
450           cend = cpos + sizes[cval];
451           if (cpos % DBLOCK_SIZE == 0)
452             {
453               /* prefer placing the largest blocks first */
454               cbad = -(cend % DBLOCK_SIZE);
455             }
456           else
457             {
458               if (cpos / DBLOCK_SIZE ==
459                   cend / DBLOCK_SIZE)
460                 {
461                   /* Data fits into the same block! Prefer small left-overs! */
462                   cbad =
463                     DBLOCK_SIZE - cend % DBLOCK_SIZE;
464                 }
465               else
466                 {
467                   /* Would have to waste space to re-align, add big factor, this
468                      case is a real loss (proportional to space wasted)! */
469                   cbad =
470                     DBLOCK_SIZE * (DBLOCK_SIZE -
471                                              cpos %
472                                              DBLOCK_SIZE);
473                 }
474             }
475           if (cbad < badness)
476             {
477               best = j;
478               badness = cbad;
479             }
480         }
481       tmp = perm[i];
482       perm[i] = perm[best];
483       perm[best] = tmp;
484       cpos += sizes[perm[i]];
485       cpos = do_align (start, cpos);
486     }
487 }
488
489
490 /**
491  * Finish building the directory.  Frees the
492  * builder context and returns the directory
493  * in-memory.
494  *
495  * @param bld directory to finish
496  * @param rsize set to the number of bytes needed
497  * @param rdata set to the encoded directory
498  * @return GNUNET_OK on success
499  */
500 int
501 GNUNET_FS_directory_builder_finish (struct GNUNET_FS_DirectoryBuilder *bld,
502                                     size_t *rsize,
503                                     void **rdata)
504 {
505   char *data;
506   size_t *sizes;
507   unsigned int *perm;
508   unsigned int i;
509   unsigned int j;
510   struct BuilderEntry *pos;
511   struct BuilderEntry **bes;
512   size_t size;
513   size_t psize;
514   size_t off;
515   ssize_t ret;
516   uint32_t big;
517
518   size = 8 + sizeof (uint32_t);
519   size += GNUNET_CONTAINER_meta_data_get_serialized_size (bld->meta, 
520                                                           GNUNET_CONTAINER_META_DATA_SERIALIZE_FULL);
521   sizes = NULL;
522   perm = NULL;
523   bes = NULL;
524   if (0 < bld->count)
525     {
526       sizes = GNUNET_malloc (bld->count * sizeof (size_t));
527       perm = GNUNET_malloc (bld->count * sizeof (unsigned int));
528       bes = GNUNET_malloc (bld->count * sizeof (struct BuilderEntry *));
529       pos = bld->head;
530       for (i = 0; i < bld->count; i++)
531         {
532           perm[i] = i;
533           bes[i] = pos;
534           sizes[i] = pos->len;
535           pos = pos->next;
536         }
537       block_align (size,
538                    bld->count,
539                    sizes,
540                    perm);
541       /* compute final size with alignment */
542       for (i = 0; i < bld->count; i++)
543         {
544           psize = size;
545           size += sizes[perm[i]];
546           size = do_align (psize, size);
547         }
548     }
549   *rsize = size;
550   data = GNUNET_malloc_large (size);
551   if (data == NULL)
552     {
553       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
554                            "malloc");
555       *rsize = 0;
556       *rdata = NULL;
557       return GNUNET_SYSERR;
558     }
559   *rdata = data;
560   memcpy (data, GNUNET_DIRECTORY_MAGIC, 8);
561   off = 8;
562
563   ret = GNUNET_CONTAINER_meta_data_serialize (bld->meta,
564                                               &data[off +
565                                                     sizeof (uint32_t)],
566                                               size - off - sizeof (uint32_t),
567                                               GNUNET_CONTAINER_META_DATA_SERIALIZE_FULL);
568   GNUNET_assert (ret != -1);
569   big = htonl (ret);  
570   memcpy (&data[8], &big, sizeof (uint32_t));
571   off += sizeof (uint32_t) + ret;
572   for (j = 0; j < bld->count; j++)
573     {
574       i = perm[j];
575       psize = off;
576       off += sizes[i];
577       off = do_align (psize, off);
578       memcpy (&data[off - sizes[i]], 
579               &(bes[i])[1],
580               sizes[i]);
581       GNUNET_free (bes[i]);
582     }
583   GNUNET_free_non_null (sizes);
584   GNUNET_free_non_null (perm);
585   GNUNET_free_non_null (bes);
586   GNUNET_assert (off == size);  
587   GNUNET_CONTAINER_meta_data_destroy (bld->meta);
588   GNUNET_free (bld);
589   return GNUNET_OK;
590 }
591
592
593 /* end of fs_directory.c */