error handling
[oweals/gnunet.git] / src / util / configuration.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2006, 2007, 2008, 2009, 2013, 2020 GNUnet e.V.
4
5      GNUnet is free software: you can redistribute it and/or modify it
6      under the terms of the GNU Affero General Public License as published
7      by the Free Software Foundation, either version 3 of the License,
8      or (at your 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      Affero General Public License for more details.
14
15      You should have received a copy of the GNU Affero General Public License
16      along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18      SPDX-License-Identifier: AGPL3.0-or-later
19  */
20 /**
21  * @file src/util/configuration.c
22  * @brief configuration management
23  * @author Christian Grothoff
24  */
25 #include "platform.h"
26 #include "gnunet_crypto_lib.h"
27 #include "gnunet_strings_lib.h"
28 #include "gnunet_os_lib.h"
29 #include "gnunet_configuration_lib.h"
30 #include "gnunet_disk_lib.h"
31
32 #define LOG(kind, ...) GNUNET_log_from (kind, "util", __VA_ARGS__)
33
34 #define LOG_STRERROR_FILE(kind, syscall, filename) \
35   GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
36
37 /**
38  * @brief configuration entry
39  */
40 struct ConfigEntry
41 {
42   /**
43    * This is a linked list.
44    */
45   struct ConfigEntry *next;
46
47   /**
48    * key for this entry
49    */
50   char *key;
51
52   /**
53    * current, commited value
54    */
55   char *val;
56 };
57
58
59 /**
60  * @brief configuration section
61  */
62 struct ConfigSection
63 {
64   /**
65    * This is a linked list.
66    */
67   struct ConfigSection *next;
68
69   /**
70    * entries in the section
71    */
72   struct ConfigEntry *entries;
73
74   /**
75    * name of the section
76    */
77   char *name;
78 };
79
80
81 /**
82  * @brief configuration data
83  */
84 struct GNUNET_CONFIGURATION_Handle
85 {
86   /**
87    * Configuration sections.
88    */
89   struct ConfigSection *sections;
90
91   /**
92    * Modification indication since last save
93    * #GNUNET_NO if clean, #GNUNET_YES if dirty,
94    * #GNUNET_SYSERR on error (i.e. last save failed)
95    */
96   int dirty;
97 };
98
99
100 /**
101  * Used for diffing a configuration object against
102  * the default one
103  */
104 struct DiffHandle
105 {
106   const struct GNUNET_CONFIGURATION_Handle *cfg_default;
107
108   struct GNUNET_CONFIGURATION_Handle *cfgDiff;
109 };
110
111
112 /**
113  * Create a GNUNET_CONFIGURATION_Handle.
114  *
115  * @return fresh configuration object
116  */
117 struct GNUNET_CONFIGURATION_Handle *
118 GNUNET_CONFIGURATION_create ()
119 {
120   struct GNUNET_CONFIGURATION_Handle *cfg;
121   char *p;
122
123   cfg = GNUNET_new (struct GNUNET_CONFIGURATION_Handle);
124   /* make certain values from the project data available
125      as PATHS */
126   p = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_DATADIR);
127   if (NULL != p)
128   {
129     GNUNET_CONFIGURATION_set_value_string (cfg,
130                                            "PATHS",
131                                            "DATADIR",
132                                            p);
133     GNUNET_free (p);
134   }
135   p = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBDIR);
136   if (NULL != p)
137   {
138     GNUNET_CONFIGURATION_set_value_string (cfg,
139                                            "PATHS",
140                                            "LIBDIR",
141                                            p);
142     GNUNET_free (p);
143   }
144   p = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_BINDIR);
145   if (NULL != p)
146   {
147     GNUNET_CONFIGURATION_set_value_string (cfg,
148                                            "PATHS",
149                                            "BINDIR",
150                                            p);
151     GNUNET_free (p);
152   }
153   p = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_PREFIX);
154   if (NULL != p)
155   {
156     GNUNET_CONFIGURATION_set_value_string (cfg,
157                                            "PATHS",
158                                            "PREFIX",
159                                            p);
160     GNUNET_free (p);
161   }
162   p = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LOCALEDIR);
163   if (NULL != p)
164   {
165     GNUNET_CONFIGURATION_set_value_string (cfg,
166                                            "PATHS",
167                                            "LOCALEDIR",
168                                            p);
169     GNUNET_free (p);
170   }
171   p = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_ICONDIR);
172   if (NULL != p)
173   {
174     GNUNET_CONFIGURATION_set_value_string (cfg,
175                                            "PATHS",
176                                            "ICONDIR",
177                                            p);
178     GNUNET_free (p);
179   }
180   p = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_DOCDIR);
181   if (NULL != p)
182   {
183     GNUNET_CONFIGURATION_set_value_string (cfg,
184                                            "PATHS",
185                                            "DOCDIR",
186                                            p);
187     GNUNET_free (p);
188   }
189   p = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBEXECDIR);
190   if (NULL != p)
191   {
192     GNUNET_CONFIGURATION_set_value_string (cfg,
193                                            "PATHS",
194                                            "LIBEXECDIR",
195                                            p);
196     GNUNET_free (p);
197   }
198   return cfg;
199 }
200
201
202 /**
203  * Destroy configuration object.
204  *
205  * @param cfg configuration to destroy
206  */
207 void
208 GNUNET_CONFIGURATION_destroy (struct GNUNET_CONFIGURATION_Handle *cfg)
209 {
210   struct ConfigSection *sec;
211
212   while (NULL != (sec = cfg->sections))
213     GNUNET_CONFIGURATION_remove_section (cfg, sec->name);
214   GNUNET_free (cfg);
215 }
216
217
218 /**
219  * Parse a configuration file @a filename and run the function
220  * @a cb with the resulting configuration object. Then free the
221  * configuration object and return the status value from @a cb.
222  *
223  * @param filename configuration to parse, NULL for "default"
224  * @param cb function to run
225  * @param cb_cls closure for @a cb
226  * @return #GNUNET_SYSERR if parsing the configuration failed,
227  *   otherwise return value from @a cb.
228  */
229 int
230 GNUNET_CONFIGURATION_parse_and_run (const char *filename,
231                                     GNUNET_CONFIGURATION_Callback cb,
232                                     void *cb_cls)
233 {
234   struct GNUNET_CONFIGURATION_Handle *cfg;
235   int ret;
236
237   cfg = GNUNET_CONFIGURATION_create ();
238   if (GNUNET_OK != GNUNET_CONFIGURATION_load (cfg, filename))
239   {
240     GNUNET_break (0);
241     GNUNET_CONFIGURATION_destroy (cfg);
242     return GNUNET_SYSERR;
243   }
244   ret = cb (cb_cls, cfg);
245   GNUNET_CONFIGURATION_destroy (cfg);
246   return ret;
247 }
248
249
250 /**
251  * De-serializes configuration
252  *
253  * @param cfg configuration to update
254  * @param mem the memory block of serialized configuration
255  * @param size the size of the memory block
256  * @param basedir set to path from which we recursively load configuration
257  *          from inlined configurations; NULL if not and raise warnings
258  *          when we come across them
259  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
260  */
261 int
262 GNUNET_CONFIGURATION_deserialize (struct GNUNET_CONFIGURATION_Handle *cfg,
263                                   const char *mem,
264                                   size_t size,
265                                   const char *basedir)
266 {
267   char *line;
268   char *line_orig;
269   size_t line_size;
270   char *pos;
271   unsigned int nr;
272   size_t r_bytes;
273   size_t to_read;
274   size_t i;
275   int emptyline;
276   int ret;
277   char *section;
278   char *eq;
279   char *tag;
280   char *value;
281
282   ret = GNUNET_OK;
283   section = GNUNET_strdup ("");
284   nr = 0;
285   r_bytes = 0;
286   line_orig = NULL;
287   while (r_bytes < size)
288   {
289     GNUNET_free_non_null (line_orig);
290     /* fgets-like behaviour on buffer */
291     to_read = size - r_bytes;
292     pos = memchr (&mem[r_bytes], '\n', to_read);
293     if (NULL == pos)
294     {
295       line_orig = GNUNET_strndup (&mem[r_bytes], line_size = to_read);
296       r_bytes += line_size;
297     }
298     else
299     {
300       line_orig =
301         GNUNET_strndup (&mem[r_bytes], line_size = (pos - &mem[r_bytes]));
302       r_bytes += line_size + 1;
303     }
304     line = line_orig;
305     /* increment line number */
306     nr++;
307     /* tabs and '\r' are whitespace */
308     emptyline = GNUNET_YES;
309     for (i = 0; i < line_size; i++)
310     {
311       if (line[i] == '\t')
312         line[i] = ' ';
313       if (line[i] == '\r')
314         line[i] = ' ';
315       if (' ' != line[i])
316         emptyline = GNUNET_NO;
317     }
318     /* ignore empty lines */
319     if (GNUNET_YES == emptyline)
320       continue;
321
322     /* remove tailing whitespace */
323     for (i = line_size - 1; (i >= 1) && (isspace ((unsigned char) line[i]));
324          i--)
325       line[i] = '\0';
326
327     /* remove leading whitespace */
328     for (; line[0] != '\0' && (isspace ((unsigned char) line[0])); line++)
329       ;
330
331     /* ignore comments */
332     if (('#' == line[0]) || ('%' == line[0]))
333       continue;
334
335     /* handle special "@INLINE@" directive */
336     if (0 == strncasecmp (line, "@INLINE@ ", strlen ("@INLINE@ ")))
337     {
338       /* @INLINE@ value */
339       value = &line[strlen ("@INLINE@ ")];
340       if (NULL != basedir)
341       {
342         char *fn;
343
344         GNUNET_asprintf (&fn, "%s/%s", basedir, value);
345         if (GNUNET_OK != GNUNET_CONFIGURATION_parse (cfg, fn))
346         {
347           GNUNET_free (fn);
348           ret = GNUNET_SYSERR;         /* failed to parse included config */
349           break;
350         }
351         GNUNET_free (fn);
352       }
353       else
354       {
355         LOG (GNUNET_ERROR_TYPE_DEBUG,
356              "Ignoring parsing @INLINE@ configurations, not allowed!\n");
357         ret = GNUNET_SYSERR;
358         break;
359       }
360       continue;
361     }
362     if (('[' == line[0]) && (']' == line[line_size - 1]))
363     {
364       /* [value] */
365       line[line_size - 1] = '\0';
366       value = &line[1];
367       GNUNET_free (section);
368       section = GNUNET_strdup (value);
369       continue;
370     }
371     if (NULL != (eq = strchr (line, '=')))
372     {
373       /* tag = value */
374       tag = GNUNET_strndup (line, eq - line);
375       /* remove tailing whitespace */
376       for (i = strlen (tag) - 1; (i >= 1) && (isspace ((unsigned char) tag[i]));
377            i--)
378         tag[i] = '\0';
379
380       /* Strip whitespace */
381       value = eq + 1;
382       while (isspace ((unsigned char) value[0]))
383         value++;
384       for (i = strlen (value) - 1;
385            (i >= 1) && (isspace ((unsigned char) value[i]));
386            i--)
387         value[i] = '\0';
388
389       /* remove quotes */
390       i = 0;
391       if (('"' == value[0]) && ('"' == value[strlen (value) - 1]))
392       {
393         value[strlen (value) - 1] = '\0';
394         value++;
395       }
396       GNUNET_CONFIGURATION_set_value_string (cfg, section, tag, &value[i]);
397       GNUNET_free (tag);
398       continue;
399     }
400     /* parse error */
401     LOG (GNUNET_ERROR_TYPE_WARNING,
402          _ ("Syntax error while deserializing in line %u\n"),
403          nr);
404     ret = GNUNET_SYSERR;
405     break;
406   }
407   GNUNET_free_non_null (line_orig);
408   GNUNET_free (section);
409   GNUNET_assert ((GNUNET_OK != ret) || (r_bytes == size));
410   return ret;
411 }
412
413
414 /**
415  * Parse a configuration file, add all of the options in the
416  * file to the configuration environment.
417  *
418  * @param cfg configuration to update
419  * @param filename name of the configuration file
420  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
421  */
422 int
423 GNUNET_CONFIGURATION_parse (struct GNUNET_CONFIGURATION_Handle *cfg,
424                             const char *filename)
425 {
426   uint64_t fs64;
427   size_t fs;
428   char *fn;
429   char *mem;
430   char *endsep;
431   int dirty;
432   int ret;
433   ssize_t sret;
434
435   fn = GNUNET_STRINGS_filename_expand (filename);
436   LOG (GNUNET_ERROR_TYPE_DEBUG, "Asked to parse config file `%s'\n", fn);
437   if (NULL == fn)
438     return GNUNET_SYSERR;
439   dirty = cfg->dirty; /* back up value! */
440   if (GNUNET_SYSERR ==
441       GNUNET_DISK_file_size (fn, &fs64, GNUNET_YES, GNUNET_YES))
442   {
443     LOG (GNUNET_ERROR_TYPE_WARNING,
444          "Error while determining the file size of `%s'\n",
445          fn);
446     GNUNET_free (fn);
447     return GNUNET_SYSERR;
448   }
449   if (fs64 > SIZE_MAX)
450   {
451     GNUNET_break (0);  /* File size is more than the heap size */
452     GNUNET_free (fn);
453     return GNUNET_SYSERR;
454   }
455   fs = fs64;
456   mem = GNUNET_malloc (fs);
457   sret = GNUNET_DISK_fn_read (fn, mem, fs);
458   if ((sret < 0) || (fs != (size_t) sret))
459   {
460     LOG (GNUNET_ERROR_TYPE_WARNING, _ ("Error while reading file `%s'\n"), fn);
461     GNUNET_free (fn);
462     GNUNET_free (mem);
463     return GNUNET_SYSERR;
464   }
465   LOG (GNUNET_ERROR_TYPE_DEBUG, "Deserializing contents of file `%s'\n", fn);
466   endsep = strrchr (fn, (int) '/');
467   if (NULL != endsep)
468     *endsep = '\0';
469   ret = GNUNET_CONFIGURATION_deserialize (cfg, mem, fs, fn);
470   GNUNET_free (fn);
471   GNUNET_free (mem);
472   /* restore dirty flag - anything we set in the meantime
473    * came from disk */
474   cfg->dirty = dirty;
475   return ret;
476 }
477
478
479 /**
480  * Test if there are configuration options that were
481  * changed since the last save.
482  *
483  * @param cfg configuration to inspect
484  * @return #GNUNET_NO if clean, #GNUNET_YES if dirty, #GNUNET_SYSERR on error (i.e. last save failed)
485  */
486 int
487 GNUNET_CONFIGURATION_is_dirty (const struct GNUNET_CONFIGURATION_Handle *cfg)
488 {
489   return cfg->dirty;
490 }
491
492
493 /**
494  * Serializes the given configuration.
495  *
496  * @param cfg configuration to serialize
497  * @param size will be set to the size of the serialized memory block
498  * @return the memory block where the serialized configuration is
499  *           present. This memory should be freed by the caller
500  */
501 char *
502 GNUNET_CONFIGURATION_serialize (const struct GNUNET_CONFIGURATION_Handle *cfg,
503                                 size_t *size)
504 {
505   struct ConfigSection *sec;
506   struct ConfigEntry *ent;
507   char *mem;
508   char *cbuf;
509   char *val;
510   char *pos;
511   size_t m_size;
512   size_t c_size;
513
514   /* Pass1 : calculate the buffer size required */
515   m_size = 0;
516   for (sec = cfg->sections; NULL != sec; sec = sec->next)
517   {
518     /* For each section we need to add 3 charaters: {'[',']','\n'} */
519     m_size += strlen (sec->name) + 3;
520     for (ent = sec->entries; NULL != ent; ent = ent->next)
521     {
522       if (NULL != ent->val)
523       {
524         /* if val has any '\n' then they occupy +1 character as '\n'->'\\','n' */
525         pos = ent->val;
526         while (NULL != (pos = strstr (pos, "\n")))
527         {
528           m_size++;
529           pos++;
530         }
531         /* For each key = value pair we need to add 4 characters (2
532            spaces and 1 equal-to character and 1 new line) */
533         m_size += strlen (ent->key) + strlen (ent->val) + 4;
534       }
535     }
536     /* A new line after section end */
537     m_size++;
538   }
539
540   /* Pass2: Allocate memory and write the configuration to it */
541   mem = GNUNET_malloc (m_size);
542   sec = cfg->sections;
543   c_size = 0;
544   *size = c_size;
545   while (NULL != sec)
546   {
547     int len;
548
549     len = GNUNET_asprintf (&cbuf, "[%s]\n", sec->name);
550     GNUNET_assert (0 < len);
551     GNUNET_memcpy (mem + c_size, cbuf, len);
552     c_size += len;
553     GNUNET_free (cbuf);
554     for (ent = sec->entries; NULL != ent; ent = ent->next)
555     {
556       if (NULL != ent->val)
557       {
558         val = GNUNET_malloc (strlen (ent->val) * 2 + 1);
559         strcpy (val, ent->val);
560         while (NULL != (pos = strstr (val, "\n")))
561         {
562           memmove (&pos[2], &pos[1], strlen (&pos[1]));
563           pos[0] = '\\';
564           pos[1] = 'n';
565         }
566         len = GNUNET_asprintf (&cbuf, "%s = %s\n", ent->key, val);
567         GNUNET_free (val);
568         GNUNET_memcpy (mem + c_size, cbuf, len);
569         c_size += len;
570         GNUNET_free (cbuf);
571       }
572     }
573     GNUNET_memcpy (mem + c_size, "\n", 1);
574     c_size++;
575     sec = sec->next;
576   }
577   GNUNET_assert (c_size == m_size);
578   *size = c_size;
579   return mem;
580 }
581
582
583 /**
584  * Write configuration file.
585  *
586  * @param cfg configuration to write
587  * @param filename where to write the configuration
588  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
589  */
590 int
591 GNUNET_CONFIGURATION_write (struct GNUNET_CONFIGURATION_Handle *cfg,
592                             const char *filename)
593 {
594   char *fn;
595   char *cfg_buf;
596   size_t size;
597   ssize_t sret;
598
599   fn = GNUNET_STRINGS_filename_expand (filename);
600   if (fn == NULL)
601     return GNUNET_SYSERR;
602   if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (fn))
603   {
604     GNUNET_free (fn);
605     return GNUNET_SYSERR;
606   }
607   cfg_buf = GNUNET_CONFIGURATION_serialize (cfg, &size);
608   sret = GNUNET_DISK_fn_write (fn,
609                                cfg_buf,
610                                size,
611                                GNUNET_DISK_PERM_USER_READ
612                                | GNUNET_DISK_PERM_USER_WRITE
613                                | GNUNET_DISK_PERM_GROUP_READ
614                                | GNUNET_DISK_PERM_GROUP_WRITE);
615   if ((sret < 0) || (size != (size_t) sret))
616   {
617     GNUNET_free (fn);
618     GNUNET_free (cfg_buf);
619     LOG (GNUNET_ERROR_TYPE_WARNING,
620          "Writing configuration to file `%s' failed\n",
621          filename);
622     cfg->dirty = GNUNET_SYSERR;   /* last write failed */
623     return GNUNET_SYSERR;
624   }
625   GNUNET_free (fn);
626   GNUNET_free (cfg_buf);
627   cfg->dirty = GNUNET_NO; /* last write succeeded */
628   return GNUNET_OK;
629 }
630
631
632 /**
633  * Iterate over all options in the configuration.
634  *
635  * @param cfg configuration to inspect
636  * @param iter function to call on each option
637  * @param iter_cls closure for @a iter
638  */
639 void
640 GNUNET_CONFIGURATION_iterate (const struct GNUNET_CONFIGURATION_Handle *cfg,
641                               GNUNET_CONFIGURATION_Iterator iter,
642                               void *iter_cls)
643 {
644   struct ConfigSection *spos;
645   struct ConfigEntry *epos;
646
647   for (spos = cfg->sections; NULL != spos; spos = spos->next)
648     for (epos = spos->entries; NULL != epos; epos = epos->next)
649       if (NULL != epos->val)
650         iter (iter_cls, spos->name, epos->key, epos->val);
651 }
652
653
654 /**
655  * Iterate over values of a section in the configuration.
656  *
657  * @param cfg configuration to inspect
658  * @param section the section
659  * @param iter function to call on each option
660  * @param iter_cls closure for @a iter
661  */
662 void
663 GNUNET_CONFIGURATION_iterate_section_values (
664   const struct GNUNET_CONFIGURATION_Handle *cfg,
665   const char *section,
666   GNUNET_CONFIGURATION_Iterator iter,
667   void *iter_cls)
668 {
669   struct ConfigSection *spos;
670   struct ConfigEntry *epos;
671
672   spos = cfg->sections;
673   while ((spos != NULL) && (0 != strcasecmp (spos->name, section)))
674     spos = spos->next;
675   if (NULL == spos)
676     return;
677   for (epos = spos->entries; NULL != epos; epos = epos->next)
678     if (NULL != epos->val)
679       iter (iter_cls, spos->name, epos->key, epos->val);
680 }
681
682
683 /**
684  * Iterate over all sections in the configuration.
685  *
686  * @param cfg configuration to inspect
687  * @param iter function to call on each section
688  * @param iter_cls closure for @a iter
689  */
690 void
691 GNUNET_CONFIGURATION_iterate_sections (
692   const struct GNUNET_CONFIGURATION_Handle *cfg,
693   GNUNET_CONFIGURATION_Section_Iterator iter,
694   void *iter_cls)
695 {
696   struct ConfigSection *spos;
697   struct ConfigSection *next;
698
699   next = cfg->sections;
700   while (next != NULL)
701   {
702     spos = next;
703     next = spos->next;
704     iter (iter_cls, spos->name);
705   }
706 }
707
708
709 /**
710  * Remove the given section and all options in it.
711  *
712  * @param cfg configuration to inspect
713  * @param section name of the section to remove
714  */
715 void
716 GNUNET_CONFIGURATION_remove_section (struct GNUNET_CONFIGURATION_Handle *cfg,
717                                      const char *section)
718 {
719   struct ConfigSection *spos;
720   struct ConfigSection *prev;
721   struct ConfigEntry *ent;
722
723   prev = NULL;
724   spos = cfg->sections;
725   while (NULL != spos)
726   {
727     if (0 == strcasecmp (section, spos->name))
728     {
729       if (NULL == prev)
730         cfg->sections = spos->next;
731       else
732         prev->next = spos->next;
733       while (NULL != (ent = spos->entries))
734       {
735         spos->entries = ent->next;
736         GNUNET_free (ent->key);
737         GNUNET_free_non_null (ent->val);
738         GNUNET_free (ent);
739         cfg->dirty = GNUNET_YES;
740       }
741       GNUNET_free (spos->name);
742       GNUNET_free (spos);
743       return;
744     }
745     prev = spos;
746     spos = spos->next;
747   }
748 }
749
750
751 /**
752  * Copy a configuration value to the given target configuration.
753  * Overwrites existing entries.
754  *
755  * @param cls the destination configuration (`struct GNUNET_CONFIGURATION_Handle *`)
756  * @param section section for the value
757  * @param option option name of the value
758  * @param value value to copy
759  */
760 static void
761 copy_entry (void *cls,
762             const char *section,
763             const char *option,
764             const char *value)
765 {
766   struct GNUNET_CONFIGURATION_Handle *dst = cls;
767
768   GNUNET_CONFIGURATION_set_value_string (dst, section, option, value);
769 }
770
771
772 /**
773  * Duplicate an existing configuration object.
774  *
775  * @param cfg configuration to duplicate
776  * @return duplicate configuration
777  */
778 struct GNUNET_CONFIGURATION_Handle *
779 GNUNET_CONFIGURATION_dup (const struct GNUNET_CONFIGURATION_Handle *cfg)
780 {
781   struct GNUNET_CONFIGURATION_Handle *ret;
782
783   ret = GNUNET_CONFIGURATION_create ();
784   GNUNET_CONFIGURATION_iterate (cfg, &copy_entry, ret);
785   return ret;
786 }
787
788
789 /**
790  * Find a section entry from a configuration.
791  *
792  * @param cfg configuration to search in
793  * @param section name of the section to look for
794  * @return matching entry, NULL if not found
795  */
796 static struct ConfigSection *
797 find_section (const struct GNUNET_CONFIGURATION_Handle *cfg,
798               const char *section)
799 {
800   struct ConfigSection *pos;
801
802   pos = cfg->sections;
803   while ((pos != NULL) && (0 != strcasecmp (section, pos->name)))
804     pos = pos->next;
805   return pos;
806 }
807
808
809 /**
810  * Find an entry from a configuration.
811  *
812  * @param cfg handle to the configuration
813  * @param section section the option is in
814  * @param key the option
815  * @return matching entry, NULL if not found
816  */
817 static struct ConfigEntry *
818 find_entry (const struct GNUNET_CONFIGURATION_Handle *cfg,
819             const char *section,
820             const char *key)
821 {
822   struct ConfigSection *sec;
823   struct ConfigEntry *pos;
824
825   if (NULL == (sec = find_section (cfg, section)))
826     return NULL;
827   pos = sec->entries;
828   while ((pos != NULL) && (0 != strcasecmp (key, pos->key)))
829     pos = pos->next;
830   return pos;
831 }
832
833
834 /**
835  * A callback function, compares entries from two configurations
836  * (default against a new configuration) and write the diffs in a
837  * diff-configuration object (the callback object).
838  *
839  * @param cls the diff configuration (`struct DiffHandle *`)
840  * @param section section for the value (of the default conf.)
841  * @param option option name of the value (of the default conf.)
842  * @param value value to copy (of the default conf.)
843  */
844 static void
845 compare_entries (void *cls,
846                  const char *section,
847                  const char *option,
848                  const char *value)
849 {
850   struct DiffHandle *dh = cls;
851   struct ConfigEntry *entNew;
852
853   entNew = find_entry (dh->cfg_default, section, option);
854   if ((NULL != entNew) && (NULL != entNew->val) &&
855       (0 == strcmp (entNew->val, value)))
856     return;
857   GNUNET_CONFIGURATION_set_value_string (dh->cfgDiff, section, option, value);
858 }
859
860
861 /**
862  * Compute configuration with only entries that have been changed
863  *
864  * @param cfg_default original configuration
865  * @param cfg_new new configuration
866  * @return configuration with only the differences, never NULL
867  */
868 struct GNUNET_CONFIGURATION_Handle *
869 GNUNET_CONFIGURATION_get_diff (
870   const struct GNUNET_CONFIGURATION_Handle *cfg_default,
871   const struct GNUNET_CONFIGURATION_Handle *cfg_new)
872 {
873   struct DiffHandle diffHandle;
874
875   diffHandle.cfgDiff = GNUNET_CONFIGURATION_create ();
876   diffHandle.cfg_default = cfg_default;
877   GNUNET_CONFIGURATION_iterate (cfg_new, &compare_entries, &diffHandle);
878   return diffHandle.cfgDiff;
879 }
880
881
882 /**
883  * Write only configuration entries that have been changed to configuration file
884  *
885  * @param cfg_default default configuration
886  * @param cfg_new new configuration
887  * @param filename where to write the configuration diff between default and new
888  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
889  */
890 int
891 GNUNET_CONFIGURATION_write_diffs (
892   const struct GNUNET_CONFIGURATION_Handle *cfg_default,
893   const struct GNUNET_CONFIGURATION_Handle *cfg_new,
894   const char *filename)
895 {
896   int ret;
897   struct GNUNET_CONFIGURATION_Handle *diff;
898
899   diff = GNUNET_CONFIGURATION_get_diff (cfg_default, cfg_new);
900   ret = GNUNET_CONFIGURATION_write (diff, filename);
901   GNUNET_CONFIGURATION_destroy (diff);
902   return ret;
903 }
904
905
906 /**
907  * Set a configuration value that should be a string.
908  *
909  * @param cfg configuration to update
910  * @param section section of interest
911  * @param option option of interest
912  * @param value value to set
913  */
914 void
915 GNUNET_CONFIGURATION_set_value_string (struct GNUNET_CONFIGURATION_Handle *cfg,
916                                        const char *section,
917                                        const char *option,
918                                        const char *value)
919 {
920   struct ConfigSection *sec;
921   struct ConfigEntry *e;
922   char *nv;
923
924   e = find_entry (cfg, section, option);
925   if (NULL != e)
926   {
927     if (NULL == value)
928     {
929       GNUNET_free_non_null (e->val);
930       e->val = NULL;
931     }
932     else
933     {
934       nv = GNUNET_strdup (value);
935       GNUNET_free_non_null (e->val);
936       e->val = nv;
937     }
938     return;
939   }
940   sec = find_section (cfg, section);
941   if (sec == NULL)
942   {
943     sec = GNUNET_new (struct ConfigSection);
944     sec->name = GNUNET_strdup (section);
945     sec->next = cfg->sections;
946     cfg->sections = sec;
947   }
948   e = GNUNET_new (struct ConfigEntry);
949   e->key = GNUNET_strdup (option);
950   e->val = GNUNET_strdup (value);
951   e->next = sec->entries;
952   sec->entries = e;
953 }
954
955
956 /**
957  * Set a configuration value that should be a number.
958  *
959  * @param cfg configuration to update
960  * @param section section of interest
961  * @param option option of interest
962  * @param number value to set
963  */
964 void
965 GNUNET_CONFIGURATION_set_value_number (struct GNUNET_CONFIGURATION_Handle *cfg,
966                                        const char *section,
967                                        const char *option,
968                                        unsigned long long number)
969 {
970   char s[64];
971
972   GNUNET_snprintf (s, 64, "%llu", number);
973   GNUNET_CONFIGURATION_set_value_string (cfg, section, option, s);
974 }
975
976
977 /**
978  * Get a configuration value that should be a number.
979  *
980  * @param cfg configuration to inspect
981  * @param section section of interest
982  * @param option option of interest
983  * @param number where to store the numeric value of the option
984  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
985  */
986 int
987 GNUNET_CONFIGURATION_get_value_number (
988   const struct GNUNET_CONFIGURATION_Handle *cfg,
989   const char *section,
990   const char *option,
991   unsigned long long *number)
992 {
993   struct ConfigEntry *e;
994   char dummy[2];
995
996   if (NULL == (e = find_entry (cfg, section, option)))
997     return GNUNET_SYSERR;
998   if (NULL == e->val)
999     return GNUNET_SYSERR;
1000   if (1 != sscanf (e->val, "%llu%1s", number, dummy))
1001     return GNUNET_SYSERR;
1002   return GNUNET_OK;
1003 }
1004
1005
1006 /**
1007  * Get a configuration value that should be a floating point number.
1008  *
1009  * @param cfg configuration to inspect
1010  * @param section section of interest
1011  * @param option option of interest
1012  * @param number where to store the floating value of the option
1013  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1014  */
1015 int
1016 GNUNET_CONFIGURATION_get_value_float (
1017   const struct GNUNET_CONFIGURATION_Handle *cfg,
1018   const char *section,
1019   const char *option,
1020   float *number)
1021 {
1022   struct ConfigEntry *e;
1023   char dummy[2];
1024
1025   if (NULL == (e = find_entry (cfg, section, option)))
1026     return GNUNET_SYSERR;
1027   if (NULL == e->val)
1028     return GNUNET_SYSERR;
1029   if (1 != sscanf (e->val, "%f%1s", number, dummy))
1030     return GNUNET_SYSERR;
1031   return GNUNET_OK;
1032 }
1033
1034
1035 /**
1036  * Get a configuration value that should be a relative time.
1037  *
1038  * @param cfg configuration to inspect
1039  * @param section section of interest
1040  * @param option option of interest
1041  * @param time set to the time value stored in the configuration
1042  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1043  */
1044 int
1045 GNUNET_CONFIGURATION_get_value_time (
1046   const struct GNUNET_CONFIGURATION_Handle *cfg,
1047   const char *section,
1048   const char *option,
1049   struct GNUNET_TIME_Relative *time)
1050 {
1051   struct ConfigEntry *e;
1052   int ret;
1053
1054   if (NULL == (e = find_entry (cfg, section, option)))
1055     return GNUNET_SYSERR;
1056   if (NULL == e->val)
1057     return GNUNET_SYSERR;
1058   ret = GNUNET_STRINGS_fancy_time_to_relative (e->val, time);
1059   if (GNUNET_OK != ret)
1060     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
1061                                section,
1062                                option,
1063                                _ ("Not a valid relative time specification"));
1064   return ret;
1065 }
1066
1067
1068 /**
1069  * Get a configuration value that should be a size in bytes.
1070  *
1071  * @param cfg configuration to inspect
1072  * @param section section of interest
1073  * @param option option of interest
1074  * @param size set to the size in bytes as stored in the configuration
1075  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1076  */
1077 int
1078 GNUNET_CONFIGURATION_get_value_size (
1079   const struct GNUNET_CONFIGURATION_Handle *cfg,
1080   const char *section,
1081   const char *option,
1082   unsigned long long *size)
1083 {
1084   struct ConfigEntry *e;
1085
1086   if (NULL == (e = find_entry (cfg, section, option)))
1087     return GNUNET_SYSERR;
1088   if (NULL == e->val)
1089     return GNUNET_SYSERR;
1090   return GNUNET_STRINGS_fancy_size_to_bytes (e->val, size);
1091 }
1092
1093
1094 /**
1095  * Get a configuration value that should be a string.
1096  *
1097  * @param cfg configuration to inspect
1098  * @param section section of interest
1099  * @param option option of interest
1100  * @param value will be set to a freshly allocated configuration
1101  *        value, or NULL if option is not specified
1102  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1103  */
1104 int
1105 GNUNET_CONFIGURATION_get_value_string (
1106   const struct GNUNET_CONFIGURATION_Handle *cfg,
1107   const char *section,
1108   const char *option,
1109   char **value)
1110 {
1111   struct ConfigEntry *e;
1112
1113   if ((NULL == (e = find_entry (cfg, section, option))) || (NULL == e->val))
1114   {
1115     *value = NULL;
1116     return GNUNET_SYSERR;
1117   }
1118   *value = GNUNET_strdup (e->val);
1119   return GNUNET_OK;
1120 }
1121
1122
1123 /**
1124  * Get a configuration value that should be in a set of
1125  * predefined strings
1126  *
1127  * @param cfg configuration to inspect
1128  * @param section section of interest
1129  * @param option option of interest
1130  * @param choices NULL-terminated list of legal values
1131  * @param value will be set to an entry in the legal list,
1132  *        or NULL if option is not specified and no default given
1133  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1134  */
1135 int
1136 GNUNET_CONFIGURATION_get_value_choice (
1137   const struct GNUNET_CONFIGURATION_Handle *cfg,
1138   const char *section,
1139   const char *option,
1140   const char *const *choices,
1141   const char **value)
1142 {
1143   struct ConfigEntry *e;
1144   unsigned int i;
1145
1146   if (NULL == (e = find_entry (cfg, section, option)))
1147     return GNUNET_SYSERR;
1148   for (i = 0; NULL != choices[i]; i++)
1149     if (0 == strcasecmp (choices[i], e->val))
1150       break;
1151   if (NULL == choices[i])
1152   {
1153     LOG (GNUNET_ERROR_TYPE_ERROR,
1154          _ ("Configuration value '%s' for '%s'"
1155             " in section '%s' is not in set of legal choices\n"),
1156          e->val,
1157          option,
1158          section);
1159     return GNUNET_SYSERR;
1160   }
1161   *value = choices[i];
1162   return GNUNET_OK;
1163 }
1164
1165
1166 /**
1167  * Get crockford32-encoded fixed-size binary data from a configuration.
1168  *
1169  * @param cfg configuration to access
1170  * @param section section to access
1171  * @param option option to access
1172  * @param buf where to store the decoded binary result
1173  * @param buf_size exact number of bytes to store in @a buf
1174  * @return #GNUNET_OK on success
1175  *         #GNUNET_NO is the value does not exist
1176  *         #GNUNET_SYSERR on decoding error
1177  */
1178 int
1179 GNUNET_CONFIGURATION_get_data (const struct GNUNET_CONFIGURATION_Handle *cfg,
1180                                const char *section,
1181                                const char *option,
1182                                void *buf,
1183                                size_t buf_size)
1184 {
1185   char *enc;
1186   int res;
1187   size_t data_size;
1188
1189   if (GNUNET_OK !=
1190       (res =
1191          GNUNET_CONFIGURATION_get_value_string (cfg, section, option, &enc)))
1192     return res;
1193   data_size = (strlen (enc) * 5) / 8;
1194   if (data_size != buf_size)
1195   {
1196     GNUNET_free (enc);
1197     return GNUNET_SYSERR;
1198   }
1199   if (GNUNET_OK !=
1200       GNUNET_STRINGS_string_to_data (enc, strlen (enc), buf, buf_size))
1201   {
1202     GNUNET_free (enc);
1203     return GNUNET_SYSERR;
1204   }
1205   GNUNET_free (enc);
1206   return GNUNET_OK;
1207 }
1208
1209
1210 /**
1211  * Test if we have a value for a particular option
1212  *
1213  * @param cfg configuration to inspect
1214  * @param section section of interest
1215  * @param option option of interest
1216  * @return #GNUNET_YES if so, #GNUNET_NO if not.
1217  */
1218 int
1219 GNUNET_CONFIGURATION_have_value (const struct GNUNET_CONFIGURATION_Handle *cfg,
1220                                  const char *section,
1221                                  const char *option)
1222 {
1223   struct ConfigEntry *e;
1224
1225   if ((NULL == (e = find_entry (cfg, section, option))) || (NULL == e->val))
1226     return GNUNET_NO;
1227   return GNUNET_YES;
1228 }
1229
1230
1231 /**
1232  * Expand an expression of the form "$FOO/BAR" to "DIRECTORY/BAR"
1233  * where either in the "PATHS" section or the environtment "FOO" is
1234  * set to "DIRECTORY".  We also support default expansion,
1235  * i.e. ${VARIABLE:-default} will expand to $VARIABLE if VARIABLE is
1236  * set in PATHS or the environment, and otherwise to "default".  Note
1237  * that "default" itself can also be a $-expression, thus
1238  * "${VAR1:-{$VAR2}}" will expand to VAR1 and if that is not defined
1239  * to VAR2.
1240  *
1241  * @param cfg configuration to use for path expansion
1242  * @param orig string to $-expand (will be freed!)
1243  * @param depth recursion depth, used to detect recursive expansions
1244  * @return $-expanded string, never NULL unless @a orig was NULL
1245  */
1246 static char *
1247 expand_dollar (const struct GNUNET_CONFIGURATION_Handle *cfg,
1248                char *orig,
1249                unsigned int depth)
1250 {
1251   char *prefix;
1252   char *result;
1253   char *start;
1254   const char *post;
1255   const char *env;
1256   char *def;
1257   char *end;
1258   unsigned int lopen;
1259   char erased_char;
1260   char *erased_pos;
1261   size_t len;
1262
1263   if (NULL == orig)
1264     return NULL;
1265   if (depth > 128)
1266   {
1267     LOG (GNUNET_ERROR_TYPE_WARNING,
1268          _ (
1269            "Recursive expansion suspected, aborting $-expansion for term `%s'\n"),
1270          orig);
1271     return orig;
1272   }
1273   LOG (GNUNET_ERROR_TYPE_DEBUG, "Asked to $-expand %s\n", orig);
1274   if ('$' != orig[0])
1275   {
1276     LOG (GNUNET_ERROR_TYPE_DEBUG, "Doesn't start with $ - not expanding\n");
1277     return orig;
1278   }
1279   erased_char = 0;
1280   erased_pos = NULL;
1281   if ('{' == orig[1])
1282   {
1283     start = &orig[2];
1284     lopen = 1;
1285     end = &orig[1];
1286     while (lopen > 0)
1287     {
1288       end++;
1289       switch (*end)
1290       {
1291       case '}':
1292         lopen--;
1293         break;
1294
1295       case '{':
1296         lopen++;
1297         break;
1298
1299       case '\0':
1300         LOG (GNUNET_ERROR_TYPE_WARNING,
1301              _ ("Missing closing `%s' in option `%s'\n"),
1302              "}",
1303              orig);
1304         return orig;
1305
1306       default:
1307         break;
1308       }
1309     }
1310     erased_char = *end;
1311     erased_pos = end;
1312     *end = '\0';
1313     post = end + 1;
1314     def = strchr (orig, ':');
1315     if (NULL != def)
1316     {
1317       *def = '\0';
1318       def++;
1319       if (('-' == *def) || ('=' == *def))
1320         def++;
1321       def = GNUNET_strdup (def);
1322     }
1323   }
1324   else
1325   {
1326     int i;
1327
1328     start = &orig[1];
1329     def = NULL;
1330     i = 0;
1331     while ((orig[i] != '/') && (orig[i] != '\\') && (orig[i] != '\0') &&
1332            (orig[i] != ' '))
1333       i++;
1334     if (orig[i] == '\0')
1335     {
1336       post = "";
1337     }
1338     else
1339     {
1340       erased_char = orig[i];
1341       erased_pos = &orig[i];
1342       orig[i] = '\0';
1343       post = &orig[i + 1];
1344     }
1345   }
1346   LOG (GNUNET_ERROR_TYPE_DEBUG,
1347        "Split into `%s' and `%s' with default %s\n",
1348        start,
1349        post,
1350        def);
1351   if (GNUNET_OK !=
1352       GNUNET_CONFIGURATION_get_value_string (cfg, "PATHS", start, &prefix))
1353   {
1354     if (NULL == (env = getenv (start)))
1355     {
1356       /* try default */
1357       def = expand_dollar (cfg, def, depth + 1);
1358       env = def;
1359     }
1360     if (NULL == env)
1361     {
1362       start = GNUNET_strdup (start);
1363       if (erased_pos)
1364         *erased_pos = erased_char;
1365       LOG (GNUNET_ERROR_TYPE_WARNING,
1366            _ (
1367              "Failed to expand `%s' in `%s' as it is neither found in [PATHS] nor defined as an environmental variable\n"),
1368            start,
1369            orig);
1370       GNUNET_free (start);
1371       return orig;
1372     }
1373     prefix = GNUNET_strdup (env);
1374   }
1375   prefix = GNUNET_CONFIGURATION_expand_dollar (cfg, prefix);
1376   if ((erased_pos) && ('}' != erased_char))
1377   {
1378     len = strlen (prefix) + 1;
1379     prefix = GNUNET_realloc (prefix, len + 1);
1380     prefix[len - 1] = erased_char;
1381     prefix[len] = '\0';
1382   }
1383   result = GNUNET_malloc (strlen (prefix) + strlen (post) + 1);
1384   strcpy (result, prefix);
1385   strcat (result, post);
1386   GNUNET_free_non_null (def);
1387   GNUNET_free (prefix);
1388   GNUNET_free (orig);
1389   return result;
1390 }
1391
1392
1393 /**
1394  * Expand an expression of the form "$FOO/BAR" to "DIRECTORY/BAR"
1395  * where either in the "PATHS" section or the environtment "FOO" is
1396  * set to "DIRECTORY".  We also support default expansion,
1397  * i.e. ${VARIABLE:-default} will expand to $VARIABLE if VARIABLE is
1398  * set in PATHS or the environment, and otherwise to "default".  Note
1399  * that "default" itself can also be a $-expression, thus
1400  * "${VAR1:-{$VAR2}}" will expand to VAR1 and if that is not defined
1401  * to VAR2.
1402  *
1403  * @param cfg configuration to use for path expansion
1404  * @param orig string to $-expand (will be freed!).  Note that multiple
1405  *          $-expressions can be present in this string.  They will all be
1406  *          $-expanded.
1407  * @return $-expanded string
1408  */
1409 char *
1410 GNUNET_CONFIGURATION_expand_dollar (
1411   const struct GNUNET_CONFIGURATION_Handle *cfg,
1412   char *orig)
1413 {
1414   char *dup;
1415   size_t i;
1416   size_t len;
1417
1418   for (i = 0; '\0' != orig[i]; i++)
1419   {
1420     if ('$' != orig[i])
1421       continue;
1422     dup = GNUNET_strdup (orig + i);
1423     dup = expand_dollar (cfg, dup, 0);
1424     GNUNET_assert (NULL != dup); /* make compiler happy */
1425     len = strlen (dup) + 1;
1426     orig = GNUNET_realloc (orig, i + len);
1427     GNUNET_memcpy (orig + i, dup, len);
1428     GNUNET_free (dup);
1429   }
1430   return orig;
1431 }
1432
1433
1434 /**
1435  * Get a configuration value that should be a string.
1436  *
1437  * @param cfg configuration to inspect
1438  * @param section section of interest
1439  * @param option option of interest
1440  * @param value will be set to a freshly allocated configuration
1441  *        value, or NULL if option is not specified
1442  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1443  */
1444 int
1445 GNUNET_CONFIGURATION_get_value_filename (
1446   const struct GNUNET_CONFIGURATION_Handle *cfg,
1447   const char *section,
1448   const char *option,
1449   char **value)
1450 {
1451   char *tmp;
1452
1453   if (GNUNET_OK !=
1454       GNUNET_CONFIGURATION_get_value_string (cfg, section, option, &tmp))
1455   {
1456     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to retrieve filename\n");
1457     *value = NULL;
1458     return GNUNET_SYSERR;
1459   }
1460   tmp = GNUNET_CONFIGURATION_expand_dollar (cfg, tmp);
1461   *value = GNUNET_STRINGS_filename_expand (tmp);
1462   GNUNET_free (tmp);
1463   if (*value == NULL)
1464     return GNUNET_SYSERR;
1465   return GNUNET_OK;
1466 }
1467
1468
1469 /**
1470  * Get a configuration value that should be in a set of
1471  * "YES" or "NO".
1472  *
1473  * @param cfg configuration to inspect
1474  * @param section section of interest
1475  * @param option option of interest
1476  * @return #GNUNET_YES, #GNUNET_NO or #GNUNET_SYSERR
1477  */
1478 int
1479 GNUNET_CONFIGURATION_get_value_yesno (
1480   const struct GNUNET_CONFIGURATION_Handle *cfg,
1481   const char *section,
1482   const char *option)
1483 {
1484   static const char *yesno[] = { "YES", "NO", NULL };
1485   const char *val;
1486   int ret;
1487
1488   ret =
1489     GNUNET_CONFIGURATION_get_value_choice (cfg, section, option, yesno, &val);
1490   if (ret == GNUNET_SYSERR)
1491     return ret;
1492   if (val == yesno[0])
1493     return GNUNET_YES;
1494   return GNUNET_NO;
1495 }
1496
1497
1498 /**
1499  * Iterate over the set of filenames stored in a configuration value.
1500  *
1501  * @param cfg configuration to inspect
1502  * @param section section of interest
1503  * @param option option of interest
1504  * @param cb function to call on each filename
1505  * @param cb_cls closure for @a cb
1506  * @return number of filenames iterated over, -1 on error
1507  */
1508 int
1509 GNUNET_CONFIGURATION_iterate_value_filenames (
1510   const struct GNUNET_CONFIGURATION_Handle *cfg,
1511   const char *section,
1512   const char *option,
1513   GNUNET_FileNameCallback cb,
1514   void *cb_cls)
1515 {
1516   char *list;
1517   char *pos;
1518   char *end;
1519   char old;
1520   int ret;
1521
1522   if (GNUNET_OK !=
1523       GNUNET_CONFIGURATION_get_value_string (cfg, section, option, &list))
1524     return 0;
1525   GNUNET_assert (list != NULL);
1526   ret = 0;
1527   pos = list;
1528   while (1)
1529   {
1530     while (pos[0] == ' ')
1531       pos++;
1532     if (strlen (pos) == 0)
1533       break;
1534     end = pos + 1;
1535     while ((end[0] != ' ') && (end[0] != '\0'))
1536     {
1537       if (end[0] == '\\')
1538       {
1539         switch (end[1])
1540         {
1541         case '\\':
1542         case ' ':
1543           memmove (end, &end[1], strlen (&end[1]) + 1);
1544
1545         case '\0':
1546           /* illegal, but just keep it */
1547           break;
1548
1549         default:
1550           /* illegal, but just ignore that there was a '/' */
1551           break;
1552         }
1553       }
1554       end++;
1555     }
1556     old = end[0];
1557     end[0] = '\0';
1558     if (strlen (pos) > 0)
1559     {
1560       ret++;
1561       if ((cb != NULL) && (GNUNET_OK != cb (cb_cls, pos)))
1562       {
1563         ret = GNUNET_SYSERR;
1564         break;
1565       }
1566     }
1567     if (old == '\0')
1568       break;
1569     pos = end + 1;
1570   }
1571   GNUNET_free (list);
1572   return ret;
1573 }
1574
1575
1576 /**
1577  * FIXME.
1578  *
1579  * @param value FIXME
1580  * @return FIXME
1581  */
1582 static char *
1583 escape_name (const char *value)
1584 {
1585   char *escaped;
1586   const char *rpos;
1587   char *wpos;
1588
1589   escaped = GNUNET_malloc (strlen (value) * 2 + 1);
1590   memset (escaped, 0, strlen (value) * 2 + 1);
1591   rpos = value;
1592   wpos = escaped;
1593   while (rpos[0] != '\0')
1594   {
1595     switch (rpos[0])
1596     {
1597     case '\\':
1598     case ' ':
1599       wpos[0] = '\\';
1600       wpos[1] = rpos[0];
1601       wpos += 2;
1602       break;
1603
1604     default:
1605       wpos[0] = rpos[0];
1606       wpos++;
1607     }
1608     rpos++;
1609   }
1610   return escaped;
1611 }
1612
1613
1614 /**
1615  * FIXME.
1616  *
1617  * @param cls string we compare with (const char*)
1618  * @param fn filename we are currently looking at
1619  * @return #GNUNET_OK if the names do not match, #GNUNET_SYSERR if they do
1620  */
1621 static int
1622 test_match (void *cls, const char *fn)
1623 {
1624   const char *of = cls;
1625
1626   return (0 == strcmp (of, fn)) ? GNUNET_SYSERR : GNUNET_OK;
1627 }
1628
1629
1630 /**
1631  * Append a filename to a configuration value that
1632  * represents a list of filenames
1633  *
1634  * @param cfg configuration to update
1635  * @param section section of interest
1636  * @param option option of interest
1637  * @param value filename to append
1638  * @return #GNUNET_OK on success,
1639  *         #GNUNET_NO if the filename already in the list
1640  *         #GNUNET_SYSERR on error
1641  */
1642 int
1643 GNUNET_CONFIGURATION_append_value_filename (
1644   struct GNUNET_CONFIGURATION_Handle *cfg,
1645   const char *section,
1646   const char *option,
1647   const char *value)
1648 {
1649   char *escaped;
1650   char *old;
1651   char *nw;
1652
1653   if (GNUNET_SYSERR ==
1654       GNUNET_CONFIGURATION_iterate_value_filenames (cfg,
1655                                                     section,
1656                                                     option,
1657                                                     &test_match,
1658                                                     (void *) value))
1659     return GNUNET_NO; /* already exists */
1660   if (GNUNET_OK !=
1661       GNUNET_CONFIGURATION_get_value_string (cfg, section, option, &old))
1662     old = GNUNET_strdup ("");
1663   escaped = escape_name (value);
1664   nw = GNUNET_malloc (strlen (old) + strlen (escaped) + 2);
1665   strcpy (nw, old);
1666   if (strlen (old) > 0)
1667     strcat (nw, " ");
1668   strcat (nw, escaped);
1669   GNUNET_CONFIGURATION_set_value_string (cfg, section, option, nw);
1670   GNUNET_free (old);
1671   GNUNET_free (nw);
1672   GNUNET_free (escaped);
1673   return GNUNET_OK;
1674 }
1675
1676
1677 /**
1678  * Remove a filename from a configuration value that
1679  * represents a list of filenames
1680  *
1681  * @param cfg configuration to update
1682  * @param section section of interest
1683  * @param option option of interest
1684  * @param value filename to remove
1685  * @return #GNUNET_OK on success,
1686  *         #GNUNET_NO if the filename is not in the list,
1687  *         #GNUNET_SYSERR on error
1688  */
1689 int
1690 GNUNET_CONFIGURATION_remove_value_filename (
1691   struct GNUNET_CONFIGURATION_Handle *cfg,
1692   const char *section,
1693   const char *option,
1694   const char *value)
1695 {
1696   char *list;
1697   char *pos;
1698   char *end;
1699   char *match;
1700   char old;
1701
1702   if (GNUNET_OK !=
1703       GNUNET_CONFIGURATION_get_value_string (cfg, section, option, &list))
1704     return GNUNET_NO;
1705   match = escape_name (value);
1706   pos = list;
1707   while (1)
1708   {
1709     while (pos[0] == ' ')
1710       pos++;
1711     if (strlen (pos) == 0)
1712       break;
1713     end = pos + 1;
1714     while ((end[0] != ' ') && (end[0] != '\0'))
1715     {
1716       if (end[0] == '\\')
1717       {
1718         switch (end[1])
1719         {
1720         case '\\':
1721         case ' ':
1722           end++;
1723           break;
1724
1725         case '\0':
1726           /* illegal, but just keep it */
1727           break;
1728
1729         default:
1730           /* illegal, but just ignore that there was a '/' */
1731           break;
1732         }
1733       }
1734       end++;
1735     }
1736     old = end[0];
1737     end[0] = '\0';
1738     if (0 == strcmp (pos, match))
1739     {
1740       if (old != '\0')
1741         memmove (pos, &end[1], strlen (&end[1]) + 1);
1742       else
1743       {
1744         if (pos != list)
1745           pos[-1] = '\0';
1746         else
1747           pos[0] = '\0';
1748       }
1749       GNUNET_CONFIGURATION_set_value_string (cfg, section, option, list);
1750       GNUNET_free (list);
1751       GNUNET_free (match);
1752       return GNUNET_OK;
1753     }
1754     if (old == '\0')
1755       break;
1756     end[0] = old;
1757     pos = end + 1;
1758   }
1759   GNUNET_free (list);
1760   GNUNET_free (match);
1761   return GNUNET_NO;
1762 }
1763
1764
1765 /**
1766  * Wrapper around #GNUNET_CONFIGURATION_parse.  Called on each
1767  * file in a directory, we trigger parsing on those files that
1768  * end with ".conf".
1769  *
1770  * @param cls the cfg
1771  * @param filename file to parse
1772  * @return #GNUNET_OK on success
1773  */
1774 static int
1775 parse_configuration_file (void *cls, const char *filename)
1776 {
1777   struct GNUNET_CONFIGURATION_Handle *cfg = cls;
1778   char *ext;
1779   int ret;
1780
1781   /* Examine file extension */
1782   ext = strrchr (filename, '.');
1783   if ((NULL == ext) || (0 != strcmp (ext, ".conf")))
1784   {
1785     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Skipping file `%s'\n", filename);
1786     return GNUNET_OK;
1787   }
1788
1789   ret = GNUNET_CONFIGURATION_parse (cfg, filename);
1790   return ret;
1791 }
1792
1793
1794 /**
1795  * Load default configuration.  This function will parse the
1796  * defaults from the given defaults_d directory.
1797  *
1798  * @param cfg configuration to update
1799  * @param defaults_d directory with the defaults
1800  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1801  */
1802 int
1803 GNUNET_CONFIGURATION_load_from (struct GNUNET_CONFIGURATION_Handle *cfg,
1804                                 const char *defaults_d)
1805 {
1806   if (GNUNET_SYSERR ==
1807       GNUNET_DISK_directory_scan (defaults_d, &parse_configuration_file, cfg))
1808     return GNUNET_SYSERR; /* no configuration at all found */
1809   return GNUNET_OK;
1810 }
1811
1812
1813 /* end of configuration.c */