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