]> mj.ucw.cz Git - libucw.git/blob - ucw/conf.h
bef4553e155a5477cb1abb664d27c1da62785be1
[libucw.git] / ucw / conf.h
1 /*
2  *      UCW Library -- Configuration files
3  *
4  *      (c) 2001--2006 Robert Spalek <robert@ucw.cz>
5  *      (c) 2003--2012 Martin Mares <mj@ucw.cz>
6  *
7  *      This software may be freely distributed and used according to the terms
8  *      of the GNU Lesser General Public License.
9  */
10
11 #ifndef _UCW_CONF_H
12 #define _UCW_CONF_H
13
14 #include <ucw/clists.h>
15
16 struct mempool;
17
18 /***
19  * [[conf_ctxt]]
20  * Configuration contexts
21  * ~~~~~~~~~~~~~~~~~~~~~~
22  *
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.
26  *
27  * In full generality, you can define as many context 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.
30  ***/
31
32 /** Create a new configuration context. **/
33 struct cf_context *cf_new_context(void);
34
35 /**
36  * Free a configuration context. The context must not be set as current
37  * for any thread, nor can it be the default context.
38  *
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
42  * cf_malloc().
43  **/
44 void cf_free_context(struct cf_context *cc);
45
46 /**
47  * Make the given configuration context current and return the previously
48  * active context. Both the new and the old context may be NULL.
49  **/
50 struct cf_context *cf_switch_context(struct cf_context *cc);
51
52 /***
53  * [[conf_load]]
54  * Safe configuration loading
55  * ~~~~~~~~~~~~~~~~~~~~~~~~~~
56  *
57  * These functions can be used to to safely load or reload configuration.
58  */
59
60 int cf_reload(const char *file);        /** Reload configuration from @file, replace the old one. **/
61 int cf_load(const char *file);          /** Load configuration from @file. If @file is NULL, reload all loaded configuration files. **/
62 /**
63  * Parse some part of configuration passed in @string.
64  * The syntax is the same as in the <<config:,configuration file>>.
65  **/
66 int cf_set(const char *string);
67
68 /*** === Data types [[conf_types]] ***/
69
70 enum cf_class {                         /** Class of the configuration item. **/
71   CC_END,                               // end of list
72   CC_STATIC,                            // single variable or static array
73   CC_DYNAMIC,                           // dynamically allocated array
74   CC_PARSER,                            // arbitrary parser function
75   CC_SECTION,                           // section appears exactly once
76   CC_LIST,                              // list with 0..many nodes
77   CC_BITMAP                             // of up to 32 items
78 };
79
80 enum cf_type {                          /** Type of a single value. **/
81   CT_INT, CT_U64, CT_DOUBLE,            // number types
82   CT_IP,                                // IP address
83   CT_STRING,                            // string type
84   CT_LOOKUP,                            // in a string table
85   CT_USER                               // user-defined type
86 };
87
88 struct fastbuf;
89
90 /**
91  * A parser function gets an array of (strdup'ed) strings and a pointer with
92  * the customized information (most likely the target address).  It can store
93  * the parsed value anywhere in any way it likes, however it must first call
94  * @cf_journal_block() on the overwritten memory block.  It returns an error
95  * message or NULL if everything is all right.
96  **/
97 typedef char *cf_parser(uns number, char **pars, void *ptr);
98 /**
99  * A parser function for user-defined types gets a string and a pointer to
100  * the destination variable.  It must store the value within [ptr,ptr+size),
101  * where size is fixed for each type.  It should not call @cf_journal_block().
102  **/
103 typedef char *cf_parser1(char *string, void *ptr);
104 /**
105  * An init- or commit-hook gets a pointer to the section or NULL if this
106  * is the global section.  It returns an error message or NULL if everything
107  * is all right.  The init-hook should fill in default values (needed for
108  * dynamically allocated nodes of link lists or for filling global variables
109  * that are run-time dependent).  The commit-hook should perform sanity
110  * checks and postprocess the parsed values.  Commit-hooks must call
111  * @cf_journal_block() too.  Caveat! init-hooks for static sections must not
112  * use @cf_malloc() but normal <<memory:xmalloc()>>.
113  **/
114 typedef char *cf_hook(void *ptr);
115 /**
116  * Dumps the contents of a variable of a user-defined type.
117  **/
118 typedef void cf_dumper1(struct fastbuf *fb, void *ptr);
119 /**
120  * Similar to init-hook, but it copies attributes from another list node
121  * instead of setting the attributes to default values.  You have to provide
122  * it if your node contains parsed values and/or sub-lists.
123  **/
124 typedef char *cf_copier(void *dest, void *src);
125
126 struct cf_user_type {                   /** Structure to store information about user-defined variable type. **/
127   uns size;                             // of the parsed attribute
128   char *name;                           // name of the type (for dumping)
129   cf_parser1 *parser;                   // how to parse it
130   cf_dumper1 *dumper;                   // how to dump the type
131 };
132
133 struct cf_section;
134 struct cf_item {                        /** Single configuration item. **/
135   const char *name;                     // case insensitive
136   int number;                           // length of an array or #parameters of a parser (negative means at most)
137   void *ptr;                            // pointer to a global variable or an offset in a section
138   union cf_union {
139     struct cf_section *sec;             // declaration of a section or a list
140     cf_parser *par;                     // parser function
141     const char * const *lookup;         // NULL-terminated sequence of allowed strings for lookups
142     struct cf_user_type *utype;         // specification of the user-defined type
143   } u;
144   enum cf_class cls:16;                 // attribute class
145   enum cf_type type:16;                 // type of a static or dynamic attribute
146 };
147
148 struct cf_section {                     /** A section. **/
149   uns size;                             // 0 for a global block, sizeof(struct) for a section
150   cf_hook *init;                        // fills in default values (no need to bzero)
151   cf_hook *commit;                      // verifies parsed data (optional)
152   cf_copier *copy;                      // copies values from another instance (optional, no need to copy basic attributes)
153   struct cf_item *cfg;                  // CC_END-terminated array of items
154   uns flags;                            // for internal use only
155 };
156
157 /***
158  * [[conf_macros]]
159  * Convenience macros
160  * ~~~~~~~~~~~~~~~~~~
161  *
162  * You could create the structures manually, but you can use these macros to
163  * save some typing.
164  */
165
166 /***
167  * Declaration of <<struct_cf_section,`cf_section`>>
168  * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
169  *
170  * These macros can be used to configure the <<struct_cf_section,`cf_section`>>
171  * structure.
172  ***/
173
174 /**
175  * Data type of a section.
176  * If you store the section into a structure, use this macro.
177  *
178  * Storing a section into a structure is useful mostly when you may have multiple instances of the
179  * section (eg. <<conf_multi,array or list>>).
180  *
181  * Example:
182  *
183  *   struct list_node {
184  *     cnode n;         // This one is for the list itself
185  *     char *name;
186  *     uns value;
187  *   };
188  *
189  *   static struct clist nodes;
190  *
191  *   static struct cf_section node = {
192  *     CF_TYPE(struct list_node),
193  *     CF_ITEMS {
194  *       CF_STRING("name", PTR_TO(struct list_node, name)),
195  *       CF_UNS("value", PTR_TO(struct list_node, value)),
196  *       CF_END
197  *     }
198  *   };
199  *
200  *   static struct cf_section section = {
201  *     CF_LIST("node", &nodes, &node),
202  *     CF_END
203  *   };
204  *
205  * You could use <<def_CF_STATIC,`CF_STATIC`>> or <<def_CF_DYNAMIC,`CF_DYNAMIC`>>
206  * macros to create arrays.
207  */
208 #define CF_TYPE(s)      .size = sizeof(s)
209 /**
210  * An init <<hooks,hook>>.
211  * You can use this to initialize dynamically allocated items (for a dynamic array or list).
212  * The hook returns an error message or NULL if everything was OK.
213  */
214 #define CF_INIT(f)      .init = (cf_hook*) f
215 /**
216  * A commit <<hooks,hook>>.
217  * You can use this one to check sanity of loaded data and postprocess them.
218  * You must call @cf_journal_block() if you change anything.
219  *
220  * Return error message or NULL if everything went OK.
221  **/
222 #define CF_COMMIT(f)    .commit = (cf_hook*) f
223 /**
224  * A <<hooks,copy function>>.
225  * You need to provide one for too complicated sections where a memcpy is not
226  * enough to copy it properly. It happens, for example, when you have a dynamically
227  * allocated section containing a list of other sections.
228  *
229  * You return an error message or NULL if you succeed.
230  **/
231 #define CF_COPY(f)      .copy = (cf_copier*) f          /**  **/
232 #define CF_ITEMS        .cfg = ( struct cf_item[] )     /** List of sub-items. **/
233 #define CF_END          { .cls = CC_END }               /** End of the structure. **/
234 /***
235  * Declaration of a configuration item
236  * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
237  *
238  * Each of these describe single <<struct_cf_item,configuration item>>. They are mostly
239  * for internal use, do not use them directly unless you really know what you are doing.
240  ***/
241
242 /**
243  * Static array of items.
244  * Expects you to allocate the memory and provide pointer to it.
245  **/
246 #define CF_STATIC(n,p,T,t,c)    { .cls = CC_STATIC, .type = CT_##T, .name = n, .number = c, .ptr = CHECK_PTR_TYPE(p,t*) }
247 /**
248  * Dynamic array of items.
249  * Expects you to provide pointer to your pointer to data and it will allocate new memory for it
250  * and set your pointer to it.
251  **/
252 #define CF_DYNAMIC(n,p,T,t,c)   { .cls = CC_DYNAMIC, .type = CT_##T, .name = n, .number = c, .ptr = CHECK_PTR_TYPE(p,t**) }
253 #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. **/
254 #define CF_SECTION(n,p,s)       { .cls = CC_SECTION, .name = n, .number = 1, .ptr = p, .u.sec = s }                                             /** A sub-section. **/
255 #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. **/
256 #define CF_BITMAP_INT(n,p)      { .cls = CC_BITMAP, .type = CT_INT, .name = n, .number = 1, .ptr = CHECK_PTR_TYPE(p,u32*) }                     /** A bitmap. **/
257 #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. **/
258 /***
259  * Basic configuration items
260  * ^^^^^^^^^^^^^^^^^^^^^^^^^
261  *
262  * They describe basic data types used in the configuration. This should be enough for
263  * most real-life purposes.
264  *
265  * The parameters are as follows:
266  *
267  * * @n -- name of the item.
268  * * @p -- pointer to the variable where it shall be stored.
269  * * @c -- count.
270  **/
271 #define CF_INT(n,p)             CF_STATIC(n,p,INT,int,1)                /** Single `int` value. **/
272 #define CF_INT_ARY(n,p,c)       CF_STATIC(n,p,INT,int,c)                /** Static array of integers. **/
273 #define CF_INT_DYN(n,p,c)       CF_DYNAMIC(n,p,INT,int,c)               /** Dynamic array of integers. **/
274 #define CF_UNS(n,p)             CF_STATIC(n,p,INT,uns,1)                /** Single `uns` (`unsigned`) value. **/
275 #define CF_UNS_ARY(n,p,c)       CF_STATIC(n,p,INT,uns,c)                /** Static array of unsigned integers. **/
276 #define CF_UNS_DYN(n,p,c)       CF_DYNAMIC(n,p,INT,uns,c)               /** Dynamic array of unsigned integers. **/
277 #define CF_U64(n,p)             CF_STATIC(n,p,U64,u64,1)                /** Single unsigned 64bit integer (`u64`). **/
278 #define CF_U64_ARY(n,p,c)       CF_STATIC(n,p,U64,u64,c)                /** Static array of u64s. **/
279 #define CF_U64_DYN(n,p,c)       CF_DYNAMIC(n,p,U64,u64,c)               /** Dynamic array of u64s. **/
280 #define CF_DOUBLE(n,p)          CF_STATIC(n,p,DOUBLE,double,1)          /** Single instance of `double`. **/
281 #define CF_DOUBLE_ARY(n,p,c)    CF_STATIC(n,p,DOUBLE,double,c)          /** Static array of doubles. **/
282 #define CF_DOUBLE_DYN(n,p,c)    CF_DYNAMIC(n,p,DOUBLE,double,c)         /** Dynamic array of doubles. **/
283 #define CF_IP(n,p)              CF_STATIC(n,p,IP,u32,1)                 /** Single IPv4 address. **/
284 #define CF_IP_ARY(n,p,c)        CF_STATIC(n,p,IP,u32,c)                 /** Static array of IP addresses. **/.
285 #define CF_IP_DYN(n,p,c)        CF_DYNAMIC(n,p,IP,u32,c)                /** Dynamic array of IP addresses. **/
286 /**
287  * A string.
288  * You provide a pointer to a `char *` variable and it will fill it with
289  * dynamically allocated string. For example:
290  *
291  *   static char *string = "Default string";
292  *
293  *   static struct cf_section section = {
294  *     CF_ITEMS {
295  *       CF_STRING("string", &string),
296  *       CF_END
297  *     }
298  *   };
299  **/
300 #define CF_STRING(n,p)          CF_STATIC(n,p,STRING,char*,1)
301 #define CF_STRING_ARY(n,p,c)    CF_STATIC(n,p,STRING,char*,c)           /** Static array of strings. **/
302 #define CF_STRING_DYN(n,p,c)    CF_DYNAMIC(n,p,STRING,char*,c)          /** Dynamic array of strings. **/
303 /**
304  * One string out of a predefined set.
305  * You provide the set as an array of strings terminated by NULL (similar to @argv argument
306  * of main()) as the @t parameter.
307  *
308  * The configured variable (pointer to `int`) is set to index of the string.
309  * So, it works this way:
310  *
311  *   static *strings[] = { "First", "Second", "Third", NULL };
312  *
313  *   static int variable;
314  *
315  *   static struct cf_section section = {
316  *     CF_ITEMS {
317  *       CF_LOOKUP("choice", &variable, strings),
318  *       CF_END
319  *     }
320  *   };
321  *
322  * Now, if the configuration contains `choice "Second"`, `variable` will be set to 1.
323  **/
324 #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 }
325 /**
326  * Static array of strings out of predefined set.
327  **/
328 #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 }
329 /**
330  * Dynamic array of strings out of predefined set.
331  **/
332 #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 }
333 /**
334  * A user-defined type.
335  * See <<custom_parser,creating custom parsers>> section if you want to know more.
336  **/
337 #define CF_USER(n,p,t)          { .cls = CC_STATIC, .type = CT_USER, .name = n, .number = 1, .ptr = p, .u.utype = t }
338 /**
339  * Static array of user-defined types (all of the same type).
340  * See <<custom_parser,creating custom parsers>> section.
341  **/
342 #define CF_USER_ARY(n,p,t,c)    { .cls = CC_STATIC, .type = CT_USER, .name = n, .number = c, .ptr = p, .u.utype = t }
343 /**
344  * Dynamic array of user-defined types.
345  * See <<custom_parser,creating custom parsers>> section.
346  **/
347 #define CF_USER_DYN(n,p,t,c)    { .cls = CC_DYNAMIC, .type = CT_USER, .name = n, .number = c, .ptr = p, .u.utype = t }
348
349 /**
350  * Any number of dynamic array elements
351  **/
352 #define CF_ANY_NUM              -0x7fffffff
353
354 #define DARY_LEN(a) ((uns*)a)[-1]       /** Length of an dynamic array. **/
355 #define DARY_ALLOC(type,len,val...) ((struct { uns l; type a[len]; }) { .l = len, .a = { val } }).a
356   // creates a static instance of a dynamic array
357
358 /***
359  * [[alloc]]
360  * Memory allocation
361  * ~~~~~~~~~~~~~~~~~
362  *
363  * Each configuration context has one or more <<mempool:,memory pools>>, where all
364  * data related to the configuration are stored.
365  *
366  * The following set of functions allocate from these pools. The allocated memory
367  * is valid as long as the current configuration (when the configuration file is
368  * reloaded or rolled back, or the context is deleted, it gets lost).
369  *
370  * Memory allocated from within custom parsers should be allocated from the pools.
371  ***/
372 struct mempool *cf_get_pool(void); /** Return a pointer to the current configuration pool. **/
373 void *cf_malloc(uns size);      /** Returns @size bytes of memory allocated from the current configuration pool. **/
374 void *cf_malloc_zero(uns size); /** Like @cf_malloc(), but zeroes the memory. **/
375 char *cf_strdup(const char *s); /** Copy a string into @cf_malloc()ed memory. **/
376 char *cf_printf(const char *fmt, ...) FORMAT_CHECK(printf,1,2); /** printf() into @cf_malloc()ed memory. **/
377
378 /***
379  * [[journal]]
380  * Undo journal
381  * ~~~~~~~~~~~~
382  *
383  * The configuration system uses journaling to safely reload
384  * configuration. It begins a transaction and tries to load the
385  * configuration. If it fails, it restores the original state.
386  *
387  * The behaviour of journal is described in <<reload,reloading configuration>>.
388  ***/
389 /**
390  * By default, the configuration mechanism remembers all changes in a journal,
391  * so that the configuration can be rolled back or reloaded. This function
392  * can be used to disable journalling, which saves some memory.
393  **/
394 void cf_set_journalling(int enable);
395 /**
396  * When a block of memory is about to be changed, put the old value
397  * into journal with this function. You need to call it from a <<hooks,commit hook>>
398  * if you change anything. It is used internally by low-level parsers.
399  * <<custom_parser,Custom parsers>> do not need to call it, it is called
400  * before them.
401  **/
402 void cf_journal_block(void *ptr, uns len);
403 #define CF_JOURNAL_VAR(var) cf_journal_block(&(var), sizeof(var))       // Store single value into journal.
404
405 struct cf_journal_item;         /** Opaque identifier of the journal state. **/
406 /**
407  * Starts a new transaction. It returns the current state so you can
408  * get back to it. The @new_pool parameter tells if a new memory pool
409  * should be created and used from now.
410  **/
411 struct cf_journal_item *cf_journal_new_transaction(uns new_pool);
412 /**
413  * Marks current state as a complete transaction. The @new_pool
414  * parameter tells if the transaction was created with new memory pool
415  * (the parameter must be the same as the one with
416  * @cf_journal_new_transaction() was called with). The @oldj parameter
417  * is the journal state returned from last
418  * @cf_journal_new_transaction() call.
419  **/
420 void cf_journal_commit_transaction(uns new_pool, struct cf_journal_item *oldj);
421 /**
422  * Returns to an old journal state, reverting anything the current
423  * transaction did. The @new_pool parameter must be the same as the
424  * one you used when you created the transaction. The @oldj parameter
425  * is the journal state you got from @cf_journal_new_transaction() --
426  * it is the state to return to.
427  **/
428 void cf_journal_rollback_transaction(uns new_pool, struct cf_journal_item *oldj);
429
430 /***
431  * [[declare]]
432  * Section declaration
433  * ~~~~~~~~~~~~~~~~~~~
434  **/
435
436 /**
437  * Plug another top-level section into the configuration system.
438  * @name is the name in the configuration file,
439  * @sec is pointer to the section description.
440  * If @allow_unknown is set to 0 and a variable not described in @sec
441  * is found in the configuration file, it produces an error.
442  * If you set it to 1, all such variables are ignored.
443  **/
444 void cf_declare_section(const char *name, struct cf_section *sec, uns allow_unknown);
445 /**
446  * If you have a section in a structure and you want to initialize it
447  * (eg. if you want a copy of default values outside the configuration),
448  * you can use this. It initializes it recursively.
449  *
450  * This is used mostly internally. You probably do not need it.
451  **/
452 void cf_init_section(const char *name, struct cf_section *sec, void *ptr, uns do_bzero);
453
454 /***
455  * [[bparser]]
456  * Parsers for basic types
457  * ~~~~~~~~~~~~~~~~~~~~~~~
458  *
459  * Each of them gets a string to parse and pointer to store the value.
460  * It returns either NULL or error message.
461  *
462  * The parsers support units. See <<config:units,their list>>.
463  ***/
464 char *cf_parse_int(const char *str, int *ptr);          /** Parser for integers. **/
465 char *cf_parse_u64(const char *str, u64 *ptr);          /** Parser for 64 unsigned integers. **/
466 char *cf_parse_double(const char *str, double *ptr);    /** Parser for doubles. **/
467 char *cf_parse_ip(const char *p, u32 *varp);            /** Parser for IP addresses. **/
468
469 /***
470  * [[conf_direct]]
471  * Direct access
472  * ~~~~~~~~~~~~~
473  *
474  * Direct access to configuration items.
475  * You probably should not need this.
476  ***/
477
478 /**
479  * List of operations used on items.
480  * This macro is used to generate internal source code,
481  * but you may be interested in the list of operations it creates.
482  *
483  * Each operation corresponds to the same-named operation
484  * described in <<config:operations,configuration syntax>>.
485  **/
486 #define CF_OPERATIONS T(CLOSE) T(SET) T(CLEAR) T(ALL) \
487   T(APPEND) T(PREPEND) T(REMOVE) T(EDIT) T(AFTER) T(BEFORE) T(COPY) T(RESET)
488   /* Closing brace finishes previous block.
489    * Basic attributes (static, dynamic, parsed) can be used with SET.
490    * Dynamic arrays can be used with SET, APPEND, PREPEND.
491    * Sections can be used with SET.
492    * Lists can be used with everything. */
493 #define T(x) OP_##x,
494 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`). **/
495 #undef T
496
497 /**
498  * Searches for a configuration item called @name.
499  * If it is found, it is copied into @item and NULL is returned.
500  * Otherwise, an error is returned and @item is zeroed.
501  **/
502 char *cf_find_item(const char *name, struct cf_item *item);
503 /**
504  * Performs a single operation on a given item.
505  **/
506 char *cf_modify_item(struct cf_item *item, enum cf_operation op, int number, char **pars);
507
508 /***
509  * [[conf_dump]]
510  * Debug dumping
511  * ~~~~~~~~~~~~~
512  ***/
513
514 struct fastbuf;
515 /**
516  * Take everything and write it into @fb.
517  **/
518 void cf_dump_sections(struct fastbuf *fb);
519
520 #endif