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