fixing drq code
[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   mime = GNUNET_CONTAINER_meta_data_get_by_type (md, EXTRACTOR_METATYPE_MIMETYPE);
60   if (mime == NULL)
61     return GNUNET_SYSERR;
62   ret = (0 == strcmp (mime, GNUNET_FS_DIRECTORY_MIME)) ? GNUNET_YES : GNUNET_NO;
63   GNUNET_free (mime);
64   return ret; 
65 }
66
67
68 /**
69  * Set the MIMETYPE information for the given
70  * metadata to "application/gnunet-directory".
71  * 
72  * @param md metadata to add mimetype to
73  */
74 void
75 GNUNET_FS_meta_data_make_directory (struct GNUNET_CONTAINER_MetaData *md)
76 {
77   char *mime;
78   
79   mime = GNUNET_CONTAINER_meta_data_get_by_type (md, EXTRACTOR_METATYPE_MIMETYPE);
80   if (mime != NULL)
81     {
82       GNUNET_break (0 == strcmp (mime,
83                                  GNUNET_FS_DIRECTORY_MIME));
84       GNUNET_free (mime);
85       return;
86     }
87   GNUNET_CONTAINER_meta_data_insert (md, 
88                                      "<gnunet>",
89                                      EXTRACTOR_METATYPE_MIMETYPE,
90                                      EXTRACTOR_METAFORMAT_UTF8,
91                                      "text/plain",
92                                      GNUNET_FS_DIRECTORY_MIME,
93                                      strlen (GNUNET_FS_DIRECTORY_MIME)+1);
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_METATYPE_FILENAME);
229       file_data = GNUNET_CONTAINER_meta_data_get_by_type (md,
230                                                           EXTRACTOR_METATYPE_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   char *sptr;
326   size_t slen;
327   struct GNUNET_CONTAINER_MetaData *meta;
328   const struct GNUNET_CONTAINER_MetaData *meta_use;
329
330   GNUNET_assert (! GNUNET_FS_uri_test_ksk (uri));
331   if (NULL != data)
332     if (GNUNET_FS_uri_test_chk (uri))
333       fsize = GNUNET_FS_uri_chk_get_file_size (uri);
334     else
335       {
336         curi = GNUNET_FS_uri_loc_get_uri (uri);
337         fsize = GNUNET_FS_uri_chk_get_file_size (curi);
338         GNUNET_FS_uri_destroy (curi);
339       }
340   else
341     fsize = 0; /* not given */
342   if (fsize > MAX_INLINE_SIZE)
343     fsize = 0; /* too large */
344   uris = GNUNET_FS_uri_to_string (uri);
345   slen = strlen (uris) + 1;
346   mds =
347     GNUNET_CONTAINER_meta_data_get_serialized_size (md);  
348   meta_use = md;
349   meta = NULL;
350   if (fsize > 0)
351     {
352       meta = GNUNET_CONTAINER_meta_data_duplicate (md);
353       GNUNET_CONTAINER_meta_data_insert (meta,
354                                          "<gnunet>",                                     
355                                          EXTRACTOR_METATYPE_GNUNET_FULL_DATA,
356                                          EXTRACTOR_METAFORMAT_BINARY,
357                                          NULL,
358                                          data,
359                                          fsize);
360       mdxs =
361         GNUNET_CONTAINER_meta_data_get_serialized_size (meta);  
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   sptr = &ser[slen + sizeof(uint32_t)];
380   ret = GNUNET_CONTAINER_meta_data_serialize (meta_use,
381                                               &sptr,
382                                               mds,
383                                               GNUNET_CONTAINER_META_DATA_SERIALIZE_PART);
384   if (NULL != meta)
385     GNUNET_CONTAINER_meta_data_destroy (meta);
386   if (ret == -1)
387     mds = 0;
388   else
389     mds = ret;
390   big = htonl (mds);
391   memcpy (&ser[slen], &big, sizeof (uint32_t));
392   e->len = slen + sizeof (uint32_t) + mds;
393   e->next = bld->head;
394   bld->head = e;
395   bld->count++;
396 }
397
398
399 /**
400  * Given the start and end position of a block of
401  * data, return the end position of that data
402  * after alignment to the DBLOCK_SIZE.
403  */
404 static size_t
405 do_align (size_t start_position, 
406           size_t end_position)
407 {
408   size_t align;
409   
410   align = (end_position / DBLOCK_SIZE) * DBLOCK_SIZE;
411   if ((start_position < align) && (end_position > align))
412     return align + end_position - start_position;
413   return end_position;
414 }
415
416
417 /**
418  * Compute a permuation of the blocks to
419  * minimize the cost of alignment.  Greedy packer.
420  *
421  * @param start starting position for the first block
422  * @param count size of the two arrays
423  * @param sizes the sizes of the individual blocks
424  * @param perm the permutation of the blocks (updated)
425  */
426 static void
427 block_align (size_t start,
428              unsigned int count, 
429              const size_t *sizes,
430              unsigned int *perm)
431 {
432   unsigned int i;
433   unsigned int j;
434   unsigned int tmp;
435   unsigned int best;
436   ssize_t badness;
437   size_t cpos;
438   size_t cend;
439   ssize_t cbad;
440   unsigned int cval;
441
442   cpos = start;
443   for (i = 0; i < count; i++)
444     {
445       start = cpos;
446       badness = 0x7FFFFFFF;
447       best = -1;
448       for (j = i; j < count; j++)
449         {
450           cval = perm[j];
451           cend = cpos + sizes[cval];
452           if (cpos % DBLOCK_SIZE == 0)
453             {
454               /* prefer placing the largest blocks first */
455               cbad = -(cend % DBLOCK_SIZE);
456             }
457           else
458             {
459               if (cpos / DBLOCK_SIZE ==
460                   cend / DBLOCK_SIZE)
461                 {
462                   /* Data fits into the same block! Prefer small left-overs! */
463                   cbad =
464                     DBLOCK_SIZE - cend % DBLOCK_SIZE;
465                 }
466               else
467                 {
468                   /* Would have to waste space to re-align, add big factor, this
469                      case is a real loss (proportional to space wasted)! */
470                   cbad =
471                     DBLOCK_SIZE * (DBLOCK_SIZE -
472                                              cpos %
473                                              DBLOCK_SIZE);
474                 }
475             }
476           if (cbad < badness)
477             {
478               best = j;
479               badness = cbad;
480             }
481         }
482       tmp = perm[i];
483       perm[i] = perm[best];
484       perm[best] = tmp;
485       cpos += sizes[perm[i]];
486       cpos = do_align (start, cpos);
487     }
488 }
489
490
491 /**
492  * Finish building the directory.  Frees the
493  * builder context and returns the directory
494  * in-memory.
495  *
496  * @param bld directory to finish
497  * @param rsize set to the number of bytes needed
498  * @param rdata set to the encoded directory
499  * @return GNUNET_OK on success
500  */
501 int
502 GNUNET_FS_directory_builder_finish (struct GNUNET_FS_DirectoryBuilder *bld,
503                                     size_t *rsize,
504                                     void **rdata)
505 {
506   char *data;
507   char *sptr;
508   size_t *sizes;
509   unsigned int *perm;
510   unsigned int i;
511   unsigned int j;
512   struct BuilderEntry *pos;
513   struct BuilderEntry **bes;
514   size_t size;
515   size_t psize;
516   size_t off;
517   ssize_t ret;
518   uint32_t big;
519
520   size = 8 + sizeof (uint32_t);
521   size += GNUNET_CONTAINER_meta_data_get_serialized_size (bld->meta);
522   sizes = NULL;
523   perm = NULL;
524   bes = NULL;
525   if (0 < bld->count)
526     {
527       sizes = GNUNET_malloc (bld->count * sizeof (size_t));
528       perm = GNUNET_malloc (bld->count * sizeof (unsigned int));
529       bes = GNUNET_malloc (bld->count * sizeof (struct BuilderEntry *));
530       pos = bld->head;
531       for (i = 0; i < bld->count; i++)
532         {
533           perm[i] = i;
534           bes[i] = pos;
535           sizes[i] = pos->len;
536           pos = pos->next;
537         }
538       block_align (size,
539                    bld->count,
540                    sizes,
541                    perm);
542       /* compute final size with alignment */
543       for (i = 0; i < bld->count; i++)
544         {
545           psize = size;
546           size += sizes[perm[i]];
547           size = do_align (psize, size);
548         }
549     }
550   *rsize = size;
551   data = GNUNET_malloc_large (size);
552   if (data == NULL)
553     {
554       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
555                            "malloc");
556       *rsize = 0;
557       *rdata = NULL;
558       return GNUNET_SYSERR;
559     }
560   *rdata = data;
561   memcpy (data, GNUNET_DIRECTORY_MAGIC, 8);
562   off = 8;
563
564   sptr = &data[off + sizeof (uint32_t)];
565   ret = GNUNET_CONTAINER_meta_data_serialize (bld->meta,
566                                               &sptr,
567                                               size - off - sizeof (uint32_t),
568                                               GNUNET_CONTAINER_META_DATA_SERIALIZE_FULL);
569   GNUNET_assert (ret != -1);
570   big = htonl (ret);  
571   memcpy (&data[8], &big, sizeof (uint32_t));
572   off += sizeof (uint32_t) + ret;
573   for (j = 0; j < bld->count; j++)
574     {
575       i = perm[j];
576       psize = off;
577       off += sizes[i];
578       off = do_align (psize, off);
579       memcpy (&data[off - sizes[i]], 
580               &(bes[i])[1],
581               sizes[i]);
582       GNUNET_free (bes[i]);
583     }
584   GNUNET_free_non_null (sizes);
585   GNUNET_free_non_null (perm);
586   GNUNET_free_non_null (bes);
587   GNUNET_assert (off == size);  
588   GNUNET_CONTAINER_meta_data_destroy (bld->meta);
589   GNUNET_free (bld);
590   return GNUNET_OK;
591 }
592
593
594 /* end of fs_directory.c */