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