]> mj.ucw.cz Git - libucw.git/blob - ucw/conf.h
bf106274b2f239ad900041a8a2fd0ee2743da9c3
[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  * If you do not create contexts explicitly, the library will create one for you
25  * and you need not care, as long as you use a single configuration file.
26  *
27  * In whole 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.
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  * Return a pointer to the current context, or create the default context
54  * if there is no context active.
55  **/
56 struct cf_context *cf_obtain_context(void);
57
58 /**
59  * Set name of default configuration file. May be NULL if there should be
60  * no such default.
61  * FIXME: Explain where it is used
62  **/
63 void cf_set_default_file(char *name);
64
65 /**
66  * Set name of environment variable used to override the name of the default
67  * configuration file. May be NULL if there should be no such variable.
68  **/
69 void cf_set_env_override(char *name);
70
71 /*** === Data types [[conf_types]] ***/
72
73 enum cf_class {                         /** Class of the configuration item. **/
74   CC_END,                               // end of list
75   CC_STATIC,                            // single variable or static array
76   CC_DYNAMIC,                           // dynamically allocated array
77   CC_PARSER,                            // arbitrary parser function
78   CC_SECTION,                           // section appears exactly once
79   CC_LIST,                              // list with 0..many nodes
80   CC_BITMAP                             // of up to 32 items
81 };
82
83 enum cf_type {                          /** Type of a single value. **/
84   CT_INT, CT_U64, CT_DOUBLE,            // number types
85   CT_IP,                                // IP address
86   CT_STRING,                            // string type
87   CT_LOOKUP,                            // in a string table
88   CT_USER                               // user-defined type
89 };
90
91 struct fastbuf;
92
93 /**
94  * A parser function gets an array of (strdup'ed) strings and a pointer with
95  * the customized information (most likely the target address).  It can store
96  * the parsed value anywhere in any way it likes, however it must first call
97  * @cf_journal_block() on the overwritten memory block.  It returns an error
98  * message or NULL if everything is all right.
99  **/
100 typedef char *cf_parser(uns number, char **pars, void *ptr);
101 /**
102  * A parser function for user-defined types gets a string and a pointer to
103  * the destination variable.  It must store the value within [ptr,ptr+size),
104  * where size is fixed for each type.  It should not call @cf_journal_block().
105  **/
106 typedef char *cf_parser1(char *string, void *ptr);
107 /**
108  * An init- or commit-hook gets a pointer to the section or NULL if this
109  * is the global section.  It returns an error message or NULL if everything
110  * is all right.  The init-hook should fill in default values (needed for
111  * dynamically allocated nodes of link lists or for filling global variables
112  * that are run-time dependent).  The commit-hook should perform sanity
113  * checks and postprocess the parsed values.  Commit-hooks must call
114  * @cf_journal_block() too.  Caveat! init-hooks for static sections must not
115  * use @cf_malloc() but normal <<memory:xmalloc()>>.
116  **/
117 typedef char *cf_hook(void *ptr);
118 /**
119  * Dumps the contents of a variable of a user-defined type.
120  **/
121 typedef void cf_dumper1(struct fastbuf *fb, void *ptr);
122 /**
123  * Similar to init-hook, but it copies attributes from another list node
124  * instead of setting the attributes to default values.  You have to provide
125  * it if your node contains parsed values and/or sub-lists.
126  **/
127 typedef char *cf_copier(void *dest, void *src);
128
129 struct cf_user_type {                   /** Structure to store information about user-defined variable type. **/
130   uns size;                             // of the parsed attribute
131   char *name;                           // name of the type (for dumping)
132   cf_parser1 *parser;                   // how to parse it
133   cf_dumper1 *dumper;                   // how to dump the type
134 };
135
136 struct cf_section;
137 struct cf_item {                        /** Single configuration item. **/
138   const char *name;                     // case insensitive
139   int number;                           // length of an array or #parameters of a parser (negative means at most)
140   void *ptr;                            // pointer to a global variable or an offset in a section
141   union cf_union {
142     struct cf_section *sec;             // declaration of a section or a list
143     cf_parser *par;                     // parser function
144     const char * const *lookup;         // NULL-terminated sequence of allowed strings for lookups
145     struct cf_user_type *utype;         // specification of the user-defined type
146   } u;
147   enum cf_class cls:16;                 // attribute class
148   enum cf_type type:16;                 // type of a static or dynamic attribute
149 };
150
151 struct cf_section {                     /** A section. **/
152   uns size;                             // 0 for a global block, sizeof(struct) for a section
153   cf_hook *init;                        // fills in default values (no need to bzero)
154   cf_hook *commit;                      // verifies parsed data (optional)
155   cf_copier *copy;                      // copies values from another instance (optional, no need to copy basic attributes)
156   struct cf_item *cfg;                  // CC_END-terminated array of items
157   uns flags;                            // for internal use only
158 };
159
160 /***
161  * [[conf_macros]]
162  * Convenience macros
163  * ~~~~~~~~~~~~~~~~~~
164  *
165  * You could create the structures manually, but you can use these macros to
166  * save some typing.
167  */
168
169 /***
170  * Declaration of <<struct_cf_section,`cf_section`>>
171  * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
172  *
173  * These macros can be used to configure the <<struct_cf_section,`cf_section`>>
174  * structure.
175  ***/
176
177 /**
178  * Data type of a section.
179  * If you store the section into a structure, use this macro.
180  *
181  * Storing a section into a structure is useful mostly when you may have multiple instances of the
182  * section (eg. <<conf_multi,array or list>>).
183  *
184  * Example:
185  *
186  *   struct list_node {
187  *     cnode n;         // This one is for the list itself
188  *     char *name;
189  *     uns value;
190  *   };
191  *
192  *   static struct clist nodes;
193  *
194  *   static struct cf_section node = {
195  *     CF_TYPE(struct list_node),
196  *     CF_ITEMS {
197  *       CF_STRING("name", PTR_TO(struct list_node, name)),
198  *       CF_UNS("value", PTR_TO(struct list_node, value)),
199  *       CF_END
200  *     }
201  *   };
202  *
203  *   static struct cf_section section = {
204  *     CF_LIST("node", &nodes, &node),
205  *     CF_END
206  *   };
207  *
208  * You could use <<def_CF_STATIC,`CF_STATIC`>> or <<def_CF_DYNAMIC,`CF_DYNAMIC`>>
209  * macros to create arrays.
210  */
211 #define CF_TYPE(s)      .size = sizeof(s)
212 /**
213  * An init <<hooks,hook>>.
214  * You can use this to initialize dynamically allocated items (for a dynamic array or list).
215  * The hook returns an error message or NULL if everything was OK.
216  */
217 #define CF_INIT(f)      .init = (cf_hook*) f
218 /**
219  * A commit <<hooks,hook>>.
220  * You can use this one to check sanity of loaded data and postprocess them.
221  * You must call @cf_journal_block() if you change anything.
222  *
223  * Return error message or NULL if everything went OK.
224  **/
225 #define CF_COMMIT(f)    .commit = (cf_hook*) f
226 /**
227  * A <<hooks,copy function>>.
228  * You need to provide one for too complicated sections where a memcpy is not
229  * enough to copy it properly. It happens, for example, when you have a dynamically
230  * allocated section containing a list of other sections.
231  *
232  * You return an error message or NULL if you succeed.
233  **/
234 #define CF_COPY(f)      .copy = (cf_copier*) f          /**  **/
235 #define CF_ITEMS        .cfg = ( struct cf_item[] )     /** List of sub-items. **/
236 #define CF_END          { .cls = CC_END }               /** End of the structure. **/
237 /***
238  * Declaration of a configuration item
239  * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
240  *
241  * Each of these describe single <<struct_cf_item,configuration item>>. They are mostly
242  * for internal use, do not use them directly unless you really know what you are doing.
243  ***/
244
245 /**
246  * Static array of items.
247  * Expects you to allocate the memory and provide pointer to it.
248  **/
249 #define CF_STATIC(n,p,T,t,c)    { .cls = CC_STATIC, .type = CT_##T, .name = n, .number = c, .ptr = CHECK_PTR_TYPE(p,t*) }
250 /**
251  * Dynamic array of items.
252  * Expects you to provide pointer to your pointer to data and it will allocate new memory for it
253  * and set your pointer to it.
254  **/
255 #define CF_DYNAMIC(n,p,T,t,c)   { .cls = CC_DYNAMIC, .type = CT_##T, .name = n, .number = c, .ptr = CHECK_PTR_TYPE(p,t**) }
256 #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. **/
257 #define CF_SECTION(n,p,s)       { .cls = CC_SECTION, .name = n, .number = 1, .ptr = p, .u.sec = s }                                             /** A sub-section. **/
258 #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. **/
259 #define CF_BITMAP_INT(n,p)      { .cls = CC_BITMAP, .type = CT_INT, .name = n, .number = 1, .ptr = CHECK_PTR_TYPE(p,u32*) }                     /** A bitmap. **/
260 #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. **/
261 /***
262  * Basic configuration items
263  * ^^^^^^^^^^^^^^^^^^^^^^^^^
264  *
265  * They describe basic data types used in the configuration. This should be enough for
266  * most real-life purposes.
267  *
268  * The parameters are as follows:
269  *
270  * * @n -- name of the item.
271  * * @p -- pointer to the variable where it shall be stored.
272  * * @c -- count.
273  **/
274 #define CF_INT(n,p)             CF_STATIC(n,p,INT,int,1)                /** Single `int` value. **/
275 #define CF_INT_ARY(n,p,c)       CF_STATIC(n,p,INT,int,c)                /** Static array of integers. **/
276 #define CF_INT_DYN(n,p,c)       CF_DYNAMIC(n,p,INT,int,c)               /** Dynamic array of integers. **/
277 #define CF_UNS(n,p)             CF_STATIC(n,p,INT,uns,1)                /** Single `uns` (`unsigned`) value. **/
278 #define CF_UNS_ARY(n,p,c)       CF_STATIC(n,p,INT,uns,c)                /** Static array of unsigned integers. **/
279 #define CF_UNS_DYN(n,p,c)       CF_DYNAMIC(n,p,INT,uns,c)               /** Dynamic array of unsigned integers. **/
280 #define CF_U64(n,p)             CF_STATIC(n,p,U64,u64,1)                /** Single unsigned 64bit integer (`u64`). **/
281 #define CF_U64_ARY(n,p,c)       CF_STATIC(n,p,U64,u64,c)                /** Static array of u64s. **/
282 #define CF_U64_DYN(n,p,c)       CF_DYNAMIC(n,p,U64,u64,c)               /** Dynamic array of u64s. **/
283 #define CF_DOUBLE(n,p)          CF_STATIC(n,p,DOUBLE,double,1)          /** Single instance of `double`. **/
284 #define CF_DOUBLE_ARY(n,p,c)    CF_STATIC(n,p,DOUBLE,double,c)          /** Static array of doubles. **/
285 #define CF_DOUBLE_DYN(n,p,c)    CF_DYNAMIC(n,p,DOUBLE,double,c)         /** Dynamic array of doubles. **/
286 #define CF_IP(n,p)              CF_STATIC(n,p,IP,u32,1)                 /** Single IPv4 address. **/
287 #define CF_IP_ARY(n,p,c)        CF_STATIC(n,p,IP,u32,c)                 /** Static array of IP addresses. **/.
288 #define CF_IP_DYN(n,p,c)        CF_DYNAMIC(n,p,IP,u32,c)                /** Dynamic array of IP addresses. **/
289 /**
290  * A string.
291  * You provide a pointer to a `char *` variable and it will fill it with
292  * dynamically allocated string. For example:
293  *
294  *   static char *string = "Default string";
295  *
296  *   static struct cf_section section = {
297  *     CF_ITEMS {
298  *       CF_STRING("string", &string),
299  *       CF_END
300  *     }
301  *   };
302  **/
303 #define CF_STRING(n,p)          CF_STATIC(n,p,STRING,char*,1)
304 #define CF_STRING_ARY(n,p,c)    CF_STATIC(n,p,STRING,char*,c)           /** Static array of strings. **/
305 #define CF_STRING_DYN(n,p,c)    CF_DYNAMIC(n,p,STRING,char*,c)          /** Dynamic array of strings. **/
306 /**
307  * One string out of a predefined set.
308  * You provide the set as an array of strings terminated by NULL (similar to @argv argument
309  * of main()) as the @t parameter.
310  *
311  * The configured variable (pointer to `int`) is set to index of the string.
312  * So, it works this way:
313  *
314  *   static *strings[] = { "First", "Second", "Third", NULL };
315  *
316  *   static int variable;
317  *
318  *   static struct cf_section section = {
319  *     CF_ITEMS {
320  *       CF_LOOKUP("choice", &variable, strings),
321  *       CF_END
322  *     }
323  *   };
324  *
325  * Now, if the configuration contains `choice "Second"`, `variable` will be set to 1.
326  **/
327 #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 }
328 /**
329  * Static array of strings out of predefined set.
330  **/
331 #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 }
332 /**
333  * Dynamic array of strings out of predefined set.
334  **/
335 #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 }
336 /**
337  * A user-defined type.
338  * See <<custom_parser,creating custom parsers>> section if you want to know more.
339  **/
340 #define CF_USER(n,p,t)          { .cls = CC_STATIC, .type = CT_USER, .name = n, .number = 1, .ptr = p, .u.utype = t }
341 /**
342  * Static array of user-defined types (all of the same type).
343  * See <<custom_parser,creating custom parsers>> section.
344  **/
345 #define CF_USER_ARY(n,p,t,c)    { .cls = CC_STATIC, .type = CT_USER, .name = n, .number = c, .ptr = p, .u.utype = t }
346 /**
347  * Dynamic array of user-defined types.
348  * See <<custom_parser,creating custom parsers>> section.
349  **/
350 #define CF_USER_DYN(n,p,t,c)    { .cls = CC_DYNAMIC, .type = CT_USER, .name = n, .number = c, .ptr = p, .u.utype = t }
351
352 /**
353  * Any number of dynamic array elements
354  **/
355 #define CF_ANY_NUM              -0x7fffffff
356
357 #define DARY_LEN(a) ((uns*)a)[-1]       /** Length of an dynamic array. **/
358 #define DARY_ALLOC(type,len,val...) ((struct { uns l; type a[len]; }) { .l = len, .a = { val } }).a
359   // creates a static instance of a dynamic array
360
361 /***
362  * [[alloc]]
363  * Memory allocation
364  * ~~~~~~~~~~~~~~~~~
365  *
366  * Each configuration context has one or more <<mempool:,memory pools>>, where all
367  * data related to the configuration are stored.
368  *
369  * The following set of functions allocate from these pools. The allocated memory
370  * is valid as long as the current configuration (when the configuration file is
371  * reloaded or rolled back, or the context is deleted, it gets lost).
372  *
373  * Memory allocated from within custom parsers should be allocated from the pools.
374  ***/
375 struct mempool *cf_get_pool(void); /** Return a pointer to the current configuration pool. **/
376 void *cf_malloc(uns size);      /** Returns @size bytes of memory allocated from the current configuration pool. **/
377 void *cf_malloc_zero(uns size); /** Like @cf_malloc(), but zeroes the memory. **/
378 char *cf_strdup(const char *s); /** Copy a string into @cf_malloc()ed memory. **/
379 char *cf_printf(const char *fmt, ...) FORMAT_CHECK(printf,1,2); /** printf() into @cf_malloc()ed memory. **/
380
381 /***
382  * [[journal]]
383  * Undo journal
384  * ~~~~~~~~~~~~
385  *
386  * For error recovery when <<reload,reloading configuration>>.
387  ***/
388 extern uns cf_need_journal;     /** Is the journal needed? If you do not reload configuration, you set this to 0 and gain a little more performance and free memory. **/
389 /**
390  * When a block of memory is about to be changed, put the old value
391  * into journal with this function. You need to call it from a <<hooks,commit hook>>
392  * if you change anything. It is used internally by low-level parsers.
393  * <<custom_parser,Custom parsers>> do not need to call it, it is called
394  * before them.
395  **/
396 void cf_journal_block(void *ptr, uns len);
397 #define CF_JOURNAL_VAR(var) cf_journal_block(&(var), sizeof(var))       // Store single value into journal.
398
399 /***
400  * [[declare]]
401  * Section declaration
402  * ~~~~~~~~~~~~~~~~~~~
403  **/
404
405 /**
406  * Plug another top-level section into the configuration system.
407  * @name is the name in the configuration file,
408  * @sec is pointer to the section description.
409  * If @allow_unknown is set to 0 and a variable not described in @sec
410  * is found in the configuration file, it produces an error.
411  * If you set it to 1, all such variables are ignored.
412  **/
413 void cf_declare_section(const char *name, struct cf_section *sec, uns allow_unknown);
414 /**
415  * If you have a section in a structure and you want to initialize it
416  * (eg. if you want a copy of default values outside the configuration),
417  * you can use this. It initializes it recursively.
418  *
419  * This is used mostly internally. You probably do not need it.
420  **/
421 void cf_init_section(const char *name, struct cf_section *sec, void *ptr, uns do_bzero);
422
423 /***
424  * [[bparser]]
425  * Parsers for basic types
426  * ~~~~~~~~~~~~~~~~~~~~~~~
427  *
428  * Each of them gets a string to parse and pointer to store the value.
429  * It returns either NULL or error message.
430  *
431  * The parsers support units. See <<config:units,their list>>.
432  ***/
433 char *cf_parse_int(const char *str, int *ptr);          /** Parser for integers. **/
434 char *cf_parse_u64(const char *str, u64 *ptr);          /** Parser for 64 unsigned integers. **/
435 char *cf_parse_double(const char *str, double *ptr);    /** Parser for doubles. **/
436 char *cf_parse_ip(const char *p, u32 *varp);            /** Parser for IP addresses. **/
437
438 #endif
439