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"
58 #include "conf/keywords.h"
60 #define KW_HASH_SIZE 64
61 static struct keyword *kw_hash[KW_HASH_SIZE];
62 static int kw_hash_inited;
64 #define SYM_HASH_SIZE 128
67 struct sym_scope *next; /* Next on scope stack */
68 struct symbol *name; /* Name of this scope */
69 int active; /* Currently entered */
71 static struct sym_scope *conf_this_scope;
73 static int cf_hash(byte *c);
74 static inline struct symbol * cf_get_sym(byte *c, uint h0);
78 int (*cf_read_hook)(byte *buf, unsigned int max, int fd);
79 struct include_file_stack *ifs;
80 static struct include_file_stack *ifs_head;
82 #define MAX_INCLUDE_DEPTH 8
84 #define YY_INPUT(buf,result,max) result = cf_read_hook(buf, max, ifs->fd);
86 #define YY_FATAL_ERROR(msg) cf_error(msg)
88 static void cf_include(char *arg, int alen);
89 static int check_eof(void);
105 include ^{WHITE}*include{WHITE}*\".*\"{WHITE}*;
112 cf_error("Include not allowed in CLI");
114 start = strchr(yytext, '"');
117 end = strchr(start, '"');
121 cf_error("Include with empty argument");
123 cf_include(start, end-start);
126 [02]:{DIGIT}+:{DIGIT}+ {
127 unsigned long int l, len1, len2;
130 if (yytext[0] == '0')
138 cf_lval.i64 = 2ULL << 48;
144 l = strtoul(yytext+2, &e, 10);
145 if (e && (*e != ':') || (errno == ERANGE) || (l >> len1))
146 cf_error("ASN out of range");
147 cf_lval.i64 |= ((u64) l) << len2;
150 l = strtoul(e+1, &e, 10);
151 if (e && *e || (errno == ERANGE) || (l >> len2))
152 cf_error("Number out of range");
158 1:{DIGIT}+\.{DIGIT}+\.{DIGIT}+\.{DIGIT}+:{DIGIT}+ {
163 cf_lval.i64 = 1ULL << 48;
165 e = strchr(yytext+2, ':');
167 if (!ip4_pton(yytext+2, &ip4))
168 cf_error("Invalid IPv4 address %s in Route Distinguisher", yytext+2);
169 cf_lval.i64 |= ((u64) ip4_to_u32(ip4)) << 16;
172 l = strtoul(e, &e, 10);
173 if (e && *e || (errno == ERANGE) || (l >> 16))
174 cf_error("Number out of range");
180 {DIGIT}+\.{DIGIT}+\.{DIGIT}+\.{DIGIT}+ {
181 if (!ip4_pton(yytext, &cf_lval.ip4))
182 cf_error("Invalid IPv4 address %s", yytext);
186 ({XIGIT}*::|({XIGIT}*:){3,})({XIGIT}*|{DIGIT}+\.{DIGIT}+\.{DIGIT}+\.{DIGIT}+) {
187 if (!ip6_pton(yytext, &cf_lval.ip6))
188 cf_error("Invalid IPv6 address %s", yytext);
196 l = strtoul(yytext+2, &e, 16);
197 if (e && *e || errno == ERANGE || (unsigned long int)(unsigned int) l != l)
198 cf_error("Number out of range");
207 l = strtoul(yytext, &e, 10);
208 if (e && *e || errno == ERANGE || (unsigned long int)(unsigned int) l != l)
209 cf_error("Number out of range");
215 /* Hack to distinguish if..else from else: in case */
219 ({ALPHA}{ALNUM}*|[']({ALNUM}|[-]|[\.]|[:])*[']) {
220 if(*yytext == '\'') {
221 yytext[yyleng-1] = 0;
224 unsigned int h = cf_hash(yytext);
225 struct keyword *k = kw_hash[h & (KW_HASH_SIZE-1)];
228 if (!strcmp(k->name, yytext))
234 cf_lval.i = -k->value;
240 cf_lval.s = cf_get_sym(yytext, h);
253 [={}:;,.()+*/%<>~\[\]?!\|-] {
258 yytext[yyleng-1] = 0;
259 cf_lval.t = cfg_strdup(yytext+1);
260 yytext[yyleng-1] = '"';
264 ["][^"\n]*\n cf_error("Unterminated string");
266 <INITIAL,COMMENT><<EOF>> { if (check_eof()) return END; }
276 . cf_error("Unknown character");
285 <CCOMM>\*\/ BEGIN(INITIAL);
286 <CCOMM>\n ifs->lino++;
287 <CCOMM>\/\* cf_error("Comment nesting not supported");
288 <CCOMM><<EOF>> cf_error("Unterminated comment");
315 * IFS stack - it contains structures needed for recursive processing
316 * of include in config files. On the top of the stack is a structure
317 * for currently processed file. Other structures are either for
318 * active files interrupted because of include directive (these have
319 * fd and flex buffer) or for inactive files scheduled to be processed
320 * later (when parent requested including of several files by wildcard
321 * match - these do not have fd and flex buffer yet).
323 * FIXME: Most of these ifs and include functions are really sysdep/unix.
326 static struct include_file_stack *
327 push_ifs(struct include_file_stack *old)
329 struct include_file_stack *ret;
330 ret = cfg_allocz(sizeof(struct include_file_stack));
336 static struct include_file_stack *
337 pop_ifs(struct include_file_stack *old)
339 yy_delete_buffer(old->buffer);
345 enter_ifs(struct include_file_stack *new)
349 new->fd = open(new->file_name, O_RDONLY);
353 cf_error("Unable to open included file %s: %m", new->file_name);
356 new->buffer = yy_create_buffer(NULL, YY_BUF_SIZE);
359 yy_switch_to_buffer(new->buffer);
363 * cf_lex_unwind - unwind lexer state during error
365 * cf_lex_unwind() frees the internal state on IFS stack when the lexical
366 * analyzer is terminated by cf_error().
371 struct include_file_stack *n;
373 for (n = ifs; n != ifs_head; n = n->prev)
375 /* Memory is freed automatically */
377 yy_delete_buffer(n->buffer);
386 cf_include(char *arg, int alen)
388 struct include_file_stack *base_ifs = ifs;
389 int new_depth, rv, i;
393 new_depth = ifs->depth + 1;
394 if (new_depth > MAX_INCLUDE_DEPTH)
395 cf_error("Max include depth reached");
397 /* expand arg to properly handle relative filenames */
400 int dlen = strlen(ifs->file_name);
401 char *dir = alloca(dlen + 1);
402 patt = alloca(dlen + alen + 2);
403 memcpy(dir, ifs->file_name, dlen + 1);
404 sprintf(patt, "%s/%s", dirname(dir), arg);
409 /* Skip globbing if there are no wildcards, mainly to get proper
410 response when the included config file is missing */
411 if (!strpbrk(arg, "?*["))
414 ifs->file_name = cfg_strdup(patt);
415 ifs->depth = new_depth;
421 /* Expand the pattern */
422 rv = glob(patt, GLOB_ERR | GLOB_NOESCAPE, NULL, &g);
423 if (rv == GLOB_ABORTED)
424 cf_error("Unable to match pattern %s: %m", patt);
425 if ((rv != 0) || (g.gl_pathc <= 0))
429 * Now we put all found files to ifs stack in reverse order, they
430 * will be activated and processed in order as ifs stack is popped
431 * by pop_ifs() and enter_ifs() in check_eof().
433 for(i = g.gl_pathc - 1; i >= 0; i--)
435 char *fname = g.gl_pathv[i];
438 if (stat(fname, &fs) < 0)
441 cf_error("Unable to stat included file %s: %m", fname);
444 if (fs.st_mode & S_IFDIR)
447 /* Prepare new stack item */
449 ifs->file_name = cfg_strdup(fname);
450 ifs->depth = new_depth;
463 /* EOF in main config file */
464 ifs->lino = 1; /* Why this? */
473 static struct symbol *
474 cf_new_sym(byte *c, uint h0)
476 uint h = h0 & (SYM_HASH_SIZE-1);
477 struct symbol *s, **ht;
480 if (!new_config->sym_hash)
481 new_config->sym_hash = cfg_allocz(SYM_HASH_SIZE * sizeof(struct keyword *));
482 ht = new_config->sym_hash;
485 cf_error("Symbol too long");
486 s = cfg_alloc(sizeof(struct symbol) + l);
489 s->scope = conf_this_scope;
497 static struct symbol *
498 cf_find_sym(struct config *cfg, byte *c, uint h0)
500 uint h = h0 & (SYM_HASH_SIZE-1);
501 struct symbol *s, **ht;
503 if (ht = cfg->sym_hash)
505 for(s = ht[h]; s; s=s->next)
506 if (!strcmp(s->name, c) && s->scope->active)
509 if (ht = cfg->sym_fallback)
511 /* We know only top-level scope is active */
512 for(s = ht[h]; s; s=s->next)
513 if (!strcmp(s->name, c) && s->scope->active)
520 static inline struct symbol *
521 cf_get_sym(byte *c, uint h0)
523 return cf_find_sym(new_config, c, h0) ?: cf_new_sym(c, h0);
527 * cf_find_symbol - find a symbol by name
528 * @cfg: specificed config
531 * This functions searches the symbol table in the config @cfg for a symbol of
532 * given name. First it examines the current scope, then the second recent one
533 * and so on until it either finds the symbol and returns a pointer to its
534 * &symbol structure or reaches the end of the scope chain and returns %NULL to
538 cf_find_symbol(struct config *cfg, byte *c)
540 return cf_find_sym(cfg, c, cf_hash(c));
544 * cf_get_symbol - get a symbol by name
547 * This functions searches the symbol table of the currently parsed config
548 * (@new_config) for a symbol of given name. It returns either the already
549 * existing symbol or a newly allocated undefined (%SYM_VOID) symbol if no
550 * existing symbol is found.
553 cf_get_symbol(byte *c)
555 return cf_get_sym(c, cf_hash(c));
559 cf_default_name(char *template, int *counter)
561 char buf[SYM_MAX_LEN];
563 char *perc = strchr(template, '%');
567 bsprintf(buf, template, ++(*counter));
568 s = cf_get_sym(buf, cf_hash(buf));
569 if (s->class == SYM_VOID)
574 cf_error("Unable to generate default name");
578 * cf_define_symbol - define meaning of a symbol
579 * @sym: symbol to be defined
580 * @type: symbol class to assign
581 * @def: class dependent data
583 * Defines new meaning of a symbol. If the symbol is an undefined
584 * one (%SYM_VOID), it's just re-defined to the new type. If it's defined
585 * in different scope, a new symbol in current scope is created and the
586 * meaning is assigned to it. If it's already defined in the current scope,
587 * an error is reported via cf_error().
589 * Result: Pointer to the newly defined symbol. If we are in the top-level
590 * scope, it's the same @sym as passed to the function.
593 cf_define_symbol(struct symbol *sym, int type, void *def)
597 if (sym->scope == conf_this_scope)
598 cf_error("Symbol already defined");
599 sym = cf_new_sym(sym->name, cf_hash(sym->name));
611 for(k=keyword_list; k->name; k++)
613 unsigned h = cf_hash(k->name) & (KW_HASH_SIZE-1);
614 k->next = kw_hash[h];
621 * cf_lex_init - initialize the lexer
622 * @is_cli: true if we're going to parse CLI command, false for configuration
623 * @c: configuration structure
625 * cf_lex_init() initializes the lexical analyzer and prepares it for
626 * parsing of a new input.
629 cf_lex_init(int is_cli, struct config *c)
634 ifs_head = ifs = push_ifs(NULL);
637 ifs->file_name = c->file_name;
638 ifs->fd = c->file_fd;
643 ifs->buffer = YY_CURRENT_BUFFER;
650 conf_this_scope = cfg_allocz(sizeof(struct sym_scope));
651 conf_this_scope->active = 1;
655 * cf_push_scope - enter new scope
656 * @sym: symbol representing scope name
658 * If we want to enter a new scope to process declarations inside
659 * a nested block, we can just call cf_push_scope() to push a new
660 * scope onto the scope stack which will cause all new symbols to be
661 * defined in this scope and all existing symbols to be sought for
662 * in all scopes stored on the stack.
665 cf_push_scope(struct symbol *sym)
667 struct sym_scope *s = cfg_alloc(sizeof(struct sym_scope));
669 s->next = conf_this_scope;
676 * cf_pop_scope - leave a scope
678 * cf_pop_scope() pops the topmost scope from the scope stack,
679 * leaving all its symbols in the symbol table, but making them
680 * invisible to the rest of the config.
685 conf_this_scope->active = 0;
686 conf_this_scope = conf_this_scope->next;
687 ASSERT(conf_this_scope);
691 cf_walk_symbols(struct config *cf, struct symbol *sym, int *pos)
697 if (*pos >= SYM_HASH_SIZE)
699 sym = cf->sym_hash[(*pos)++];
703 if (sym && sym->scope->active)
709 * cf_symbol_class_name - get name of a symbol class
712 * This function returns a string representing the class
713 * of the given symbol.
716 cf_symbol_class_name(struct symbol *sym)
718 if (cf_symbol_is_constant(sym))
728 return "protocol template";
734 return "routing table";
736 return "unknown type";
744 * Both the configuration and CLI commands are analyzed using a syntax
745 * driven parser generated by the |bison| tool from a grammar which
746 * is constructed from information gathered from grammar snippets by
747 * the |gen_parser.m4| script.
749 * Grammar snippets are files (usually with extension |.Y|) contributed
750 * by various BIRD modules in order to provide information about syntax of their
751 * configuration and their CLI commands. Each snipped consists of several
752 * sections, each of them starting with a special keyword: |CF_HDR| for
753 * a list of |#include| directives needed by the C code, |CF_DEFINES|
754 * for a list of C declarations, |CF_DECLS| for |bison| declarations
755 * including keyword definitions specified as |CF_KEYWORDS|, |CF_GRAMMAR|
756 * for the grammar rules, |CF_CODE| for auxiliary C code and finally
757 * |CF_END| at the end of the snippet.
759 * To create references between the snippets, it's possible to define
760 * multi-part rules by utilizing the |CF_ADDTO| macro which adds a new
761 * alternative to a multi-part rule.
763 * CLI commands are defined using a |CF_CLI| macro. Its parameters are:
764 * the list of keywords determining the command, the list of parameters,
765 * help text for the parameters and help text for the command.
767 * Values of |enum| filter types can be defined using |CF_ENUM| with
768 * the following parameters: name of filter type, prefix common for all
769 * literals of this type and names of all the possible values.