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