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