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