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