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