2 * UCW Library -- Reading of configuration files
4 * (c) 2001--2006 Robert Spalek <robert@ucw.cz>
5 * (c) 2003--2006 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.
12 #include "lib/conf2.h"
13 #include "lib/mempool.h"
14 #include "lib/clists.h"
15 #include "lib/fastbuf.h"
16 #include "lib/chartype.h"
25 #define TRY(f) do { byte *_msg = f; if (_msg) return _msg; } while (0)
27 /* Memory allocation */
29 struct mempool *cf_pool; // current pool for loading new configuration
30 static struct old_pools {
31 struct old_pools *prev;
33 } *pools; // link-list of older cf_pool's
38 return mp_alloc(cf_pool, size);
42 cf_malloc_zero(uns size)
44 return mp_alloc_zero(cf_pool, size);
50 return mp_strdup(cf_pool, s);
54 cf_printf(char *fmt, ...)
58 byte *res = mp_vprintf(cf_pool, fmt, args);
65 uns cf_need_journal; // some programs do not need journal
66 static struct journal_item {
67 struct journal_item *prev;
74 cf_journal_block(void *ptr, uns len)
78 struct journal_item *ji = cf_malloc(sizeof(struct journal_item) + len);
82 memcpy(ji->copy, ptr, len);
88 // swaps the contents of the memory and the journal, and reverses the list
90 struct journal_item *curr, *prev, *next;
91 for (next=NULL, curr=journal; curr; next=curr, curr=prev)
95 for (uns i=0; i<curr->len; i++)
97 byte x = curr->copy[i];
98 curr->copy[i] = curr->ptr[i];
105 static struct journal_item *
106 journal_new_section(uns new_pool)
109 cf_pool = mp_new(1<<14);
110 struct journal_item *oldj = journal;
116 journal_commit_section(uns new_pool, struct journal_item *oldj)
120 struct old_pools *p = cf_malloc(sizeof(struct old_pools));
127 struct journal_item **j = &journal;
135 journal_rollback_section(uns new_pool, struct journal_item *oldj)
137 if (!cf_need_journal)
138 die("Cannot rollback the configuration, because the journal is disabled.");
144 cf_pool = pools ? pools->pool : NULL;
150 #define SEC_FLAG_DYNAMIC 0x80000000 // contains a dynamic attribute
151 #define SEC_FLAG_UNKNOWN 0x40000000 // ignore unknown entriies
152 #define SEC_FLAG_NUMBER 0x3fffffff // number of entries
154 static struct cf_section sections; // root section
156 static struct cf_item *
157 find_subitem(struct cf_section *sec, byte *name)
159 struct cf_item *ci = sec->cfg;
160 for (; ci->cls; ci++)
161 if (!strcasecmp(ci->name, name))
167 inspect_section(struct cf_section *sec)
171 for (ci=sec->cfg; ci->cls; ci++)
172 if (ci->cls == CC_SECTION) {
173 inspect_section(ci->u.sec);
174 sec->flags |= ci->u.sec->flags & SEC_FLAG_DYNAMIC;
175 } else if (ci->cls == CC_LIST) {
176 inspect_section(ci->u.sec);
177 sec->flags |= SEC_FLAG_DYNAMIC;
178 } else if (ci->cls == CC_DYNAMIC || ci->cls == CC_PARSER && ci->number < 0)
179 sec->flags |= SEC_FLAG_DYNAMIC;
180 sec->flags |= ci - sec->cfg; // record the number of entries
184 cf_declare_section(byte *name, struct cf_section *sec, uns allow_unknown)
189 sections.cfg = xmalloc_zero(sections.size * sizeof(struct cf_item));
191 struct cf_item *ci = find_subitem(§ions, name);
193 die("Cannot register section %s twice", name);
194 ci->cls = CC_SECTION;
199 inspect_section(sec);
201 sec->flags |= SEC_FLAG_UNKNOWN;
203 if (ci - sections.cfg >= (int) sections.size)
205 sections.cfg = xrealloc(sections.cfg, 2*sections.size * sizeof(struct cf_item));
206 bzero(sections.cfg + sections.size, sections.size * sizeof(struct cf_item));
212 cf_init_section(byte *name, struct cf_section *sec, void *ptr)
215 bzero(ptr, sec->size);
216 for (uns i=0; sec->cfg[i].cls; i++)
217 if (sec->cfg[i].cls == CC_SECTION)
218 cf_init_section(sec->cfg[i].name, sec->cfg[i].u.sec, ptr + (addr_int_t) sec->cfg[i].ptr);
219 else if (sec->cfg[i].cls == CC_LIST)
220 clist_init(sec->cfg[i].ptr);
221 byte *msg = sec->init(ptr);
223 die("Cannot initialize section %s: %s", name, msg);
229 static uns initialized = 0;
232 sections.flags |= SEC_FLAG_UNKNOWN;
233 for (struct cf_item *ci=sections.cfg; ci->cls; ci++)
234 cf_init_section(ci->name, ci->u.sec, NULL);
237 static struct cf_item *
238 find_item(struct cf_section *curr_sec, byte *name, byte **msg)
241 if (name[0] == '^') // absolute name instead of relative
242 name++, curr_sec = §ions;
243 if (!curr_sec) // don't even search in an unknown section
247 byte *c = strchr(name, '.');
250 struct cf_item *ci = find_subitem(curr_sec, name);
253 if (!(curr_sec->flags & SEC_FLAG_UNKNOWN)) // ignore silently unknown top-level sections and unknown attributes in flagged sections
254 *msg = cf_printf("Unknown item %s", name);
259 if (ci->cls != CC_SECTION)
261 *msg = cf_printf("Item %s is not a section", name);
264 curr_sec = ci->u.sec;
269 /* Safe loading and reloading */
271 static int load_file(byte *file);
272 static int load_string(byte *string);
275 cf_reload(byte *file)
278 struct journal_item *oldj = journal_new_section(1);
279 int err = load_file(file);
282 for (struct old_pools *p=pools; p; p=pools)
287 journal_commit_section(1, NULL);
291 journal_rollback_section(1, oldj);
300 struct journal_item *oldj = journal_new_section(1);
301 int err = load_file(file);
303 journal_commit_section(1, oldj);
305 journal_rollback_section(1, oldj);
312 struct journal_item *oldj = journal_new_section(0);
313 int err = load_string(string);
315 journal_commit_section(0, oldj);
317 journal_rollback_section(0, oldj);
321 /* Parsers for standard types */
324 uns name; // one-letter name of the unit
325 uns num, den; // fraction
328 static const struct unit units[] = {
333 { 'g', 1000000000, 1 },
336 { 'G', 1073741824, 1 },
341 static const struct unit *
342 lookup_unit(byte *value, byte *end, byte **msg)
345 if (end == value || end[1] || *end >= '0' && *end <= '9')
346 *msg = "Invalid number";
348 for (const struct unit *u=units; u->name; u++)
351 *msg = "Invalid unit";
357 static char cf_rngerr[] = "Number out of range";
359 //FIXME: parsers should handle well empty strings, unwanted suffixes etc.
361 cf_parse_int(byte *str, int *ptr)
365 msg = "Missing number";
367 const struct unit *u;
370 uns x = strtoul(str, &end, 0);
373 else if (u = lookup_unit(str, end, &msg)) {
374 u64 y = (u64)x * u->num;
376 msg = "Number is not an integer";
390 cf_parse_u64(byte *str, u64 *ptr)
394 msg = "Missing number";
396 const struct unit *u;
399 u64 x = strtoull(str, &end, 0);
402 else if (u = lookup_unit(str, end, &msg)) {
403 if (x > ~(u64)0 / u->num)
404 msg = "Number out of range";
408 msg = "Number is not an integer";
419 cf_parse_double(byte *str, double *ptr)
423 msg = "Missing number";
425 const struct unit *u;
428 double x = strtoul(str, &end, 0);
431 else if (u = lookup_unit(str, end, &msg))
432 *ptr = x * u->num / u->den;
440 cf_parse_ip(byte *p, u32 *varp)
443 return "Missing IP address";
445 if (*p == '0' && p[1] | 32 == 'X') {
447 x = strtoul(p + 2, NULL, 16);
448 if (errno == ERANGE || x > 0xffffffff)
452 for (uns i = 0; i < 4; i++) {
459 uns y = strtoul(p, &p2, 10);
461 if (errno == ERANGE || y > 255)
468 return "Invalid IP address";
472 cf_parse_string(byte *str, byte **ptr)
474 *ptr = cf_strdup(str);
478 /* Register size of and parser for each basic type */
480 typedef byte *cf_basic_parser(byte *str, void *ptr);
485 { sizeof(int), cf_parse_int },
486 { sizeof(u64), cf_parse_u64 },
487 { sizeof(double), cf_parse_double },
488 { sizeof(u32), cf_parse_ip },
489 { sizeof(byte*), cf_parse_string }
493 cf_parse_ary(uns number, byte **pars, void *ptr, enum cf_type type)
495 for (uns i=0; i<number; i++)
497 byte *msg = ((cf_basic_parser*) parsers[type].parser) (pars[i], ptr + i * parsers[type].size);
499 return cf_printf("Cannot parse item %d: %s", i+1, msg);
506 #define OPERATIONS T(CLOSE) T(SET) T(CLEAR) T(APPEND) T(PREPEND) \
507 T(REMOVE) T(EDIT) T(AFTER) T(BEFORE)
508 /* Closing brace finishes previous block.
509 * Basic attributes (static, dynamic, parsed) can be used with SET.
510 * Dynamic arrays can be used with SET, APPEND, PREPEND.
511 * Sections can be used with SET.
512 * Lists can be used with everything. */
519 static byte *op_names[] = {
524 #define OP_MASK 0xff // only get the operation
525 #define OP_OPEN 0x100 // here we only get an opening brace instead of parameters
526 #define OP_1ST 0x200 // in the 1st phase selectors are recorded into the mask
527 #define OP_2ND 0x400 // in the 2nd phase real data are entered
530 interpret_set_dynamic(struct cf_item *item, int number, byte **pars, void **ptr)
532 enum cf_type type = item->u.type;
533 cf_journal_block(ptr, sizeof(void*));
534 // boundary checks done by the caller
535 *ptr = cf_malloc((number+1) * parsers[type].size) + parsers[type].size;
536 * (uns*) (*ptr - parsers[type].size) = number;
537 return cf_parse_ary(number, pars, *ptr, type);
541 interpret_add_dynamic(struct cf_item *item, int number, byte **pars, int *processed, void **ptr, enum operation op)
543 enum cf_type type = item->u.type;
545 int old_nr = * (int*) (old_p - parsers[type].size);
546 int taken = MIN(number, item->number-old_nr);
548 // stretch the dynamic array
549 void *new_p = cf_malloc((old_nr + taken + 1) * parsers[type].size) + parsers[type].size;
550 * (uns*) (new_p - parsers[type].size) = old_nr + taken;
551 cf_journal_block(ptr, sizeof(void*));
553 if (op == OP_APPEND) {
554 memcpy(new_p, old_p, old_nr * parsers[type].size);
555 return cf_parse_ary(taken, pars, new_p + old_nr * parsers[type].size, type);
556 } else if (op == OP_PREPEND) {
557 memcpy(new_p + taken * parsers[type].size, old_p, old_nr * parsers[type].size);
558 return cf_parse_ary(taken, pars, new_p, type);
560 return cf_printf("Dynamic arrays do not support operation %s", op_names[op]);
563 static byte *interpret_set_item(struct cf_item *item, int number, byte **pars, int *processed, void *ptr, uns allow_dynamic);
566 interpret_section(struct cf_section *sec, int number, byte **pars, int *processed, void *ptr, uns allow_dynamic)
569 for (struct cf_item *ci=sec->cfg; ci->cls; ci++)
572 byte *msg = interpret_set_item(ci, number, pars, &taken, ptr + (addr_int_t) ci->ptr, allow_dynamic && !ci[1].cls);
574 return cf_printf("Item %s: %s", ci->name, msg);
578 if (!number) // stop parsing, because many parsers would otherwise complain that number==0
585 add_to_list(void *list, struct cnode *node, enum operation op)
587 cf_journal_block(list, sizeof(struct clist)); //FIXME: we should journal the nodes of the list instead
592 clist_add_tail(list, node);
595 clist_add_head(list, node);
600 case OP_EDIT: // edition has been done in-place
602 case OP_AFTER: // here the pointer list is actually a pointer to another node
603 clist_insert_after(node, list);
606 clist_insert_before(node, list);
614 interpret_add_list(struct cf_item *item, int number, byte **pars, int *processed, void *ptr, enum operation op)
617 return "Missing value";
618 ASSERT(op < OP_REMOVE);
619 struct cf_section *sec = item->u.sec;
623 void *node = cf_malloc(sec->size);
624 cf_init_section(item->name, sec, node);
625 add_to_list(ptr, node, op);
627 /* If the node contains any dynamic attribute at the end, we suppress
628 * auto-repetition here and pass the flag inside instead. */
629 TRY( interpret_section(sec, number, pars, &taken, node, sec->flags & SEC_FLAG_DYNAMIC) );
633 if (sec->flags & SEC_FLAG_DYNAMIC)
640 interpret_set_item(struct cf_item *item, int number, byte **pars, int *processed, void *ptr, uns allow_dynamic)
647 return "Missing value";
648 taken = MIN(number, item->number);
650 cf_journal_block(ptr, taken * parsers[item->u.type].size);
651 return cf_parse_ary(taken, pars, ptr, item->u.type);
654 return "Dynamic array cannot be used here";
655 taken = MIN(number, item->number);
657 return interpret_set_dynamic(item, taken, pars, ptr);
659 if (item->number < 0 && !allow_dynamic)
660 return "Parsers with variable number of parameters cannot be used here";
661 if (item->number > 0 && number < item->number)
662 return "Not enough parameters available for the parser";
663 taken = MIN(number, ABS(item->number));
665 for (int i=0; i<taken; i++)
666 pars[i] = cf_strdup(pars[i]);
667 return item->u.par(taken, pars, ptr);
669 return interpret_section(item->u.sec, number, pars, processed, ptr, allow_dynamic);
672 return "Lists cannot be used here";
673 return interpret_add_list(item, number, pars, ptr, processed, OP_SET);
680 interpret_clear(struct cf_item *item, void *ptr)
682 if (item->cls == CC_LIST) {
683 cf_journal_block(ptr, sizeof(struct clist));
685 } else if (item->cls == CC_DYNAMIC) {
686 cf_journal_block(ptr, sizeof(void *));
687 * (void**) ptr = NULL;
689 return "The item is not a list or a dynamic array";
694 cmp_items(void *i1, void *i2, struct cf_item *item)
696 ASSERT(item->cls == CC_STATIC);
697 i1 += (addr_int_t) item->ptr;
698 i2 += (addr_int_t) item->ptr;
699 if (item->u.type == CT_STRING)
700 return strcmp(* (byte**) i1, * (byte**) i2);
701 else // all numeric types
702 return memcmp(i1, i2, parsers[item->u.type].size);
706 find_list_node(struct clist *list, void *query, struct cf_section *sec, u32 mask)
712 for (uns i=0; i<32; i++)
714 if (cmp_items(n, query, sec->cfg+i))
726 record_selector(struct cf_item *item, struct cf_section *sec, u32 *mask)
728 uns nr = sec->flags & SEC_FLAG_NUMBER;
729 if (item >= sec->cfg && item < sec->cfg + nr) // setting an attribute relative to this section
731 uns i = item - sec->cfg;
733 return "Cannot select list nodes by this attribute";
734 if (sec->cfg[i].cls != CC_STATIC)
735 return "Selection can only be done based on basic attributes";
741 #define MAX_STACK_SIZE 100
742 static struct item_stack {
743 struct cf_section *sec; // nested section
744 void *base_ptr; // because original pointers are often relative
745 enum operation op; // it is performed when a closing brace is encountered
746 void *list; // list the operations should be done on
747 u32 mask; // bit array of selectors searching in a list
748 struct cf_item *item; // cf_item of the list
749 } stack[MAX_STACK_SIZE];
753 opening_brace(struct cf_item *item, void *ptr, enum operation op)
755 if (level >= MAX_STACK_SIZE-1)
756 return "Too many nested sections";
757 stack[++level] = (struct item_stack) {
765 if (!item) // unknown is ignored; we just need to trace recursion
767 stack[level].sec = item->u.sec;
768 if (item->cls == CC_SECTION)
770 stack[level].base_ptr = ptr;
771 stack[level].op = OP_EDIT | OP_2ND; // this list operation does nothing
773 else if (item->cls == CC_LIST)
775 stack[level].base_ptr = cf_malloc(item->u.sec->size);
776 cf_init_section(item->name, item->u.sec, stack[level].base_ptr);
777 stack[level].list = ptr;
778 stack[level].item = item;
779 stack[level].op |= op < OP_REMOVE ? OP_2ND : OP_1ST;
782 return "Opening brace can only be used on sections and lists";
787 closing_brace(struct item_stack *st, int number, byte **pars)
789 if (st->op == OP_CLOSE) // top-level
790 return "Unmatched } parenthese";
791 if (!st->sec) { // dummy run on unknown section
795 enum operation op = st->op & OP_MASK;
798 st->list = find_list_node(st->list, st->base_ptr, st->sec, st->mask);
800 return "Cannot find a node matching the query";
804 st->base_ptr = st->list;
805 else if (op == OP_AFTER || op == OP_BEFORE)
806 cf_init_section(st->item->name, st->sec, st->base_ptr);
809 if (st->op & OP_OPEN) { // stay at the same recursion level
810 st->op = (st->op | OP_2ND) & ~OP_1ST;
813 int taken; // parse parameters on 1 line immediately
814 TRY( interpret_section(st->sec, number, pars, &taken, st->base_ptr, 1) );
817 // and fall-thru to the 2nd phase
820 add_to_list(st->list, st->base_ptr, op);
823 return "No parameters expected after the }";
824 else if (st->op & OP_OPEN)
825 return "No { is expected";
831 interpret_line(byte *name, enum operation op, int number, byte **pars)
835 return closing_brace(stack+level, number, pars);
836 struct cf_item *item = find_item(stack[level].sec, name, &msg);
839 if (stack[level].op & OP_1ST)
840 TRY( record_selector(item, stack[level].sec, &stack[level].mask) );
841 void *ptr = stack[level].base_ptr + (addr_int_t) item->ptr;
842 if (op & OP_OPEN) // the operation will be performed after the closing brace
843 return opening_brace(item, ptr, op);
844 if (!item) // ignored item in an unknown section
848 int taken; // process as many parameters as possible
850 taken = 0, msg = interpret_clear(item, ptr);
851 else if (op == OP_SET)
852 msg = interpret_set_item(item, number, pars, &taken, ptr, 1);
853 else if (item->cls == CC_DYNAMIC)
854 msg = interpret_add_dynamic(item, number, pars, &taken, ptr, op);
855 else if (item->cls == CC_LIST)
856 msg = interpret_add_list(item, number, pars, &taken, ptr, op);
858 return cf_printf("Operation %s not supported on attribute class %d", op_names[op], item->cls);
862 return cf_printf("Too many parameters: %d>%d", number, taken);
872 stack[0] = (struct item_stack) {
886 log(L_ERROR, "Unterminated block");
892 /* Text file parser */
894 static struct fastbuf *parse_fb;
897 #define MAX_LINE 4096
898 static byte line_buf[MAX_LINE];
899 static byte *line = line_buf;
901 #include "lib/bbuf.h"
902 static bb_t copy_buf;
905 #define GBUF_TYPE uns
906 #define GBUF_PREFIX(x) split_##x
907 #include "lib/gbuf.h"
908 static split_t word_buf;
910 static uns ends_by_brace; // the line is ended by "{"
915 if (!bgets(parse_fb, line_buf, MAX_LINE))
919 while (Cblank(*line))
925 append(byte *start, byte *end)
927 uns len = end - start;
928 bb_grow(©_buf, copied + len + 1);
929 memcpy(copy_buf.ptr + copied, start, len);
931 copy_buf.ptr[copied-1] = 0;
934 #define CONTROL_CHAR(x) (x == '{' || x == '}' || x == ';')
935 // these characters separate words like blanks
938 get_word(uns stop_at_equal)
940 // promised that *line is non-null and non-blank
945 while (*line && *line != '\'')
950 copy_buf.ptr[copied-1] = '\n';
952 return "Unterminated apostrophe word at the end";
955 } else if (*line == '"') {
961 if (*line == '"' && !escape)
963 else if (*line == '\\')
973 copy_buf.ptr[copied-1] = '\n';
974 else // merge two lines
977 return "Unterminated quoted word at the end";
982 while (*line && !Cblank(*line) && !CONTROL_CHAR(*line)
983 && (*line != '=' || !stop_at_equal))
985 if (*line == '=') { // nice for setting from a command-line
987 return "Assignment without a variable";
990 if (CONTROL_CHAR(*line)) // already the first char is control
994 while (Cblank(*line))
1005 while (!*line || *line == '#')
1009 while (*line == ';' // empty trash at the beginning
1010 || (*line == '\\' && !line[1])) {
1014 if (*line == '{') // only one opening brace
1015 return "Unexpected opening brace";
1017 /* We have got a non-null, non-blank, non-;, non-merge, and non-{ character. */
1020 split_grow(&word_buf, words+1);
1021 word_buf.ptr[words++] = copied;
1022 TRY( get_word(!words) );
1025 else if (*line == '}' || *line == ';') // end of line now and preserve the char
1027 else if (*line == '{') { // discard the char and end the line
1032 } else if (*line == '\\' && !line[1]) { // merge two lines
1034 return "Last line ends by a backslash";
1035 if (!*line || *line == '#') {
1036 log(L_WARN, "The line following the backslash is empty");
1038 } else if (*line == '{')
1045 /* Parsing multiple files */
1048 parse_fastbuf(byte *name_fb, struct fastbuf *fb, uns depth)
1062 byte *name = copy_buf.ptr + word_buf.ptr[0];
1063 byte *pars[words-1];
1064 for (uns i=1; i<words; i++)
1065 pars[i-1] = copy_buf.ptr + word_buf.ptr[i];
1066 if (!strcasecmp(name, "#include"))
1069 msg = "Expecting one filename";
1073 msg = "Too many nested files";
1076 parse_fb = bopen(pars[0], O_RDONLY, 1<<14);
1078 msg = parse_fastbuf(pars[0], parse_fb, depth+1);
1086 byte *c = strchr(name, ':');
1088 op = strcmp(name, "}") ? OP_SET : OP_CLOSE;
1091 switch (Clocase(*c)) {
1092 case 's': op = OP_SET; break;
1093 case 'c': op = OP_CLEAR; break;
1094 case 'a': op = Clocase(c[1]) == 'p' ? OP_APPEND : OP_AFTER; break;
1095 case 'p': op = OP_PREPEND; break;
1096 case 'r': op = OP_REMOVE; break;
1097 case 'e': op = OP_EDIT; break;
1098 case 'b': op = OP_BEFORE; break;
1099 default: op = OP_SET; break;
1101 if (strcasecmp(c, op_names[op])) {
1102 msg = cf_printf("Unknown operation %s", c);
1108 msg = interpret_line(name, op, words-1, pars);
1113 log(L_ERROR, "File %s, line %d: %s", name_fb, line_num, msg);
1114 return "included from here";
1117 #ifndef DEFAULT_CONFIG
1118 #define DEFAULT_CONFIG NULL
1120 byte *cf_def_file = DEFAULT_CONFIG;
1123 load_file(byte *file)
1127 struct fastbuf *fb = bopen(file, O_RDONLY, 1<<14);
1128 byte *msg = parse_fastbuf(file, fb, 0);
1130 return !!msg || done_stack();
1134 load_string(byte *string)
1138 fbbuf_init_read(&fb, string, strlen(string), 0);
1139 byte *msg = parse_fastbuf("memory string", &fb, 0);
1140 return !!msg || done_stack();
1143 /* Command-line parser */
1149 if (cf_load(cf_def_file))
1150 die("Cannot load default config %s", optarg);
1154 cf_get_opt(int argc, char * const argv[], const char *short_opts, const struct option *long_opts, int *long_index)
1156 static int other_options = 0;
1158 int res = getopt_long (argc, argv, short_opts, long_opts, long_index);
1159 if (res == 'S' || res == 'C')
1162 die("The -S and -C options must precede all other arguments");
1166 die("Cannot set %s", optarg);
1168 if (cf_load(optarg))
1169 die("Cannot load %s", optarg);
1172 /* unhandled option or end of options */