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