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