- refactor to check messages from both enc systems
[oweals/gnunet.git] / src / util / configuration.c
1 /*
2      This file is part of GNUnet.
3      Copyright (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 *cfg,
576                                        GNUNET_CONFIGURATION_Section_Iterator iter,
577                                        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 *cfg,
923                                      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  * Get crockford32-encoded fixed-size binary data from a configuration.
1039  *
1040  * @param cfg configuration to access
1041  * @param section section to access
1042  * @param option option to access
1043  * @param buf where to store the decoded binary result
1044  * @param buf_size exact number of bytes to store in @a buf
1045  * @return #GNUNET_OK on success
1046  *         #GNUNET_NO is the value does not exist
1047  *         #GNUNET_SYSERR on decoding error
1048  */
1049 int
1050 GNUNET_CONFIGURATION_get_data (const struct GNUNET_CONFIGURATION_Handle *cfg,
1051                                const char *section,
1052                                const char *option,
1053                                void *buf,
1054                                size_t buf_size)
1055 {
1056   char *enc;
1057   int res;
1058   size_t data_size;
1059
1060   if (GNUNET_OK !=
1061       (res = GNUNET_CONFIGURATION_get_value_string (cfg,
1062                                                     section,
1063                                                     option,
1064                                                     &enc)))
1065     return res;
1066   data_size = (strlen (enc) * 5) / 8;
1067   if (data_size != buf_size)
1068   {
1069     GNUNET_free (enc);
1070     return GNUNET_SYSERR;
1071   }
1072   if (GNUNET_OK !=
1073       GNUNET_STRINGS_string_to_data (enc,
1074                                      strlen (enc),
1075                                      buf, buf_size))
1076   {
1077     GNUNET_free (enc);
1078     return GNUNET_SYSERR;
1079   }
1080   GNUNET_free (enc);
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 */