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