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