fixing common off-by-one error with respect to maximum message size
[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  */
183 void 
184 GNUNET_FS_directory_list_contents (size_t size,
185                                    const void *data,
186                                    uint64_t offset,
187                                    GNUNET_FS_DirectoryEntryProcessor dep, 
188                                    void *dep_cls)
189 {
190   struct GetFullDataClosure full_data;
191   const char *cdata = data;
192   char *emsg;
193   uint64_t pos;
194   uint64_t align;
195   uint32_t mdSize;
196   uint64_t epos;
197   struct GNUNET_FS_Uri *uri;
198   struct GNUNET_CONTAINER_MetaData *md;
199   char *filename;
200
201   pos = offset;
202   if ( (pos == 0) && 
203        (size >= 8 + sizeof (uint32_t)) &&
204        (0 == memcmp (cdata, GNUNET_FS_DIRECTORY_MAGIC, 8)) )
205     {
206       memcpy (&mdSize, &cdata[8], sizeof (uint32_t));
207       mdSize = ntohl (mdSize);
208       if (mdSize > size - 8 - sizeof (uint32_t))
209         {
210           /* invalid size */
211           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
212                       _("Not a GNUnet directory.\n"));
213           return;
214         }
215       md = GNUNET_CONTAINER_meta_data_deserialize (&cdata[8 +
216                                                          sizeof (uint32_t)],
217                                                    mdSize);
218       if (md == NULL)
219         {
220           GNUNET_break (0);
221           return; /* malformed ! */
222         }
223       dep (dep_cls,
224            NULL,
225            NULL,                                
226            md,
227            0,
228            NULL);
229       GNUNET_CONTAINER_meta_data_destroy (md);
230       pos = 8 + sizeof (uint32_t) + mdSize;
231     }
232   while (pos < size)
233     {
234       /* find end of URI */
235       if (cdata[pos] == '\0')
236         {
237           /* URI is never empty, must be end of block,
238              skip to next alignment */
239           align =
240             ((pos / DBLOCK_SIZE) + 1) * DBLOCK_SIZE;
241           if (align == pos)
242             {
243               /* if we were already aligned, still skip a block! */
244               align += DBLOCK_SIZE;
245             }
246           pos = align;
247           if (pos >= size)
248             {
249               /* malformed - or partial download... */
250               break;
251             }
252         }
253       epos = pos;
254       while ((epos < size) && (cdata[epos] != '\0'))
255         epos++;
256       if (epos >= size)
257         return;   /* malformed - or partial download */
258       
259       uri = GNUNET_FS_uri_parse (&cdata[pos], &emsg);
260       pos = epos + 1;
261       if (uri == NULL)
262         {
263           GNUNET_free (emsg);
264           pos--;                /* go back to '\0' to force going to next alignment */
265           continue;
266         }
267       if (GNUNET_FS_uri_test_ksk (uri))
268         {
269           GNUNET_FS_uri_destroy (uri);
270           GNUNET_break (0);
271           return; /* illegal in directory! */
272         }
273
274       memcpy (&mdSize, &cdata[pos], sizeof (uint32_t));
275       mdSize = ntohl (mdSize);
276       pos += sizeof (uint32_t);
277       if (pos + mdSize > size)
278         {
279           GNUNET_FS_uri_destroy (uri);
280           return; /* malformed - or partial download */
281         }
282
283       md = GNUNET_CONTAINER_meta_data_deserialize (&cdata[pos], mdSize);
284       if (md == NULL)
285         {
286           GNUNET_FS_uri_destroy (uri);
287           GNUNET_break (0);
288           return; /* malformed ! */
289         }
290       pos += mdSize;
291       filename = GNUNET_CONTAINER_meta_data_get_by_type (md,
292                                                          EXTRACTOR_METATYPE_FILENAME);
293       full_data.size = 0;
294       full_data.data = NULL;
295       GNUNET_CONTAINER_meta_data_iterate (md,
296                                           &find_full_data,
297                                           &full_data);
298       if (dep != NULL) 
299         {
300           dep (dep_cls,
301                filename,
302                uri,
303                md,
304                full_data.size,
305                full_data.data);
306         }
307       GNUNET_free_non_null (full_data.data);
308       GNUNET_free_non_null (filename);
309       GNUNET_CONTAINER_meta_data_destroy (md);
310       GNUNET_FS_uri_destroy (uri);
311     }
312 }
313
314 /**
315  * Entries in the directory (builder).
316  */
317 struct BuilderEntry
318 {
319   /**
320    * This is a linked list.
321    */
322   struct BuilderEntry *next;
323   
324   /**
325    * Length of this entry.
326    */
327   size_t len;
328 };
329
330 /**
331  * Internal state of a directory builder.
332  */
333 struct GNUNET_FS_DirectoryBuilder
334 {
335   /**
336    * Meta-data for the directory itself.
337    */
338   struct GNUNET_CONTAINER_MetaData *meta;
339
340   /**
341    * Head of linked list of entries.
342    */
343   struct BuilderEntry *head;
344
345   /**
346    * Number of entires in the directory.
347    */
348   unsigned int count;
349 };
350
351
352 /**
353  * Create a directory builder.
354  * 
355  * @param mdir metadata for the directory
356  */
357 struct GNUNET_FS_DirectoryBuilder *
358 GNUNET_FS_directory_builder_create (const struct GNUNET_CONTAINER_MetaData *mdir)
359 {
360   struct GNUNET_FS_DirectoryBuilder *ret;
361
362   ret = GNUNET_malloc(sizeof(struct GNUNET_FS_DirectoryBuilder));
363   if (mdir != NULL)
364     ret->meta = GNUNET_CONTAINER_meta_data_duplicate (mdir);
365   else
366     ret->meta = GNUNET_CONTAINER_meta_data_create ();
367   GNUNET_FS_meta_data_make_directory (ret->meta);
368   return ret;
369 }
370
371
372 /**
373  * Add an entry to a directory.
374  * 
375  * @param bld directory to extend
376  * @param uri uri of the entry (must not be a KSK)
377  * @param md metadata of the entry
378  * @param data raw data of the entry, can be NULL, otherwise
379  *        data must point to exactly the number of bytes specified
380  *        by the uri which must be of type LOC or CHK
381  */
382 void
383 GNUNET_FS_directory_builder_add (struct GNUNET_FS_DirectoryBuilder *bld,
384                                  const struct GNUNET_FS_Uri *uri,
385                                  const struct GNUNET_CONTAINER_MetaData *md,
386                                  const void *data)
387 {
388   struct GNUNET_FS_Uri *curi;
389   struct BuilderEntry *e;
390   uint64_t fsize;
391   uint32_t big;
392   ssize_t ret;
393   size_t mds;
394   size_t mdxs;
395   char *uris;
396   char *ser;
397   char *sptr;
398   size_t slen;
399   struct GNUNET_CONTAINER_MetaData *meta;
400   const struct GNUNET_CONTAINER_MetaData *meta_use;
401
402   GNUNET_assert (! GNUNET_FS_uri_test_ksk (uri));
403   if (NULL != data)
404     {
405       GNUNET_assert (! GNUNET_FS_uri_test_sks (uri));
406       if (GNUNET_FS_uri_test_chk (uri))
407         {
408           fsize = GNUNET_FS_uri_chk_get_file_size (uri);
409         }
410       else
411         {
412           curi = GNUNET_FS_uri_loc_get_uri (uri);
413           GNUNET_assert (NULL != curi);
414           fsize = GNUNET_FS_uri_chk_get_file_size (curi);
415           GNUNET_FS_uri_destroy (curi);
416         }
417     }
418   else
419     {
420       fsize = 0; /* not given */
421     }
422   if (fsize > MAX_INLINE_SIZE)
423     fsize = 0; /* too large */
424   uris = GNUNET_FS_uri_to_string (uri);
425   slen = strlen (uris) + 1;
426   mds =
427     GNUNET_CONTAINER_meta_data_get_serialized_size (md);  
428   meta_use = md;
429   meta = NULL;
430   if (fsize > 0)
431     {
432       meta = GNUNET_CONTAINER_meta_data_duplicate (md);
433       GNUNET_CONTAINER_meta_data_insert (meta,
434                                          "<gnunet>",                                     
435                                          EXTRACTOR_METATYPE_GNUNET_FULL_DATA,
436                                          EXTRACTOR_METAFORMAT_BINARY,
437                                          NULL,
438                                          data,
439                                          fsize);
440       mdxs =
441         GNUNET_CONTAINER_meta_data_get_serialized_size (meta);  
442       if ( (slen + sizeof (uint32_t) + mdxs - 1) / DBLOCK_SIZE ==
443            (slen + sizeof (uint32_t) + mds - 1) / DBLOCK_SIZE)
444         {
445           /* adding full data would not cause us to cross
446              additional blocks, so add it! */
447           meta_use = meta;
448           mds = mdxs;
449         }
450     }
451
452   if (mds > GNUNET_MAX_MALLOC_CHECKED / 2)
453     mds = GNUNET_MAX_MALLOC_CHECKED / 2;
454   e = GNUNET_malloc (sizeof(struct BuilderEntry) + 
455                      slen + mds + sizeof (uint32_t));
456   ser = (char*) &e[1];
457   memcpy (ser, uris, slen);
458   GNUNET_free (uris);
459   sptr = &ser[slen + sizeof(uint32_t)];
460   ret = GNUNET_CONTAINER_meta_data_serialize (meta_use,
461                                               &sptr,
462                                               mds,
463                                               GNUNET_CONTAINER_META_DATA_SERIALIZE_PART);
464   if (NULL != meta)
465     GNUNET_CONTAINER_meta_data_destroy (meta);
466   if (ret == -1)
467     mds = 0;
468   else
469     mds = ret;
470   big = htonl (mds);
471   memcpy (&ser[slen], &big, sizeof (uint32_t));
472   e->len = slen + sizeof (uint32_t) + mds;
473   e->next = bld->head;
474   bld->head = e;
475   bld->count++;
476 }
477
478
479 /**
480  * Given the start and end position of a block of
481  * data, return the end position of that data
482  * after alignment to the DBLOCK_SIZE.
483  */
484 static size_t
485 do_align (size_t start_position, 
486           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,
508              unsigned int count, 
509              const size_t *sizes,
510              unsigned int *perm)
511 {
512   unsigned int i;
513   unsigned int j;
514   unsigned int tmp;
515   unsigned int best;
516   ssize_t badness;
517   size_t cpos;
518   size_t cend;
519   ssize_t cbad;
520   unsigned int cval;
521
522   cpos = start;
523   for (i = 0; i < count; i++)
524     {
525       start = cpos;
526       badness = 0x7FFFFFFF;
527       best = -1;
528       for (j = i; j < count; j++)
529         {
530           cval = perm[j];
531           cend = cpos + sizes[cval];
532           if (cpos % DBLOCK_SIZE == 0)
533             {
534               /* prefer placing the largest blocks first */
535               cbad = -(cend % DBLOCK_SIZE);
536             }
537           else
538             {
539               if (cpos / DBLOCK_SIZE ==
540                   cend / DBLOCK_SIZE)
541                 {
542                   /* Data fits into the same block! Prefer small left-overs! */
543                   cbad =
544                     DBLOCK_SIZE - cend % DBLOCK_SIZE;
545                 }
546               else
547                 {
548                   /* Would have to waste space to re-align, add big factor, this
549                      case is a real loss (proportional to space wasted)! */
550                   cbad =
551                     DBLOCK_SIZE * (DBLOCK_SIZE -
552                                              cpos %
553                                              DBLOCK_SIZE);
554                 }
555             }
556           if (cbad < badness)
557             {
558               best = j;
559               badness = cbad;
560             }
561         }
562       GNUNET_assert (best != -1);
563       tmp = perm[i];
564       perm[i] = perm[best];
565       perm[best] = tmp;
566       cpos += sizes[perm[i]];
567       cpos = do_align (start, cpos);
568     }
569 }
570
571
572 /**
573  * Finish building the directory.  Frees the
574  * builder context and returns the directory
575  * in-memory.
576  *
577  * @param bld directory to finish
578  * @param rsize set to the number of bytes needed
579  * @param rdata set to the encoded directory
580  * @return GNUNET_OK on success
581  */
582 int
583 GNUNET_FS_directory_builder_finish (struct GNUNET_FS_DirectoryBuilder *bld,
584                                     size_t *rsize,
585                                     void **rdata)
586 {
587   char *data;
588   char *sptr;
589   size_t *sizes;
590   unsigned int *perm;
591   unsigned int i;
592   unsigned int j;
593   struct BuilderEntry *pos;
594   struct BuilderEntry **bes;
595   size_t size;
596   size_t psize;
597   size_t off;
598   ssize_t ret;
599   uint32_t big;
600
601   size = strlen (GNUNET_DIRECTORY_MAGIC) + sizeof (uint32_t);
602   size += GNUNET_CONTAINER_meta_data_get_serialized_size (bld->meta);
603   sizes = NULL;
604   perm = NULL;
605   bes = NULL;
606   if (0 < bld->count)
607     {
608       sizes = GNUNET_malloc (bld->count * sizeof (size_t));
609       perm = GNUNET_malloc (bld->count * sizeof (unsigned int));
610       bes = GNUNET_malloc (bld->count * sizeof (struct BuilderEntry *));
611       pos = bld->head;
612       for (i = 0; i < bld->count; i++)
613         {
614           perm[i] = i;
615           bes[i] = pos;
616           sizes[i] = pos->len;
617           pos = pos->next;
618         }
619       block_align (size,
620                    bld->count,
621                    sizes,
622                    perm);
623       /* compute final size with alignment */
624       for (i = 0; i < bld->count; i++)
625         {
626           psize = size;
627           size += sizes[perm[i]];
628           size = do_align (psize, size);
629         }
630     }
631   *rsize = size;
632   data = GNUNET_malloc_large (size);
633   if (data == NULL)
634     {
635       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
636                            "malloc");
637       *rsize = 0;
638       *rdata = NULL;
639       GNUNET_free_non_null (sizes);
640       GNUNET_free_non_null (perm);
641       GNUNET_free_non_null (bes);
642       return GNUNET_SYSERR;
643     }
644   *rdata = data;
645   memcpy (data, GNUNET_DIRECTORY_MAGIC, strlen (GNUNET_DIRECTORY_MAGIC));
646   off = strlen (GNUNET_DIRECTORY_MAGIC);
647
648   sptr = &data[off + sizeof (uint32_t)];
649   ret = GNUNET_CONTAINER_meta_data_serialize (bld->meta,
650                                               &sptr,
651                                               size - off - sizeof (uint32_t),
652                                               GNUNET_CONTAINER_META_DATA_SERIALIZE_FULL);
653   GNUNET_assert (ret != -1);
654   big = htonl (ret);  
655   memcpy (&data[off], &big, sizeof (uint32_t));
656   off += sizeof (uint32_t) + ret;
657   for (j = 0; j < bld->count; j++)
658     {
659       i = perm[j];
660       psize = off;
661       off += sizes[i];
662       off = do_align (psize, off);
663       memcpy (&data[off - sizes[i]], 
664               &(bes[i])[1],
665               sizes[i]);
666       GNUNET_free (bes[i]);
667     }
668   GNUNET_free_non_null (sizes);
669   GNUNET_free_non_null (perm);
670   GNUNET_free_non_null (bes);
671   GNUNET_assert (off == size);  
672   GNUNET_CONTAINER_meta_data_destroy (bld->meta);
673   GNUNET_free (bld);
674   return GNUNET_OK;
675 }
676
677
678 /* end of fs_directory.c */