2 * UCW Library -- Configuration files
4 * (c) 2001--2006 Robert Spalek <robert@ucw.cz>
5 * (c) 2003--2012 Martin Mares <mj@ucw.cz>
7 * This software may be freely distributed and used according to the terms
8 * of the GNU Lesser General Public License.
14 #include <ucw/clists.h>
20 * Configuration contexts
21 * ~~~~~~~~~~~~~~~~~~~~~~
23 * The state of the configuration parser is stored within a configuration context.
24 * One such context is automatically created during initialization of the library
25 * and you need not care about more, as long as you use a single configuration file.
27 * In full generality, you can define as many contexts as you wish and switch
28 * between them. Each thread has its own pointer to the current context, which
29 * must not be shared with other threads.
32 /** Create a new configuration context. **/
33 struct cf_context *cf_new_context(void);
36 * Free a configuration context. The context must not be set as current
37 * for any thread, nor can it be the default context.
39 * All configuration settings made within the context are rolled back
40 * (except when journalling is turned off). All memory allocated on behalf
41 * of the context is freed, which includes memory obtained by calls to
44 void cf_free_context(struct cf_context *cc);
47 * Make the given configuration context current and return the previously
48 * active context. Both the new and the old context may be NULL.
50 struct cf_context *cf_switch_context(struct cf_context *cc);
54 * Safe configuration loading
55 * ~~~~~~~~~~~~~~~~~~~~~~~~~~
57 * These functions can be used to to safely load or reload configuration.
61 * Load configuration from @file.
62 * Returns a non-zero value upon error. In that case, all changes to the
63 * configuration specified in the file are undone.
65 int cf_load(const char *file);
67 * Reload configuration from @file, replace the old one.
68 * If @file is NULL, reload all loaded configuration files and re-apply
69 * bits of configuration passed to cf_set().
70 * Returns a non-zero value upon error. In that case, all configuration
71 * settings are rolled back to the state before calling this function.
73 int cf_reload(const char *file);
75 * Parse some part of configuration passed in @string.
76 * The syntax is the same as in the <<config:,configuration file>>.
77 * Returns a non-zero value upon error. In that case, all changes to the
78 * configuration specified by the already executed parts of the string
81 int cf_set(const char *string);
84 * Sometimes, the configuration is split to multiple files and when only
85 * some of the are loaded, the settings are not consistent -- for example,
86 * they might have been rejected by a commit hook, because a mandatory setting
89 * This function opens a configuration group, in which multiple files can be
90 * loaded and all commit hooks are deferred until the group is closed.
92 void cf_open_group(void);
95 * Close a group opened by cf_open_group(). Returns a non-zero value upon error,
96 * which usually means that a commit hook has failed.
98 int cf_close_group(void);
100 /*** === Data types [[conf_types]] ***/
102 enum cf_class { /** Class of the configuration item. **/
103 CC_END, // end of list
104 CC_STATIC, // single variable or static array
105 CC_DYNAMIC, // dynamically allocated array
106 CC_PARSER, // arbitrary parser function
107 CC_SECTION, // section appears exactly once
108 CC_LIST, // list with 0..many nodes
109 CC_BITMAP // of up to 32 items
112 enum cf_type { /** Type of a single value. **/
113 CT_INT, CT_U64, CT_DOUBLE, // number types
115 CT_STRING, // string type
116 CT_LOOKUP, // in a string table
117 CT_USER // user-defined type
123 * A parser function gets an array of (strdup'ed) strings and a pointer with
124 * the customized information (most likely the target address). It can store
125 * the parsed value anywhere in any way it likes, however it must first call
126 * @cf_journal_block() on the overwritten memory block. It returns an error
127 * message or NULL if everything is all right.
129 typedef char *cf_parser(uns number, char **pars, void *ptr);
131 * A parser function for user-defined types gets a string and a pointer to
132 * the destination variable. It must store the value within [ptr,ptr+size),
133 * where size is fixed for each type. It should not call @cf_journal_block().
135 typedef char *cf_parser1(char *string, void *ptr);
137 * An init- or commit-hook gets a pointer to the section or NULL if this
138 * is the global section. It returns an error message or NULL if everything
139 * is all right. The init-hook should fill in default values (needed for
140 * dynamically allocated nodes of link lists or for filling global variables
141 * that are run-time dependent). The commit-hook should perform sanity
142 * checks and postprocess the parsed values. Commit-hooks must call
143 * @cf_journal_block() too. Caveat! init-hooks for static sections must not
144 * use @cf_malloc() but normal <<memory:xmalloc()>>.
146 typedef char *cf_hook(void *ptr);
148 * Dumps the contents of a variable of a user-defined type.
150 typedef void cf_dumper1(struct fastbuf *fb, void *ptr);
152 * Similar to init-hook, but it copies attributes from another list node
153 * instead of setting the attributes to default values. You have to provide
154 * it if your node contains parsed values and/or sub-lists.
156 typedef char *cf_copier(void *dest, void *src);
158 struct cf_user_type { /** Structure to store information about user-defined variable type. **/
159 uns size; // of the parsed attribute
160 char *name; // name of the type (for dumping)
161 cf_parser1 *parser; // how to parse it
162 cf_dumper1 *dumper; // how to dump the type
166 struct cf_item { /** Single configuration item. **/
167 const char *name; // case insensitive
168 int number; // length of an array or #parameters of a parser (negative means at most)
169 void *ptr; // pointer to a global variable or an offset in a section
171 struct cf_section *sec; // declaration of a section or a list
172 cf_parser *par; // parser function
173 const char * const *lookup; // NULL-terminated sequence of allowed strings for lookups
174 struct cf_user_type *utype; // specification of the user-defined type
176 enum cf_class cls:16; // attribute class
177 enum cf_type type:16; // type of a static or dynamic attribute
180 struct cf_section { /** A section. **/
181 uns size; // 0 for a global block, sizeof(struct) for a section
182 cf_hook *init; // fills in default values (no need to bzero)
183 cf_hook *commit; // verifies parsed data (optional)
184 cf_copier *copy; // copies values from another instance (optional, no need to copy basic attributes)
185 struct cf_item *cfg; // CC_END-terminated array of items
186 uns flags; // for internal use only
194 * You could create the structures manually, but you can use these macros to
199 * Declaration of <<struct_cf_section,`cf_section`>>
200 * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
202 * These macros can be used to configure the <<struct_cf_section,`cf_section`>>
207 * Data type of a section.
208 * If you store the section into a structure, use this macro.
210 * Storing a section into a structure is useful mostly when you may have multiple instances of the
211 * section (eg. <<conf_multi,array or list>>).
216 * cnode n; // This one is for the list itself
221 * static struct clist nodes;
223 * static struct cf_section node = {
224 * CF_TYPE(struct list_node),
226 * CF_STRING("name", PTR_TO(struct list_node, name)),
227 * CF_UNS("value", PTR_TO(struct list_node, value)),
232 * static struct cf_section section = {
233 * CF_LIST("node", &nodes, &node),
237 * You could use <<def_CF_STATIC,`CF_STATIC`>> or <<def_CF_DYNAMIC,`CF_DYNAMIC`>>
238 * macros to create arrays.
240 #define CF_TYPE(s) .size = sizeof(s)
242 * An init <<hooks,hook>>.
243 * You can use this to initialize dynamically allocated items (for a dynamic array or list).
244 * The hook returns an error message or NULL if everything was OK.
246 #define CF_INIT(f) .init = (cf_hook*) f
248 * A commit <<hooks,hook>>.
249 * You can use this one to check sanity of loaded data and postprocess them.
250 * You must call @cf_journal_block() if you change anything.
252 * Return error message or NULL if everything went OK.
254 #define CF_COMMIT(f) .commit = (cf_hook*) f
256 * A <<hooks,copy function>>.
257 * You need to provide one for too complicated sections where a memcpy is not
258 * enough to copy it properly. It happens, for example, when you have a dynamically
259 * allocated section containing a list of other sections.
261 * You return an error message or NULL if you succeed.
263 #define CF_COPY(f) .copy = (cf_copier*) f /** **/
264 #define CF_ITEMS .cfg = ( struct cf_item[] ) /** List of sub-items. **/
265 #define CF_END { .cls = CC_END } /** End of the structure. **/
267 * Declaration of a configuration item
268 * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
270 * Each of these describe single <<struct_cf_item,configuration item>>. They are mostly
271 * for internal use, do not use them directly unless you really know what you are doing.
275 * Static array of items.
276 * Expects you to allocate the memory and provide pointer to it.
278 #define CF_STATIC(n,p,T,t,c) { .cls = CC_STATIC, .type = CT_##T, .name = n, .number = c, .ptr = CHECK_PTR_TYPE(p,t*) }
280 * Dynamic array of items.
281 * Expects you to provide pointer to your pointer to data and it will allocate new memory for it
282 * and set your pointer to it.
284 #define CF_DYNAMIC(n,p,T,t,c) { .cls = CC_DYNAMIC, .type = CT_##T, .name = n, .number = c, .ptr = CHECK_PTR_TYPE(p,t**) }
285 #define CF_PARSER(n,p,f,c) { .cls = CC_PARSER, .name = n, .number = c, .ptr = p, .u.par = (cf_parser*) f } /** A low-level parser. **/
286 #define CF_SECTION(n,p,s) { .cls = CC_SECTION, .name = n, .number = 1, .ptr = p, .u.sec = s } /** A sub-section. **/
287 #define CF_LIST(n,p,s) { .cls = CC_LIST, .name = n, .number = 1, .ptr = CHECK_PTR_TYPE(p,clist*), .u.sec = s } /** A list with sub-items. **/
288 #define CF_BITMAP_INT(n,p) { .cls = CC_BITMAP, .type = CT_INT, .name = n, .number = 1, .ptr = CHECK_PTR_TYPE(p,u32*) } /** A bitmap. **/
289 #define CF_BITMAP_LOOKUP(n,p,t) { .cls = CC_BITMAP, .type = CT_LOOKUP, .name = n, .number = 1, .ptr = CHECK_PTR_TYPE(p,u32*), .u.lookup = t } /** A bitmap with named bits. **/
291 * Basic configuration items
292 * ^^^^^^^^^^^^^^^^^^^^^^^^^
294 * They describe basic data types used in the configuration. This should be enough for
295 * most real-life purposes.
297 * The parameters are as follows:
299 * * @n -- name of the item.
300 * * @p -- pointer to the variable where it shall be stored.
303 #define CF_INT(n,p) CF_STATIC(n,p,INT,int,1) /** Single `int` value. **/
304 #define CF_INT_ARY(n,p,c) CF_STATIC(n,p,INT,int,c) /** Static array of integers. **/
305 #define CF_INT_DYN(n,p,c) CF_DYNAMIC(n,p,INT,int,c) /** Dynamic array of integers. **/
306 #define CF_UNS(n,p) CF_STATIC(n,p,INT,uns,1) /** Single `uns` (`unsigned`) value. **/
307 #define CF_UNS_ARY(n,p,c) CF_STATIC(n,p,INT,uns,c) /** Static array of unsigned integers. **/
308 #define CF_UNS_DYN(n,p,c) CF_DYNAMIC(n,p,INT,uns,c) /** Dynamic array of unsigned integers. **/
309 #define CF_U64(n,p) CF_STATIC(n,p,U64,u64,1) /** Single unsigned 64bit integer (`u64`). **/
310 #define CF_U64_ARY(n,p,c) CF_STATIC(n,p,U64,u64,c) /** Static array of u64s. **/
311 #define CF_U64_DYN(n,p,c) CF_DYNAMIC(n,p,U64,u64,c) /** Dynamic array of u64s. **/
312 #define CF_DOUBLE(n,p) CF_STATIC(n,p,DOUBLE,double,1) /** Single instance of `double`. **/
313 #define CF_DOUBLE_ARY(n,p,c) CF_STATIC(n,p,DOUBLE,double,c) /** Static array of doubles. **/
314 #define CF_DOUBLE_DYN(n,p,c) CF_DYNAMIC(n,p,DOUBLE,double,c) /** Dynamic array of doubles. **/
315 #define CF_IP(n,p) CF_STATIC(n,p,IP,u32,1) /** Single IPv4 address. **/
316 #define CF_IP_ARY(n,p,c) CF_STATIC(n,p,IP,u32,c) /** Static array of IP addresses. **/.
317 #define CF_IP_DYN(n,p,c) CF_DYNAMIC(n,p,IP,u32,c) /** Dynamic array of IP addresses. **/
320 * You provide a pointer to a `char *` variable and it will fill it with
321 * dynamically allocated string. For example:
323 * static char *string = "Default string";
325 * static struct cf_section section = {
327 * CF_STRING("string", &string),
332 #define CF_STRING(n,p) CF_STATIC(n,p,STRING,char*,1)
333 #define CF_STRING_ARY(n,p,c) CF_STATIC(n,p,STRING,char*,c) /** Static array of strings. **/
334 #define CF_STRING_DYN(n,p,c) CF_DYNAMIC(n,p,STRING,char*,c) /** Dynamic array of strings. **/
336 * One string out of a predefined set.
337 * You provide the set as an array of strings terminated by NULL (similar to @argv argument
338 * of main()) as the @t parameter.
340 * The configured variable (pointer to `int`) is set to index of the string.
341 * So, it works this way:
343 * static *strings[] = { "First", "Second", "Third", NULL };
345 * static int variable;
347 * static struct cf_section section = {
349 * CF_LOOKUP("choice", &variable, strings),
354 * Now, if the configuration contains `choice "Second"`, `variable` will be set to 1.
356 #define CF_LOOKUP(n,p,t) { .cls = CC_STATIC, .type = CT_LOOKUP, .name = n, .number = 1, .ptr = CHECK_PTR_TYPE(p,int*), .u.lookup = t }
358 * Static array of strings out of predefined set.
360 #define CF_LOOKUP_ARY(n,p,t,c) { .cls = CC_STATIC, .type = CT_LOOKUP, .name = n, .number = c, .ptr = CHECK_PTR_TYPE(p,int*), .u.lookup = t }
362 * Dynamic array of strings out of predefined set.
364 #define CF_LOOKUP_DYN(n,p,t,c) { .cls = CC_DYNAMIC, .type = CT_LOOKUP, .name = n, .number = c, .ptr = CHECK_PTR_TYPE(p,int**), .u.lookup = t }
366 * A user-defined type.
367 * See <<custom_parser,creating custom parsers>> section if you want to know more.
369 #define CF_USER(n,p,t) { .cls = CC_STATIC, .type = CT_USER, .name = n, .number = 1, .ptr = p, .u.utype = t }
371 * Static array of user-defined types (all of the same type).
372 * See <<custom_parser,creating custom parsers>> section.
374 #define CF_USER_ARY(n,p,t,c) { .cls = CC_STATIC, .type = CT_USER, .name = n, .number = c, .ptr = p, .u.utype = t }
376 * Dynamic array of user-defined types.
377 * See <<custom_parser,creating custom parsers>> section.
379 #define CF_USER_DYN(n,p,t,c) { .cls = CC_DYNAMIC, .type = CT_USER, .name = n, .number = c, .ptr = p, .u.utype = t }
382 * Any number of dynamic array elements
384 #define CF_ANY_NUM -0x7fffffff
386 #define DARY_LEN(a) ((uns*)a)[-1] /** Length of an dynamic array. **/
387 #define DARY_ALLOC(type,len,val...) ((struct { uns l; type a[len]; }) { .l = len, .a = { val } }).a
388 // creates a static instance of a dynamic array
395 * Each configuration context has one or more <<mempool:,memory pools>>, where all
396 * data related to the configuration are stored.
398 * The following set of functions allocate from these pools. The allocated memory
399 * is valid as long as the current configuration (when the configuration file is
400 * reloaded or rolled back, or the context is deleted, it gets lost).
402 * Memory allocated from within custom parsers should be allocated from the pools.
404 * Please note that the pool is not guaranteed to exist before you call cf_load(),
405 * cf_set(), or cf_getopt() on the particular context.
407 struct mempool *cf_get_pool(void); /** Return a pointer to the current configuration pool. **/
408 void *cf_malloc(uns size); /** Returns @size bytes of memory allocated from the current configuration pool. **/
409 void *cf_malloc_zero(uns size); /** Like @cf_malloc(), but zeroes the memory. **/
410 char *cf_strdup(const char *s); /** Copy a string into @cf_malloc()ed memory. **/
411 char *cf_printf(const char *fmt, ...) FORMAT_CHECK(printf,1,2); /** printf() into @cf_malloc()ed memory. **/
418 * The configuration system uses a simple journaling mechanism, which makes
419 * it possible to undo changes to configuration. A typical example is loading
420 * of configuration by cf_load(): internally, it creates a transaction, applies
421 * all changes specified by the configuration and if one of them fails, the whole
422 * journal is replayed to restore the whole original state. Similarly, cf_reload()
423 * uses the journal to switch between configurations.
425 * In most cases, you need not care about the journal, except when you need
426 * to change some data from a <<hooks,hook>>, or if you want to call cf_modify_item() and then
430 * This function can be used to disable the whole journalling mechanism.
431 * It saves some memory, but it makes undoing of configuration changes impossible,
432 * which breaks for example cf_reload().
434 void cf_set_journalling(int enable);
436 * When a block of memory is about to be changed, put the old value
437 * into journal with this function. You need to call it from a <<hooks,commit hook>>
438 * if you change anything. It is used internally by low-level parsers.
439 * <<custom_parser,Custom parsers>> do not need to call it, it is called
442 void cf_journal_block(void *ptr, uns len);
443 #define CF_JOURNAL_VAR(var) cf_journal_block(&(var), sizeof(var)) // Store a single value into the journal
445 struct cf_journal_item; /** Opaque identifier of the journal state. **/
447 * Starts a new transaction. It returns the current state so you can
448 * get back to it. The @new_pool parameter tells if a new memory pool
449 * should be created and used from now.
451 struct cf_journal_item *cf_journal_new_transaction(uns new_pool);
453 * Marks current state as a complete transaction. The @new_pool
454 * parameter tells if the transaction was created with new memory pool
455 * (the parameter must be the same as the one with
456 * @cf_journal_new_transaction() was called with). The @oldj parameter
457 * is the journal state returned from last
458 * @cf_journal_new_transaction() call.
460 void cf_journal_commit_transaction(uns new_pool, struct cf_journal_item *oldj);
462 * Returns to an old journal state, reverting anything the current
463 * transaction did. The @new_pool parameter must be the same as the
464 * one you used when you created the transaction. The @oldj parameter
465 * is the journal state you got from @cf_journal_new_transaction() --
466 * it is the state to return to.
468 void cf_journal_rollback_transaction(uns new_pool, struct cf_journal_item *oldj);
472 * Section declaration
473 * ~~~~~~~~~~~~~~~~~~~
477 * Plug another top-level section into the configuration system.
478 * @name is the name in the configuration file,
479 * @sec is pointer to the section description.
480 * If @allow_unknown is set to 0 and a variable not described in @sec
481 * is found in the configuration file, it produces an error.
482 * If you set it to 1, all such variables are ignored.
484 void cf_declare_section(const char *name, struct cf_section *sec, uns allow_unknown);
486 * If you have a section in a structure and you want to initialize it
487 * (eg. if you want a copy of default values outside the configuration),
488 * you can use this. It initializes it recursively.
490 * This is used mostly internally. You probably do not need it.
492 void cf_init_section(const char *name, struct cf_section *sec, void *ptr, uns do_bzero);
496 * Parsers for basic types
497 * ~~~~~~~~~~~~~~~~~~~~~~~
499 * Each of them gets a string to parse and pointer to store the value.
500 * It returns either NULL or error message.
502 * The parsers support units. See <<config:units,their list>>.
504 char *cf_parse_int(const char *str, int *ptr); /** Parser for integers. **/
505 char *cf_parse_u64(const char *str, u64 *ptr); /** Parser for 64 unsigned integers. **/
506 char *cf_parse_double(const char *str, double *ptr); /** Parser for doubles. **/
507 char *cf_parse_ip(const char *p, u32 *varp); /** Parser for IP addresses. **/
514 * Direct access to configuration items.
515 * You probably should not need this, but in your do, you have to handle
516 * <<journal,journalling>> yourself.
520 * List of operations used on items.
521 * This macro is used to generate internal source code,
522 * but you may be interested in the list of operations it creates.
524 * Each operation corresponds to the same-named operation
525 * described in <<config:operations,configuration syntax>>.
527 #define CF_OPERATIONS T(CLOSE) T(SET) T(CLEAR) T(ALL) \
528 T(APPEND) T(PREPEND) T(REMOVE) T(EDIT) T(AFTER) T(BEFORE) T(COPY) T(RESET)
529 /* Closing brace finishes previous block.
530 * Basic attributes (static, dynamic, parsed) can be used with SET.
531 * Dynamic arrays can be used with SET, APPEND, PREPEND.
532 * Sections can be used with SET.
533 * Lists can be used with everything. */
535 enum cf_operation { CF_OPERATIONS }; /** Allowed operations on items. See <<def_CF_OPERATIONS,`CF_OPERATIONS`>> for list (they have an `OP_` prefix -- it means you use `OP_SET` instead of just `SET`). **/
539 * Searches for a configuration item called @name.
540 * If it is found, it is copied into @item and NULL is returned.
541 * Otherwise, an error is returned and @item is zeroed.
543 char *cf_find_item(const char *name, struct cf_item *item);
545 * Performs a single operation on a given item.
547 char *cf_modify_item(struct cf_item *item, enum cf_operation op, int number, char **pars);
557 * Write the current state of all configuration items into @fb.
559 void cf_dump_sections(struct fastbuf *fb);