03065958e20413e83db4c70282821aaf64ec388d
[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 /**
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 GNUNET_CONTAINER_MetaData *md)
55 {
56   char *mime;
57   int ret;
58   
59   if (NULL == md)
60     return GNUNET_SYSERR;
61   mime = GNUNET_CONTAINER_meta_data_get_by_type (md, EXTRACTOR_METATYPE_MIMETYPE);
62   if (mime == NULL)
63     return GNUNET_SYSERR;
64   ret = (0 == strcmp (mime, GNUNET_FS_DIRECTORY_MIME)) ? GNUNET_YES : GNUNET_NO;
65   GNUNET_free (mime);
66   return ret; 
67 }
68
69
70 /**
71  * Set the MIMETYPE information for the given
72  * metadata to "application/gnunet-directory".
73  * 
74  * @param md metadata to add mimetype to
75  */
76 void
77 GNUNET_FS_meta_data_make_directory (struct GNUNET_CONTAINER_MetaData *md)
78 {
79   char *mime;
80   
81   mime = GNUNET_CONTAINER_meta_data_get_by_type (md, EXTRACTOR_METATYPE_MIMETYPE);
82   if (mime != NULL)
83     {
84       GNUNET_break (0 == strcmp (mime,
85                                  GNUNET_FS_DIRECTORY_MIME));
86       GNUNET_free (mime);
87       return;
88     }
89   GNUNET_CONTAINER_meta_data_insert (md, 
90                                      "<gnunet>",
91                                      EXTRACTOR_METATYPE_MIMETYPE,
92                                      EXTRACTOR_METAFORMAT_UTF8,
93                                      "text/plain",
94                                      GNUNET_FS_DIRECTORY_MIME,
95                                      strlen (GNUNET_FS_DIRECTORY_MIME)+1);
96 }
97
98
99 /**
100  * Closure for 'find_full_data'.
101  */
102 struct GetFullDataClosure 
103 {
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,
136                 const char *plugin_name,
137                 enum EXTRACTOR_MetaType type,
138                 enum EXTRACTOR_MetaFormat format,
139                 const char *data_mime_type,
140                 const char *data,
141                 size_t data_len)
142 {
143   struct GetFullDataClosure *gfdc = cls;
144
145   if (type == EXTRACTOR_METATYPE_GNUNET_FULL_DATA)
146     {
147       gfdc->size = data_len;
148       if (data_len > 0)
149         {
150           gfdc->data = GNUNET_malloc (data_len);
151           memcpy (gfdc->data,
152                   data,
153                   data_len);
154         }
155       return 1;
156     }
157   return 0;
158 }
159
160
161 /**
162  * Iterate over all entries in a directory.  Note that directories
163  * are structured such that it is possible to iterate over the
164  * individual blocks as well as over the entire directory.  Thus
165  * a client can call this function on the buffer in the
166  * GNUNET_FS_ProgressCallback.  Also, directories can optionally
167  * include the contents of (small) files embedded in the directory
168  * itself; for those files, the processor may be given the
169  * contents of the file directly by this function.
170  * <p>
171  *
172  * Note that this function maybe called on parts of directories.  Thus
173  * parser errors should not be reported _at all_ (with GNUNET_break).
174  * Still, if some entries can be recovered despite these parsing
175  * errors, the function should try to do this.
176  *
177  * @param size number of bytes in data
178  * @param data pointer to the beginning of the directory
179  * @param offset offset of data in the directory
180  * @param dep function to call on each entry
181  * @param dep_cls closure for dep
182  * @return GNUNET_OK if this could be a block in a directory,
183  *         GNUNET_NO if this could be part of a directory (but not 100% OK)
184  *         GNUNET_SYSERR if 'data' does not represent a directory
185  */
186 int 
187 GNUNET_FS_directory_list_contents (size_t size,
188                                    const void *data,
189                                    uint64_t offset,
190                                    GNUNET_FS_DirectoryEntryProcessor dep, 
191                                    void *dep_cls)
192 {
193   struct GetFullDataClosure full_data;
194   const char *cdata = data;
195   char *emsg;
196   uint64_t pos;
197   uint64_t align;
198   uint32_t mdSize;
199   uint64_t epos;
200   struct GNUNET_FS_Uri *uri;
201   struct GNUNET_CONTAINER_MetaData *md;
202   char *filename;
203
204   pos = offset;
205   if ( (pos == 0) && 
206        (size >= 8 + sizeof (uint32_t)) &&
207        (0 == memcmp (cdata, GNUNET_FS_DIRECTORY_MAGIC, 8)) )
208     {
209       memcpy (&mdSize, &cdata[8], 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 +
219                                                          sizeof (uint32_t)],
220                                                    mdSize);
221       if (md == NULL)
222         {
223           GNUNET_break (0);
224           return GNUNET_SYSERR; /* malformed ! */
225         }
226       dep (dep_cls,
227            NULL,
228            NULL,                                
229            md,
230            0,
231            NULL);
232       GNUNET_CONTAINER_meta_data_destroy (md);
233       pos = 8 + sizeof (uint32_t) + mdSize;
234     }
235   while (pos < size)
236     {
237       /* find end of URI */
238       if (cdata[pos] == '\0')
239         {
240           /* URI is never empty, must be end of block,
241              skip to next alignment */
242           align =
243             ((pos / DBLOCK_SIZE) + 1) * DBLOCK_SIZE;
244           if (align == pos)
245             {
246               /* if we were already aligned, still skip a block! */
247               align += DBLOCK_SIZE;
248             }
249           pos = align;
250           if (pos >= size)
251             {
252               /* malformed - or partial download... */
253               break;
254             }
255         }
256       epos = pos;
257       while ((epos < size) && (cdata[epos] != '\0'))
258         epos++;
259       if (epos >= size)
260         return GNUNET_NO;   /* malformed - or partial download */
261       
262       uri = GNUNET_FS_uri_parse (&cdata[pos], &emsg);
263       pos = epos + 1;
264       if (uri == NULL)
265         {
266           GNUNET_free (emsg);
267           pos--;                /* go back to '\0' to force going to next alignment */
268           continue;
269         }
270       if (GNUNET_FS_uri_test_ksk (uri))
271         {
272           GNUNET_FS_uri_destroy (uri);
273           GNUNET_break (0);
274           return GNUNET_NO; /* illegal in directory! */
275         }
276
277       memcpy (&mdSize, &cdata[pos], 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], mdSize);
287       if (md == NULL)
288         {
289           GNUNET_FS_uri_destroy (uri);
290           GNUNET_break (0);
291           return GNUNET_NO; /* malformed ! */
292         }
293       pos += mdSize;
294       filename = GNUNET_CONTAINER_meta_data_get_by_type (md,
295                                                          EXTRACTOR_METATYPE_FILENAME);
296       full_data.size = 0;
297       full_data.data = NULL;
298       GNUNET_CONTAINER_meta_data_iterate (md,
299                                           &find_full_data,
300                                           &full_data);
301       if (dep != NULL) 
302         {
303           dep (dep_cls,
304                filename,
305                uri,
306                md,
307                full_data.size,
308                full_data.data);
309         }
310       GNUNET_free_non_null (full_data.data);
311       GNUNET_free_non_null (filename);
312       GNUNET_CONTAINER_meta_data_destroy (md);
313       GNUNET_FS_uri_destroy (uri);
314     }
315   return GNUNET_OK;
316 }
317
318 /**
319  * Entries in the directory (builder).
320  */
321 struct BuilderEntry
322 {
323   /**
324    * This is a linked list.
325    */
326   struct BuilderEntry *next;
327   
328   /**
329    * Length of this entry.
330    */
331   size_t len;
332 };
333
334 /**
335  * Internal state of a directory builder.
336  */
337 struct GNUNET_FS_DirectoryBuilder
338 {
339   /**
340    * Meta-data for the directory itself.
341    */
342   struct GNUNET_CONTAINER_MetaData *meta;
343
344   /**
345    * Head of linked list of entries.
346    */
347   struct BuilderEntry *head;
348
349   /**
350    * Number of entires in the directory.
351    */
352   unsigned int count;
353 };
354
355
356 /**
357  * Create a directory builder.
358  * 
359  * @param mdir metadata for the directory
360  */
361 struct GNUNET_FS_DirectoryBuilder *
362 GNUNET_FS_directory_builder_create (const struct GNUNET_CONTAINER_MetaData *mdir)
363 {
364   struct GNUNET_FS_DirectoryBuilder *ret;
365
366   ret = GNUNET_malloc(sizeof(struct GNUNET_FS_DirectoryBuilder));
367   if (mdir != NULL)
368     ret->meta = GNUNET_CONTAINER_meta_data_duplicate (mdir);
369   else
370     ret->meta = GNUNET_CONTAINER_meta_data_create ();
371   GNUNET_FS_meta_data_make_directory (ret->meta);
372   return ret;
373 }
374
375
376 /**
377  * Add an entry to a directory.
378  * 
379  * @param bld directory to extend
380  * @param uri uri of the entry (must not be a KSK)
381  * @param md metadata of the entry
382  * @param data raw data of the entry, can be NULL, otherwise
383  *        data must point to exactly the number of bytes specified
384  *        by the uri which must be of type LOC or CHK
385  */
386 void
387 GNUNET_FS_directory_builder_add (struct GNUNET_FS_DirectoryBuilder *bld,
388                                  const struct GNUNET_FS_Uri *uri,
389                                  const struct GNUNET_CONTAINER_MetaData *md,
390                                  const void *data)
391 {
392   struct GNUNET_FS_Uri *curi;
393   struct BuilderEntry *e;
394   uint64_t fsize;
395   uint32_t big;
396   ssize_t ret;
397   size_t mds;
398   size_t mdxs;
399   char *uris;
400   char *ser;
401   char *sptr;
402   size_t slen;
403   struct GNUNET_CONTAINER_MetaData *meta;
404   const struct GNUNET_CONTAINER_MetaData *meta_use;
405
406   GNUNET_assert (! GNUNET_FS_uri_test_ksk (uri));
407   if (NULL != data)
408     {
409       GNUNET_assert (! GNUNET_FS_uri_test_sks (uri));
410       if (GNUNET_FS_uri_test_chk (uri))
411         {
412           fsize = GNUNET_FS_uri_chk_get_file_size (uri);
413         }
414       else
415         {
416           curi = GNUNET_FS_uri_loc_get_uri (uri);
417           GNUNET_assert (NULL != curi);
418           fsize = GNUNET_FS_uri_chk_get_file_size (curi);
419           GNUNET_FS_uri_destroy (curi);
420         }
421     }
422   else
423     {
424       fsize = 0; /* not given */
425     }
426   if (fsize > MAX_INLINE_SIZE)
427     fsize = 0; /* too large */
428   uris = GNUNET_FS_uri_to_string (uri);
429   slen = strlen (uris) + 1;
430   mds =
431     GNUNET_CONTAINER_meta_data_get_serialized_size (md);  
432   meta_use = md;
433   meta = NULL;
434   if (fsize > 0)
435     {
436       meta = GNUNET_CONTAINER_meta_data_duplicate (md);
437       GNUNET_CONTAINER_meta_data_insert (meta,
438                                          "<gnunet>",                                     
439                                          EXTRACTOR_METATYPE_GNUNET_FULL_DATA,
440                                          EXTRACTOR_METAFORMAT_BINARY,
441                                          NULL,
442                                          data,
443                                          fsize);
444       mdxs =
445         GNUNET_CONTAINER_meta_data_get_serialized_size (meta);  
446       if ( (slen + sizeof (uint32_t) + mdxs - 1) / DBLOCK_SIZE ==
447            (slen + sizeof (uint32_t) + mds - 1) / DBLOCK_SIZE)
448         {
449           /* adding full data would not cause us to cross
450              additional blocks, so add it! */
451           meta_use = meta;
452           mds = mdxs;
453         }
454     }
455
456   if (mds > GNUNET_MAX_MALLOC_CHECKED / 2)
457     mds = GNUNET_MAX_MALLOC_CHECKED / 2;
458   e = GNUNET_malloc (sizeof(struct BuilderEntry) + 
459                      slen + mds + sizeof (uint32_t));
460   ser = (char*) &e[1];
461   memcpy (ser, uris, slen);
462   GNUNET_free (uris);
463   sptr = &ser[slen + sizeof(uint32_t)];
464   ret = GNUNET_CONTAINER_meta_data_serialize (meta_use,
465                                               &sptr,
466                                               mds,
467                                               GNUNET_CONTAINER_META_DATA_SERIALIZE_PART);
468   if (NULL != meta)
469     GNUNET_CONTAINER_meta_data_destroy (meta);
470   if (ret == -1)
471     mds = 0;
472   else
473     mds = ret;
474   big = htonl (mds);
475   memcpy (&ser[slen], &big, sizeof (uint32_t));
476   e->len = slen + sizeof (uint32_t) + mds;
477   e->next = bld->head;
478   bld->head = e;
479   bld->count++;
480 }
481
482
483 /**
484  * Given the start and end position of a block of
485  * data, return the end position of that data
486  * after alignment to the DBLOCK_SIZE.
487  */
488 static size_t
489 do_align (size_t start_position, 
490           size_t end_position)
491 {
492   size_t align;
493   
494   align = (end_position / DBLOCK_SIZE) * DBLOCK_SIZE;
495   if ((start_position < align) && (end_position > align))
496     return align + end_position - start_position;
497   return end_position;
498 }
499
500
501 /**
502  * Compute a permuation of the blocks to
503  * minimize the cost of alignment.  Greedy packer.
504  *
505  * @param start starting position for the first block
506  * @param count size of the two arrays
507  * @param sizes the sizes of the individual blocks
508  * @param perm the permutation of the blocks (updated)
509  */
510 static void
511 block_align (size_t start,
512              unsigned int count, 
513              const size_t *sizes,
514              unsigned int *perm)
515 {
516   unsigned int i;
517   unsigned int j;
518   unsigned int tmp;
519   unsigned int best;
520   ssize_t badness;
521   size_t cpos;
522   size_t cend;
523   ssize_t cbad;
524   unsigned int cval;
525
526   cpos = start;
527   for (i = 0; i < count; i++)
528     {
529       start = cpos;
530       badness = 0x7FFFFFFF;
531       best = -1;
532       for (j = i; j < count; j++)
533         {
534           cval = perm[j];
535           cend = cpos + sizes[cval];
536           if (cpos % DBLOCK_SIZE == 0)
537             {
538               /* prefer placing the largest blocks first */
539               cbad = -(cend % DBLOCK_SIZE);
540             }
541           else
542             {
543               if (cpos / DBLOCK_SIZE ==
544                   cend / DBLOCK_SIZE)
545                 {
546                   /* Data fits into the same block! Prefer small left-overs! */
547                   cbad =
548                     DBLOCK_SIZE - cend % DBLOCK_SIZE;
549                 }
550               else
551                 {
552                   /* Would have to waste space to re-align, add big factor, this
553                      case is a real loss (proportional to space wasted)! */
554                   cbad =
555                     DBLOCK_SIZE * (DBLOCK_SIZE -
556                                              cpos %
557                                              DBLOCK_SIZE);
558                 }
559             }
560           if (cbad < badness)
561             {
562               best = j;
563               badness = cbad;
564             }
565         }
566       GNUNET_assert (best != -1);
567       tmp = perm[i];
568       perm[i] = perm[best];
569       perm[best] = tmp;
570       cpos += sizes[perm[i]];
571       cpos = do_align (start, cpos);
572     }
573 }
574
575
576 /**
577  * Finish building the directory.  Frees the
578  * builder context and returns the directory
579  * in-memory.
580  *
581  * @param bld directory to finish
582  * @param rsize set to the number of bytes needed
583  * @param rdata set to the encoded directory
584  * @return GNUNET_OK on success
585  */
586 int
587 GNUNET_FS_directory_builder_finish (struct GNUNET_FS_DirectoryBuilder *bld,
588                                     size_t *rsize,
589                                     void **rdata)
590 {
591   char *data;
592   char *sptr;
593   size_t *sizes;
594   unsigned int *perm;
595   unsigned int i;
596   unsigned int j;
597   struct BuilderEntry *pos;
598   struct BuilderEntry **bes;
599   size_t size;
600   size_t psize;
601   size_t off;
602   ssize_t ret;
603   uint32_t big;
604
605   size = strlen (GNUNET_DIRECTORY_MAGIC) + sizeof (uint32_t);
606   size += GNUNET_CONTAINER_meta_data_get_serialized_size (bld->meta);
607   sizes = NULL;
608   perm = NULL;
609   bes = NULL;
610   if (0 < bld->count)
611     {
612       sizes = GNUNET_malloc (bld->count * sizeof (size_t));
613       perm = GNUNET_malloc (bld->count * sizeof (unsigned int));
614       bes = GNUNET_malloc (bld->count * sizeof (struct BuilderEntry *));
615       pos = bld->head;
616       for (i = 0; i < bld->count; i++)
617         {
618           perm[i] = i;
619           bes[i] = pos;
620           sizes[i] = pos->len;
621           pos = pos->next;
622         }
623       block_align (size,
624                    bld->count,
625                    sizes,
626                    perm);
627       /* compute final size with alignment */
628       for (i = 0; i < bld->count; i++)
629         {
630           psize = size;
631           size += sizes[perm[i]];
632           size = do_align (psize, size);
633         }
634     }
635   *rsize = size;
636   data = GNUNET_malloc_large (size);
637   if (data == NULL)
638     {
639       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
640                            "malloc");
641       *rsize = 0;
642       *rdata = NULL;
643       GNUNET_free_non_null (sizes);
644       GNUNET_free_non_null (perm);
645       GNUNET_free_non_null (bes);
646       return GNUNET_SYSERR;
647     }
648   *rdata = data;
649   memcpy (data, GNUNET_DIRECTORY_MAGIC, strlen (GNUNET_DIRECTORY_MAGIC));
650   off = strlen (GNUNET_DIRECTORY_MAGIC);
651
652   sptr = &data[off + sizeof (uint32_t)];
653   ret = GNUNET_CONTAINER_meta_data_serialize (bld->meta,
654                                               &sptr,
655                                               size - off - sizeof (uint32_t),
656                                               GNUNET_CONTAINER_META_DATA_SERIALIZE_FULL);
657   GNUNET_assert (ret != -1);
658   big = htonl (ret);  
659   memcpy (&data[off], &big, sizeof (uint32_t));
660   off += sizeof (uint32_t) + ret;
661   for (j = 0; j < bld->count; j++)
662     {
663       i = perm[j];
664       psize = off;
665       off += sizes[i];
666       off = do_align (psize, off);
667       memcpy (&data[off - sizes[i]], 
668               &(bes[i])[1],
669               sizes[i]);
670       GNUNET_free (bes[i]);
671     }
672   GNUNET_free_non_null (sizes);
673   GNUNET_free_non_null (perm);
674   GNUNET_free_non_null (bes);
675   GNUNET_assert (off == size);  
676   GNUNET_CONTAINER_meta_data_destroy (bld->meta);
677   GNUNET_free (bld);
678   return GNUNET_OK;
679 }
680
681
682 /* end of fs_directory.c */