2 * BIRD -- Configuration Lexer
4 * (c) 1998--2000 Martin Mares <mj@ucw.cz>
6 * Can be freely distributed and used under the terms of the GNU GPL.
10 * DOC: Lexical analyzer
12 * The lexical analyzer used for configuration files and CLI commands
13 * is generated using the |flex| tool accompanied by a couple of
14 * functions maintaining the hash tables containing information about
15 * symbols and keywords.
17 * Each symbol is represented by a &symbol structure containing name
18 * of the symbol, its lexical scope, symbol class (%SYM_PROTO for a
19 * name of a protocol, %SYM_CONSTANT for a constant etc.) and class
20 * dependent data. When an unknown symbol is encountered, it's
21 * automatically added to the symbol table with class %SYM_VOID.
23 * The keyword tables are generated from the grammar templates
24 * using the |gen_keywords.m4| script.
28 #undef REJECT /* Avoid name clashes */
39 #include <sys/types.h>
44 #include "nest/bird.h"
45 #include "nest/route.h"
46 #include "nest/protocol.h"
47 #include "filter/filter.h"
48 #include "conf/conf.h"
49 #include "conf/cf-parse.tab.h"
50 #include "lib/string.h"
59 #include "conf/keywords.h"
61 /* Could be defined by Bison in cf-parse.tab.h, inteferes with SYM hash */
67 static uint cf_hash(byte *c);
69 #define KW_KEY(n) n->name
70 #define KW_NEXT(n) n->next
71 #define KW_EQ(a,b) !strcmp(a,b)
72 #define KW_FN(k) cf_hash(k)
73 #define KW_ORDER 8 /* Fixed */
75 #define SYM_KEY(n) n->name, n->scope->active
76 #define SYM_NEXT(n) n->next
77 #define SYM_EQ(a,s1,b,s2) !strcmp(a,b) && s1 == s2
78 #define SYM_FN(k,s) cf_hash(k)
79 #define SYM_ORDER 6 /* Initial */
81 #define SYM_REHASH sym_rehash
82 #define SYM_PARAMS /8, *1, 2, 2, 6, 20
85 HASH_DEFINE_REHASH_FN(SYM, struct symbol)
87 HASH(struct keyword) kw_hash;
90 static struct sym_scope *conf_this_scope;
94 int (*cf_read_hook)(byte *buf, unsigned int max, int fd);
95 struct include_file_stack *ifs;
96 static struct include_file_stack *ifs_head;
98 #define MAX_INCLUDE_DEPTH 8
100 #define YY_INPUT(buf,result,max) result = cf_read_hook(buf, max, ifs->fd);
102 #define YY_FATAL_ERROR(msg) cf_error(msg)
104 static void cf_include(char *arg, int alen);
105 static int check_eof(void);
121 include ^{WHITE}*include{WHITE}*\".*\"{WHITE}*;
128 cf_error("Include not allowed in CLI");
130 start = strchr(yytext, '"');
133 end = strchr(start, '"');
137 cf_error("Include with empty argument");
139 cf_include(start, end-start);
143 uint len1 UNUSED, len2;
148 l = strtoul(yytext, &e, 10);
149 if (e && (*e != ':') || (errno == ERANGE) || (l >> 32))
150 cf_error("ASN out of range");
156 cf_lval.i64 = (2ULL << 48) | (((u64) l) << len2);
162 cf_lval.i64 = 0 | (((u64) l) << len2);
166 l = strtoul(e+1, &e, 10);
167 if (e && *e || (errno == ERANGE) || (l >> len2))
168 cf_error("Number out of range");
174 [02]:{DIGIT}+:{DIGIT}+ {
179 if (yytext[0] == '0')
187 cf_lval.i64 = 2ULL << 48;
193 l = strtoul(yytext+2, &e, 10);
194 if (e && (*e != ':') || (errno == ERANGE) || (l >> len1))
195 cf_error("ASN out of range");
196 cf_lval.i64 |= ((u64) l) << len2;
199 l = strtoul(e+1, &e, 10);
200 if (e && *e || (errno == ERANGE) || (l >> len2))
201 cf_error("Number out of range");
207 {DIGIT}+\.{DIGIT}+\.{DIGIT}+\.{DIGIT}+:{DIGIT}+ {
212 cf_lval.i64 = 1ULL << 48;
214 e = strchr(yytext, ':');
216 if (!ip4_pton(yytext, &ip4))
217 cf_error("Invalid IPv4 address %s in Route Distinguisher", yytext);
218 cf_lval.i64 |= ((u64) ip4_to_u32(ip4)) << 16;
221 l = strtoul(e, &e, 10);
222 if (e && *e || (errno == ERANGE) || (l >> 16))
223 cf_error("Number out of range");
229 {DIGIT}+\.{DIGIT}+\.{DIGIT}+\.{DIGIT}+ {
230 if (!ip4_pton(yytext, &cf_lval.ip4))
231 cf_error("Invalid IPv4 address %s", yytext);
235 ({XIGIT}*::|({XIGIT}*:){3,})({XIGIT}*|{DIGIT}+\.{DIGIT}+\.{DIGIT}+\.{DIGIT}+) {
236 if (!ip6_pton(yytext, &cf_lval.ip6))
237 cf_error("Invalid IPv6 address %s", yytext);
245 l = strtoul(yytext+2, &e, 16);
246 if (e && *e || errno == ERANGE || (unsigned long int)(unsigned int) l != l)
247 cf_error("Number out of range");
256 l = strtoul(yytext, &e, 10);
257 if (e && *e || errno == ERANGE || (unsigned long int)(unsigned int) l != l)
258 cf_error("Number out of range");
264 /* Hack to distinguish if..else from else: in case */
268 ({ALPHA}{ALNUM}*|[']({ALNUM}|[-]|[\.]|[:])*[']) {
269 if(*yytext == '\'') {
270 yytext[yyleng-1] = 0;
274 struct keyword *k = HASH_FIND(kw_hash, KW, yytext);
281 cf_lval.i = -k->value;
286 cf_lval.s = cf_get_symbol(yytext);
299 [={}:;,.()+*/%<>~\[\]?!\|-] {
304 yytext[yyleng-1] = 0;
305 cf_lval.t = cfg_strdup(yytext+1);
306 yytext[yyleng-1] = '"';
310 ["][^"\n]*\n cf_error("Unterminated string");
312 <INITIAL,COMMENT><<EOF>> { if (check_eof()) return END; }
322 . cf_error("Unknown character");
331 <CCOMM>\*\/ BEGIN(INITIAL);
332 <CCOMM>\n ifs->lino++;
333 <CCOMM>\/\* cf_error("Comment nesting not supported");
334 <CCOMM><<EOF>> cf_error("Unterminated comment");
355 h = h + (h >> 2) + (h >> 5) + ((uint) *c++ << 24);
361 * IFS stack - it contains structures needed for recursive processing
362 * of include in config files. On the top of the stack is a structure
363 * for currently processed file. Other structures are either for
364 * active files interrupted because of include directive (these have
365 * fd and flex buffer) or for inactive files scheduled to be processed
366 * later (when parent requested including of several files by wildcard
367 * match - these do not have fd and flex buffer yet).
369 * FIXME: Most of these ifs and include functions are really sysdep/unix.
372 static struct include_file_stack *
373 push_ifs(struct include_file_stack *old)
375 struct include_file_stack *ret;
376 ret = cfg_allocz(sizeof(struct include_file_stack));
382 static struct include_file_stack *
383 pop_ifs(struct include_file_stack *old)
385 yy_delete_buffer(old->buffer);
391 enter_ifs(struct include_file_stack *new)
395 new->fd = open(new->file_name, O_RDONLY);
399 cf_error("Unable to open included file %s: %m", new->file_name);
402 new->buffer = yy_create_buffer(NULL, YY_BUF_SIZE);
405 yy_switch_to_buffer(new->buffer);
409 * cf_lex_unwind - unwind lexer state during error
411 * cf_lex_unwind() frees the internal state on IFS stack when the lexical
412 * analyzer is terminated by cf_error().
417 struct include_file_stack *n;
419 for (n = ifs; n != ifs_head; n = n->prev)
421 /* Memory is freed automatically */
423 yy_delete_buffer(n->buffer);
432 cf_include(char *arg, int alen)
434 struct include_file_stack *base_ifs = ifs;
435 int new_depth, rv, i;
439 new_depth = ifs->depth + 1;
440 if (new_depth > MAX_INCLUDE_DEPTH)
441 cf_error("Max include depth reached");
443 /* expand arg to properly handle relative filenames */
446 int dlen = strlen(ifs->file_name);
447 char *dir = alloca(dlen + 1);
448 patt = alloca(dlen + alen + 2);
449 memcpy(dir, ifs->file_name, dlen + 1);
450 sprintf(patt, "%s/%s", dirname(dir), arg);
455 /* Skip globbing if there are no wildcards, mainly to get proper
456 response when the included config file is missing */
457 if (!strpbrk(arg, "?*["))
460 ifs->file_name = cfg_strdup(patt);
461 ifs->depth = new_depth;
467 /* Expand the pattern */
468 rv = glob(patt, GLOB_ERR | GLOB_NOESCAPE, NULL, &g);
469 if (rv == GLOB_ABORTED)
470 cf_error("Unable to match pattern %s: %m", patt);
471 if ((rv != 0) || (g.gl_pathc <= 0))
475 * Now we put all found files to ifs stack in reverse order, they
476 * will be activated and processed in order as ifs stack is popped
477 * by pop_ifs() and enter_ifs() in check_eof().
479 for(i = g.gl_pathc - 1; i >= 0; i--)
481 char *fname = g.gl_pathv[i];
484 if (stat(fname, &fs) < 0)
487 cf_error("Unable to stat included file %s: %m", fname);
490 if (fs.st_mode & S_IFDIR)
493 /* Prepare new stack item */
495 ifs->file_name = cfg_strdup(fname);
496 ifs->depth = new_depth;
509 /* EOF in main config file */
510 ifs->lino = 1; /* Why this? */
519 static struct symbol *
520 cf_new_symbol(byte *c)
526 cf_error("Symbol too long");
528 s = cfg_alloc(sizeof(struct symbol) + l);
529 s->scope = conf_this_scope;
535 if (!new_config->sym_hash.data)
536 HASH_INIT(new_config->sym_hash, new_config->pool, SYM_ORDER);
538 HASH_INSERT2(new_config->sym_hash, SYM, new_config->pool, s);
544 * cf_find_symbol - find a symbol by name
545 * @cfg: specificed config
548 * This functions searches the symbol table in the config @cfg for a symbol of
549 * given name. First it examines the current scope, then the second recent one
550 * and so on until it either finds the symbol and returns a pointer to its
551 * &symbol structure or reaches the end of the scope chain and returns %NULL to
555 cf_find_symbol(struct config *cfg, byte *c)
559 if (cfg->sym_hash.data &&
560 (s = HASH_FIND(cfg->sym_hash, SYM, c, 1)))
564 cfg->fallback->sym_hash.data &&
565 (s = HASH_FIND(cfg->fallback->sym_hash, SYM, c, 1)))
572 * cf_get_symbol - get a symbol by name
575 * This functions searches the symbol table of the currently parsed config
576 * (@new_config) for a symbol of given name. It returns either the already
577 * existing symbol or a newly allocated undefined (%SYM_VOID) symbol if no
578 * existing symbol is found.
581 cf_get_symbol(byte *c)
583 return cf_find_symbol(new_config, c) ?: cf_new_symbol(c);
587 cf_default_name(char *template, int *counter)
589 char buf[SYM_MAX_LEN];
591 char *perc = strchr(template, '%');
595 bsprintf(buf, template, ++(*counter));
596 s = cf_get_symbol(buf);
597 if (s->class == SYM_VOID)
602 cf_error("Unable to generate default name");
606 * cf_define_symbol - define meaning of a symbol
607 * @sym: symbol to be defined
608 * @type: symbol class to assign
609 * @def: class dependent data
611 * Defines new meaning of a symbol. If the symbol is an undefined
612 * one (%SYM_VOID), it's just re-defined to the new type. If it's defined
613 * in different scope, a new symbol in current scope is created and the
614 * meaning is assigned to it. If it's already defined in the current scope,
615 * an error is reported via cf_error().
617 * Result: Pointer to the newly defined symbol. If we are in the top-level
618 * scope, it's the same @sym as passed to the function.
621 cf_define_symbol(struct symbol *sym, int type, void *def)
625 if (sym->scope == conf_this_scope)
626 cf_error("Symbol already defined");
627 sym = cf_new_symbol(sym->name);
637 HASH_INIT(kw_hash, &root_pool, KW_ORDER);
640 for (k=keyword_list; k->name; k++)
641 HASH_INSERT(kw_hash, KW, k);
645 * cf_lex_init - initialize the lexer
646 * @is_cli: true if we're going to parse CLI command, false for configuration
647 * @c: configuration structure
649 * cf_lex_init() initializes the lexical analyzer and prepares it for
650 * parsing of a new input.
653 cf_lex_init(int is_cli, struct config *c)
658 ifs_head = ifs = push_ifs(NULL);
661 ifs->file_name = c->file_name;
662 ifs->fd = c->file_fd;
667 ifs->buffer = YY_CURRENT_BUFFER;
674 conf_this_scope = cfg_allocz(sizeof(struct sym_scope));
675 conf_this_scope->active = 1;
679 * cf_push_scope - enter new scope
680 * @sym: symbol representing scope name
682 * If we want to enter a new scope to process declarations inside
683 * a nested block, we can just call cf_push_scope() to push a new
684 * scope onto the scope stack which will cause all new symbols to be
685 * defined in this scope and all existing symbols to be sought for
686 * in all scopes stored on the stack.
689 cf_push_scope(struct symbol *sym)
691 struct sym_scope *s = cfg_alloc(sizeof(struct sym_scope));
693 s->next = conf_this_scope;
700 * cf_pop_scope - leave a scope
702 * cf_pop_scope() pops the topmost scope from the scope stack,
703 * leaving all its symbols in the symbol table, but making them
704 * invisible to the rest of the config.
709 conf_this_scope->active = 0;
710 conf_this_scope = conf_this_scope->next;
711 ASSERT(conf_this_scope);
715 * cf_symbol_class_name - get name of a symbol class
718 * This function returns a string representing the class
719 * of the given symbol.
722 cf_symbol_class_name(struct symbol *sym)
724 if (cf_symbol_is_constant(sym))
734 return "protocol template";
740 return "routing table";
742 return "unknown type";
750 * Both the configuration and CLI commands are analyzed using a syntax
751 * driven parser generated by the |bison| tool from a grammar which
752 * is constructed from information gathered from grammar snippets by
753 * the |gen_parser.m4| script.
755 * Grammar snippets are files (usually with extension |.Y|) contributed
756 * by various BIRD modules in order to provide information about syntax of their
757 * configuration and their CLI commands. Each snipped consists of several
758 * sections, each of them starting with a special keyword: |CF_HDR| for
759 * a list of |#include| directives needed by the C code, |CF_DEFINES|
760 * for a list of C declarations, |CF_DECLS| for |bison| declarations
761 * including keyword definitions specified as |CF_KEYWORDS|, |CF_GRAMMAR|
762 * for the grammar rules, |CF_CODE| for auxiliary C code and finally
763 * |CF_END| at the end of the snippet.
765 * To create references between the snippets, it's possible to define
766 * multi-part rules by utilizing the |CF_ADDTO| macro which adds a new
767 * alternative to a multi-part rule.
769 * CLI commands are defined using a |CF_CLI| macro. Its parameters are:
770 * the list of keywords determining the command, the list of parameters,
771 * help text for the parameters and help text for the command.
773 * Values of |enum| filter types can be defined using |CF_ENUM| with
774 * the following parameters: name of filter type, prefix common for all
775 * literals of this type and names of all the possible values.