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