2 * Copyright (c) 2001-2003
3 * Fraunhofer Institute for Open Communication Systems (FhG Fokus).
6 * Copyright (c) 2004-2006,2018
10 * Author: Harti Brandt <harti@freebsd.org>
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
21 * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * $Begemot: gensnmptree.c 383 2006-05-30 07:40:49Z brandt_h $
35 * Generate OID table from table description.
39 * file := top | top file
41 * top := tree | typedef | include
43 * tree := head elements ')'
45 * entry := head ':' index STRING elements ')'
47 * leaf := head type STRING ACCESS ')'
49 * column := head type ACCESS ')'
51 * type := BASETYPE | BASETYPE '|' subtype | enum | bits
55 * enum := ENUM '(' value ')'
57 * bits := BITS '(' value ')'
59 * value := optminus INT STRING | optminus INT STRING value
61 * optminus := '-' | EMPTY
63 * head := '(' INT STRING
65 * elements := EMPTY | elements element
67 * element := tree | leaf | column
69 * index := type | index type
71 * typedef := 'typedef' STRING type
73 * include := 'include' filespec
75 * filespec := '"' STRING '"' | '<' STRING '>'
77 #include <sys/types.h>
78 #include <sys/param.h>
90 #include <sys/queue.h>
94 #include "snmpagent.h"
97 * Constant prefix for all OIDs
99 static const asn_subid_t prefix[] = { 1, 3, 6 };
100 #define PREFIX_LEN (sizeof(prefix) / sizeof(prefix[0]))
103 static const char *file_prefix = "";
105 /* if true generate local include paths */
106 static int localincs = 0;
108 /* if true print tokens */
111 static const char usgtxt[] = "\
112 Generate SNMP tables.\n\
113 usage: gensnmptree [-dEeFfhlt] [-I directory] [-i infile] [-p prefix]\n\
117 -E extract the named or all enums and bits only\n\
118 -e extract the named oids or enums\n\
119 -F generate functions for -E into a .c file\n\
120 -f generate functions for -E into the header\n\
121 -h print this info\n\
122 -I directory add directory to include path\n\
123 -i ifile read from the named file instead of stdin\n\
124 -l generate local include directives\n\
125 -p prefix prepend prefix to file and variable names\n\
126 -t generate a .def file\n\
133 /** generate the tree */
139 /** print the parsed tree */
147 * Which functions to create.
153 /** functions for header files */
156 /** functions for C files */
161 * A node in the OID tree
176 TAILQ_HEAD(node_list, node);
180 asn_subid_t id; /* last element of OID */
181 char *name; /* name of node */
182 TAILQ_ENTRY(node) link;
183 u_int lno; /* starting line number */
184 u_int flags; /* allowed operations */
188 struct node_list subs;
192 uint32_t index; /* index for table entry */
193 char *func; /* function for tables */
194 struct node_list subs;
195 char *subtypes[SNMP_INDEXES_MAX];
199 enum snmp_syntax syntax; /* syntax for this leaf */
200 char *func; /* function name */
201 char *subtype; /* subtype */
205 enum snmp_syntax syntax; /* syntax for this column */
206 char *subtype; /* subtype */
213 LIST_ENTRY(func) link;
216 static LIST_HEAD(, func) funcs = LIST_HEAD_INITIALIZER(funcs);
221 TAILQ_ENTRY(enums) link;
226 const char *from_fname;
231 TAILQ_HEAD(, enums) enums;
232 LIST_ENTRY(type) link;
235 static LIST_HEAD(, type) types = LIST_HEAD_INITIALIZER(types);
237 static void report(const char *, ...) __dead2 __printflike(1, 2);
238 static void report_node(const struct node *, const char *, ...)
239 __dead2 __printflike(2, 3);
241 /************************************************************
243 * Allocate memory and panic just in the case...
250 if ((ptr = calloc(1, size)) == NULL)
251 err(1, "allocing %zu bytes", size);
257 savestr(const char *s)
262 return (strcpy(xalloc(strlen(s) + 1), s));
265 /************************************************************
274 LIST_ENTRY(input) link;
276 static LIST_HEAD(, input) inputs = LIST_HEAD_INITIALIZER(inputs);
277 static struct input *input = NULL;
279 #define MAX_PATHS 100
280 static u_int npaths = 2;
281 static u_int stdpaths = 2;
282 static const char *paths[MAX_PATHS + 1] = {
283 "/usr/share/snmp/defs",
284 "/usr/local/share/snmp/defs",
288 static int pbchar = -1;
291 path_new(const char *path)
293 if (npaths >= MAX_PATHS)
294 report("too many -I directives");
295 memmove(&paths[npaths - stdpaths + 1], &paths[npaths - stdpaths],
296 sizeof(path[0]) * stdpaths);
297 paths[npaths - stdpaths] = savestr(path);
302 input_new(FILE *fp, const char *path, const char *fname)
306 ip = xalloc(sizeof(*ip));
309 ip->fname = savestr(fname);
310 ip->path = savestr(path);
311 LIST_INSERT_HEAD(&inputs, ip, link);
325 LIST_REMOVE(input, link);
328 input = LIST_FIRST(&inputs);
332 tryopen(const char *path, const char *fname)
340 fn = xalloc(strlen(path) + strlen(fname) + 2);
341 sprintf(fn, "%s/%s", path, fname);
349 input_fopen(const char *fname, int loc)
355 if (fname[0] == '/') {
356 if ((fp = tryopen(NULL, fname)) != NULL) {
357 input_new(fp, NULL, fname);
368 if ((fp = tryopen(path, fname)) != NULL) {
369 input_new(fp, NULL, fname);
374 for (p = 0; paths[p] != NULL; p++)
375 if ((fp = tryopen(paths[p], fname)) != NULL) {
376 input_new(fp, paths[p], fname);
380 report("cannot open '%s'", fname);
398 if ((c = getc(input->fp)) != EOF)
414 /************************************************************
419 TOK_EOF = 0200, /* end-of-file seen */
420 TOK_NUM, /* number */
421 TOK_STR, /* string */
422 TOK_ACCESS, /* access operator */
423 TOK_TYPE, /* type operator */
424 TOK_ENUM, /* enum token (kind of a type) */
425 TOK_TYPEDEF, /* typedef directive */
426 TOK_DEFTYPE, /* defined type */
427 TOK_INCLUDE, /* include directive */
428 TOK_FILENAME, /* filename ("foo.bar" or <foo.bar>) */
429 TOK_BITS, /* bits token (kind of a type) */
432 static const struct {
437 { "GET", TOK_ACCESS, FL_GET },
438 { "SET", TOK_ACCESS, FL_SET },
439 { "NULL", TOK_TYPE, SNMP_SYNTAX_NULL },
440 { "INTEGER", TOK_TYPE, SNMP_SYNTAX_INTEGER },
441 { "INTEGER32", TOK_TYPE, SNMP_SYNTAX_INTEGER },
442 { "UNSIGNED32", TOK_TYPE, SNMP_SYNTAX_GAUGE },
443 { "OCTETSTRING", TOK_TYPE, SNMP_SYNTAX_OCTETSTRING },
444 { "IPADDRESS", TOK_TYPE, SNMP_SYNTAX_IPADDRESS },
445 { "OID", TOK_TYPE, SNMP_SYNTAX_OID },
446 { "TIMETICKS", TOK_TYPE, SNMP_SYNTAX_TIMETICKS },
447 { "COUNTER", TOK_TYPE, SNMP_SYNTAX_COUNTER },
448 { "GAUGE", TOK_TYPE, SNMP_SYNTAX_GAUGE },
449 { "COUNTER64", TOK_TYPE, SNMP_SYNTAX_COUNTER64 },
450 { "ENUM", TOK_ENUM, SNMP_SYNTAX_INTEGER },
451 { "BITS", TOK_BITS, SNMP_SYNTAX_OCTETSTRING },
452 { "typedef", TOK_TYPEDEF, 0 },
453 { "include", TOK_INCLUDE, 0 },
457 /* arbitrary upper limit on node names and function names */
459 static char str[MAXSTR];
460 static u_long val; /* integer values */
461 static int saved_token = -1;
464 * Report an error and exit.
467 report(const char *fmt, ...)
473 fprintf(stderr, "line %u: ", input->lno);
474 vfprintf(stderr, fmt, ap);
475 fprintf(stderr, "\n");
476 fprintf(stderr, "context: \"");
477 while ((c = tgetc()) != EOF && c != '\n')
478 fprintf(stderr, "%c", c);
479 fprintf(stderr, "\n");
484 report_node(const struct node *np, const char *fmt, ...)
489 fprintf(stderr, "line %u, node %s: ", np->lno, np->name);
490 vfprintf(stderr, fmt, ap);
491 fprintf(stderr, "\n");
497 * Return a fresh copy of the string constituting the current token.
502 return (savestr(str));
506 * Get the next token from input.
509 gettoken_internal(void)
514 if (saved_token != -1) {
522 * Skip any whitespace before the next token
524 while ((c = tgetc()) != EOF) {
533 report("unexpected character %#2x", (u_int)c);
539 while ((c = tgetc()) != EOF) {
545 report("unexpected EOF in comment");
549 * Single character tokens
551 if (strchr("():|-", c) != NULL)
554 if (c == '"' || c == '<') {
564 while ((c = tgetc()) != EOF) {
567 if (n == sizeof(str) - 1) {
569 report("filename too long '%s...'", str);
574 return (TOK_FILENAME);
583 while ((c = tgetc()) != EOF) {
588 if (n == sizeof(str) - 1) {
590 report("number too long '%s...'", str);
595 sscanf(str, "%lu", &val);
600 * So that has to be a string.
602 if (isalpha(c) || c == '_') {
605 while ((c = tgetc()) != EOF) {
606 if (!isalnum(c) && c != '_' && c != '-') {
610 if (n == sizeof(str) - 1) {
612 report("string too long '%s...'", str);
621 for (c = 0; keywords[c].str != NULL; c++)
622 if (strcmp(keywords[c].str, str) == 0) {
623 val = keywords[c].val;
624 return (keywords[c].tok);
627 LIST_FOREACH(t, &types, link) {
628 if (strcmp(t->name, str) == 0) {
630 return (TOK_DEFTYPE);
636 errx(1, "%u: unexpected character '%c'", input->lno, c);
638 errx(1, "%u: unexpected character 0x%02x", input->lno,
644 int tok = gettoken_internal();
650 fprintf(stderr, "EOF ");
654 fprintf(stderr, "NUM(%lu) ", val);
658 fprintf(stderr, "STR(%s) ", str);
662 fprintf(stderr, "ACCESS(%lu) ", val);
666 fprintf(stderr, "TYPE(%lu) ", val);
670 fprintf(stderr, "ENUM ");
674 fprintf(stderr, "BITS ");
678 fprintf(stderr, "TYPEDEF ");
682 fprintf(stderr, "DEFTYPE(%s,%lu) ", str, val);
686 fprintf(stderr, "INCLUDE ");
690 fprintf(stderr, "FILENAME ");
696 fprintf(stderr, "'%c' ", tok);
697 else if (tok == '\n')
698 fprintf(stderr, "\n");
700 fprintf(stderr, "%02x ", tok);
713 pushback(enum tok tok)
716 if (saved_token != -1)
725 make_type(const char *s)
729 t = xalloc(sizeof(*t));
730 t->name = savestr(s);
732 t->syntax = SNMP_SYNTAX_NULL;
733 t->from_fname = savestr(input->fname);
734 t->from_lno = input->lno;
735 TAILQ_INIT(&t->enums);
736 LIST_INSERT_HEAD(&types, t, link);
742 * Parse a type. We've seen the ENUM or type keyword already. Leave next
746 parse_type(enum tok *tok, struct type *t, const char *vname, char **subtype)
755 if (*tok == TOK_ENUM || *tok == TOK_BITS) {
756 if (t == NULL && vname != NULL) {
757 t = make_type(vname);
758 t->is_enum = (*tok == TOK_ENUM);
759 t->is_bits = (*tok == TOK_BITS);
762 if (gettoken() != '(')
763 report("'(' expected after ENUM");
765 if ((*tok = gettoken()) == TOK_EOF)
766 report("unexpected EOF in ENUM");
770 e = xalloc(sizeof(*e));
773 if ((*tok = gettoken()) == TOK_EOF)
774 report("unexpected EOF in ENUM");
775 e->value = -(long)val;
780 report("need value for ENUM/BITS");
781 if (gettoken() != TOK_STR)
782 report("need string in ENUM/BITS");
784 TAILQ_INSERT_TAIL(&t->enums, e, link);
785 if ((*tok = gettoken()) == TOK_EOF)
786 report("unexpected EOF in ENUM/BITS");
787 } while (*tok != ')');
790 } else if (*tok == TOK_DEFTYPE) {
794 if ((*tok = gettoken()) == '|') {
795 if (gettoken() != TOK_STR)
796 report("subtype expected after '|'");
798 *subtype = savetok();
807 * Parse the next node (complete with all subnodes)
816 node = xalloc(sizeof(struct node));
817 node->lno = input->lno;
821 report("'(' expected at begin of node");
822 if (gettoken() != TOK_NUM)
823 report("node id expected after opening '('");
825 report("subid too large '%lu'", val);
826 node->id = (asn_subid_t)val;
827 if (gettoken() != TOK_STR)
828 report("node name expected after '(' ID");
829 node->name = savetok();
831 if ((tok = gettoken()) == TOK_TYPE || tok == TOK_DEFTYPE ||
832 tok == TOK_ENUM || tok == TOK_BITS) {
835 u_int syntax = parse_type(&tok, NULL, node->name, &subtype);
837 if (tok == TOK_STR) {
839 node->type = NODE_LEAF;
840 node->u.leaf.func = savetok();
841 node->u.leaf.syntax = syntax;
842 node->u.leaf.subtype = subtype;
846 node->type = NODE_COLUMN;
847 node->u.column.syntax = syntax;
848 node->u.column.subtype = subtype;
852 if (tok != TOK_ACCESS)
853 report("access keyword or ')' expected");
854 node->flags |= (u_int)val;
858 } else if (tok == ':') {
860 node->type = NODE_ENTRY;
861 TAILQ_INIT(&node->u.entry.subs);
864 node->u.entry.index = 0;
866 while (tok == TOK_TYPE || tok == TOK_DEFTYPE ||
867 tok == TOK_ENUM || tok == TOK_BITS) {
869 u_int syntax = parse_type(&tok, NULL, node->name,
871 if (index_count == SNMP_INDEXES_MAX)
872 report("too many table indexes");
873 node->u.entry.subtypes[index_count++] = subtype;
874 node->u.entry.index |=
875 syntax << (SNMP_INDEX_SHIFT * index_count);
877 node->u.entry.index |= index_count;
878 if (index_count == 0)
879 report("need at least one index");
881 report("function name expected");
883 node->u.entry.func = savetok();
889 TAILQ_INSERT_TAIL(&node->u.entry.subs, sub, link);
895 node->type = NODE_TREE;
896 TAILQ_INIT(&node->u.tree.subs);
900 TAILQ_INSERT_TAIL(&node->u.tree.subs, sub, link);
908 * Parse a top level element. Return the tree if it was a tree, NULL
912 parse_top(enum tok tok)
919 if (tok == TOK_TYPEDEF) {
920 if (gettoken() != TOK_STR)
921 report("type name expected after typedef");
926 t->is_enum = (tok == TOK_ENUM);
927 t->is_bits = (tok == TOK_BITS);
929 t->syntax = parse_type(&tok, t, NULL, NULL);
935 if (tok == TOK_INCLUDE) {
936 if (gettoken() != TOK_FILENAME)
937 report("filename expected in include directive");
939 input_fopen(str, val);
943 report("'(' or 'typedef' expected");
947 * Generate the C-code table part for one node.
950 gen_node(FILE *fp, const struct node *np, struct asn_oid *oid, u_int idx,
957 if (oid->len == ASN_MAXOIDLEN)
958 report_node(np, "OID too long");
959 oid->subs[oid->len++] = np->id;
961 if (np->type == NODE_TREE) {
962 TAILQ_FOREACH(sub, &np->u.tree.subs, link)
963 gen_node(fp, sub, oid, 0, NULL);
967 if (np->type == NODE_ENTRY) {
968 TAILQ_FOREACH(sub, &np->u.entry.subs, link)
969 gen_node(fp, sub, oid, np->u.entry.index,
976 if ((np->flags & (FL_GET|FL_SET)) == 0) {
981 fprintf(fp, " {{ %u, {", oid->len);
982 for (n = 0; n < oid->len; n++)
983 fprintf(fp, " %u,", oid->subs[n]);
984 fprintf(fp, " }}, \"%s\", ", np->name);
986 if (np->type == NODE_COLUMN) {
987 syntax = np->u.column.syntax;
988 fprintf(fp, "SNMP_NODE_COLUMN, ");
990 syntax = np->u.leaf.syntax;
991 fprintf(fp, "SNMP_NODE_LEAF, ");
996 case SNMP_SYNTAX_NULL:
997 fprintf(fp, "SNMP_SYNTAX_NULL, ");
1000 case SNMP_SYNTAX_INTEGER:
1001 fprintf(fp, "SNMP_SYNTAX_INTEGER, ");
1004 case SNMP_SYNTAX_OCTETSTRING:
1005 fprintf(fp, "SNMP_SYNTAX_OCTETSTRING, ");
1008 case SNMP_SYNTAX_IPADDRESS:
1009 fprintf(fp, "SNMP_SYNTAX_IPADDRESS, ");
1012 case SNMP_SYNTAX_OID:
1013 fprintf(fp, "SNMP_SYNTAX_OID, ");
1016 case SNMP_SYNTAX_TIMETICKS:
1017 fprintf(fp, "SNMP_SYNTAX_TIMETICKS, ");
1020 case SNMP_SYNTAX_COUNTER:
1021 fprintf(fp, "SNMP_SYNTAX_COUNTER, ");
1024 case SNMP_SYNTAX_GAUGE:
1025 fprintf(fp, "SNMP_SYNTAX_GAUGE, ");
1028 case SNMP_SYNTAX_COUNTER64:
1029 fprintf(fp, "SNMP_SYNTAX_COUNTER64, ");
1032 case SNMP_SYNTAX_NOSUCHOBJECT:
1033 case SNMP_SYNTAX_NOSUCHINSTANCE:
1034 case SNMP_SYNTAX_ENDOFMIBVIEW:
1038 if (np->type == NODE_COLUMN)
1039 fprintf(fp, "%s, ", func);
1041 fprintf(fp, "%s, ", np->u.leaf.func);
1044 if (np->flags & FL_SET)
1045 fprintf(fp, "|SNMP_NODE_CANSET");
1046 fprintf(fp, ", %#x, NULL, NULL },\n", idx);
1052 * Generate the header file with the function declarations.
1055 gen_header(FILE *fp, const struct node *np, u_int oidlen, const char *func)
1062 if (np->type == NODE_TREE) {
1063 TAILQ_FOREACH(sub, &np->u.tree.subs, link)
1064 gen_header(fp, sub, oidlen, NULL);
1067 if (np->type == NODE_ENTRY) {
1068 TAILQ_FOREACH(sub, &np->u.entry.subs, link)
1069 gen_header(fp, sub, oidlen, np->u.entry.func);
1073 if((np->flags & (FL_GET|FL_SET)) == 0)
1076 if (np->type == NODE_COLUMN) {
1078 errx(1, "column without function (%s) - probably "
1079 "outside of a table", np->name);
1080 sprintf(f, "%s", func);
1082 sprintf(f, "%s", np->u.leaf.func);
1084 LIST_FOREACH(ptr, &funcs, link)
1085 if (strcmp(ptr->name, f) == 0)
1089 ptr = xalloc(sizeof(*ptr));
1090 ptr->name = savestr(f);
1091 LIST_INSERT_HEAD(&funcs, ptr, link);
1093 fprintf(fp, "int %s(struct snmp_context *, "
1094 "struct snmp_value *, u_int, u_int, "
1095 "enum snmp_op);\n", f);
1098 fprintf(fp, "# define LEAF_%s %u\n", np->name, np->id);
1102 * Generate the OID table.
1105 gen_table(FILE *fp, const struct node *node)
1109 fprintf(fp, "#include <sys/types.h>\n");
1110 fprintf(fp, "#include <stdio.h>\n");
1111 #ifdef HAVE_STDINT_H
1112 fprintf(fp, "#include <stdint.h>\n");
1115 fprintf(fp, "#include \"asn1.h\"\n");
1116 fprintf(fp, "#include \"snmp.h\"\n");
1117 fprintf(fp, "#include \"snmpagent.h\"\n");
1119 fprintf(fp, "#include <bsnmp/asn1.h>\n");
1120 fprintf(fp, "#include <bsnmp/snmp.h>\n");
1121 fprintf(fp, "#include <bsnmp/snmpagent.h>\n");
1123 fprintf(fp, "#include \"%stree.h\"\n", file_prefix);
1126 fprintf(fp, "const struct snmp_node %sctree[] = {\n", file_prefix);
1128 oid.len = PREFIX_LEN;
1129 memcpy(oid.subs, prefix, sizeof(prefix));
1130 gen_node(fp, node, &oid, 0, NULL);
1132 fprintf(fp, "};\n\n");
1136 print_syntax(u_int syntax)
1140 for (i = 0; keywords[i].str != NULL; i++)
1141 if (keywords[i].tok == TOK_TYPE &&
1142 keywords[i].val == syntax) {
1143 printf(" %s", keywords[i].str);
1150 * Generate a tree definition file
1153 gen_tree(const struct node *np, int level)
1155 const struct node *sp;
1158 printf("%*s(%u %s", 2 * level, "", np->id, np->name);
1163 print_syntax(np->u.leaf.syntax);
1164 if (np->u.leaf.subtype != NULL)
1165 printf(" | %s", np->u.leaf.subtype);
1166 printf(" %s%s%s)\n", np->u.leaf.func,
1167 (np->flags & FL_GET) ? " GET" : "",
1168 (np->flags & FL_SET) ? " SET" : "");
1172 if (TAILQ_EMPTY(&np->u.tree.subs)) {
1176 TAILQ_FOREACH(sp, &np->u.tree.subs, link)
1177 gen_tree(sp, level + 1);
1178 printf("%*s)\n", 2 * level, "");
1185 for (i = 0; i < SNMP_INDEX_COUNT(np->u.entry.index); i++) {
1186 print_syntax(SNMP_INDEX(np->u.entry.index, i));
1187 if (np->u.entry.subtypes[i] != NULL)
1188 printf(" | %s", np->u.entry.subtypes[i]);
1190 printf(" %s\n", np->u.entry.func);
1191 TAILQ_FOREACH(sp, &np->u.entry.subs, link)
1192 gen_tree(sp, level + 1);
1193 printf("%*s)\n", 2 * level, "");
1197 print_syntax(np->u.column.syntax);
1198 if (np->u.column.subtype != NULL)
1199 printf(" | %s", np->u.column.subtype);
1200 printf("%s%s)\n", (np->flags & FL_GET) ? " GET" : "",
1201 (np->flags & FL_SET) ? " SET" : "");
1207 extract(FILE *fp, const struct node *np, struct asn_oid *oid, const char *obj,
1208 const struct asn_oid *idx, const char *iname)
1213 if (oid->len == ASN_MAXOIDLEN)
1214 report_node(np, "OID too long");
1215 oid->subs[oid->len++] = np->id;
1217 if (strcmp(obj, np->name) == 0) {
1218 if (oid->len + idx->len >= ASN_MAXOIDLEN)
1219 report_node(np, "OID too long");
1220 fprintf(fp, "#define OID_%s%s\t%u\n", np->name,
1221 iname ? iname : "", np->id);
1222 fprintf(fp, "#define OIDLEN_%s%s\t%u\n", np->name,
1223 iname ? iname : "", oid->len + idx->len);
1224 fprintf(fp, "#define OIDX_%s%s\t{ %u, {", np->name,
1225 iname ? iname : "", oid->len + idx->len);
1226 for (n = 0; n < oid->len; n++)
1227 fprintf(fp, " %u,", oid->subs[n]);
1228 for (n = 0; n < idx->len; n++)
1229 fprintf(fp, " %u,", idx->subs[n]);
1230 fprintf(fp, " } }\n");
1234 if (np->type == NODE_TREE) {
1235 TAILQ_FOREACH(sub, &np->u.tree.subs, link)
1236 if (!extract(fp, sub, oid, obj, idx, iname))
1238 } else if (np->type == NODE_ENTRY) {
1239 TAILQ_FOREACH(sub, &np->u.entry.subs, link)
1240 if (!extract(fp, sub, oid, obj, idx, iname))
1248 gen_extract(FILE *fp, const struct node *root, char *object)
1252 char *s, *e, *end, *iname;
1256 /* look whether the object to extract has an index part */
1259 s = strchr(object, '.');
1261 iname = malloc(strlen(s) + 1);
1263 err(1, "cannot allocated index");
1266 for (e = iname; *e != '\0'; e++)
1273 errx(1, "bad index syntax");
1274 if ((e = strchr(s, '.')) != NULL)
1278 ul = strtoul(s, &end, 0);
1280 errx(1, "bad index syntax '%s'", end);
1282 err(1, "bad index syntax");
1284 if (idx.len == ASN_MAXOIDLEN)
1285 errx(1, "index oid too large");
1286 idx.subs[idx.len++] = ul;
1292 oid.len = PREFIX_LEN;
1293 memcpy(oid.subs, prefix, sizeof(prefix));
1294 ret = extract(fp, root, &oid, object, &idx, iname);
1303 check_sub_order(const struct node *np, const struct node_list *subs)
1306 const struct node *sub;
1307 asn_subid_t maxid = 0;
1309 /* ensure, that subids are ordered */
1311 TAILQ_FOREACH(sub, subs, link) {
1312 if (!first && sub->id <= maxid)
1313 report_node(np, "subids not ordered at %s", sub->name);
1320 * Do some sanity checks on the tree definition and do some computations.
1323 check_tree(struct node *np)
1327 if (np->type == NODE_LEAF || np->type == NODE_COLUMN) {
1328 if ((np->flags & (FL_GET|FL_SET)) != 0)
1333 if (np->type == NODE_ENTRY) {
1334 check_sub_order(np, &np->u.entry.subs);
1336 /* ensure all subnodes are columns */
1337 TAILQ_FOREACH(sub, &np->u.entry.subs, link) {
1338 if (sub->type != NODE_COLUMN)
1339 report_node(np, "entry subnode '%s' is not "
1340 "a column", sub->name);
1344 check_sub_order(np, &np->u.tree.subs);
1346 TAILQ_FOREACH(sub, &np->u.tree.subs, link)
1352 merge_subs(struct node_list *s1, struct node_list *s2)
1354 struct node *n1, *n2;
1356 while (!TAILQ_EMPTY(s2)) {
1357 n2 = TAILQ_FIRST(s2);
1358 TAILQ_REMOVE(s2, n2, link);
1360 TAILQ_FOREACH(n1, s1, link)
1361 if (n1->id >= n2->id)
1364 TAILQ_INSERT_TAIL(s1, n2, link);
1365 else if (n1->id > n2->id)
1366 TAILQ_INSERT_BEFORE(n1, n2, link);
1368 if (n1->type == NODE_TREE && n2->type == NODE_TREE) {
1369 if (strcmp(n1->name, n2->name) != 0)
1370 errx(1, "trees to merge must have "
1371 "same name '%s' '%s'", n1->name,
1373 merge_subs(&n1->u.tree.subs, &n2->u.tree.subs);
1375 } else if (n1->type == NODE_ENTRY &&
1376 n2->type == NODE_ENTRY) {
1377 if (strcmp(n1->name, n2->name) != 0)
1378 errx(1, "entries to merge must have "
1379 "same name '%s' '%s'", n1->name,
1381 if (n1->u.entry.index != n2->u.entry.index)
1382 errx(1, "entries to merge must have "
1383 "same index '%s'", n1->name);
1384 if (strcmp(n1->u.entry.func,
1385 n2->u.entry.func) != 0)
1386 errx(1, "entries to merge must have "
1387 "same op '%s'", n1->name);
1388 merge_subs(&n1->u.entry.subs,
1392 errx(1, "entities to merge must be both "
1393 "trees or both entries: %s, %s",
1394 n1->name, n2->name);
1400 merge(struct node **root, struct node *t)
1403 if (*root == NULL) {
1410 /* both must be trees */
1411 if ((*root)->type != NODE_TREE)
1412 errx(1, "root is not a tree");
1413 if (t->type != NODE_TREE)
1414 errx(1, "can merge only with tree");
1415 if ((*root)->id != t->id)
1416 errx(1, "trees to merge must have same id");
1418 merge_subs(&(*root)->u.tree.subs, &t->u.tree.subs);
1422 unminus(FILE *fp, const char *s)
1425 while (*s != '\0') {
1429 fprintf(fp, "%c", *s);
1435 * Generate helper functions for an enum.
1437 * We always generate a switch statement for the isok function. The compiler
1438 * optimizes this into range checks if possible.
1440 * \param fp file to write to
1442 * \param ccode generate externally visible non-inline functions
1445 gen_enum_funcs(FILE *fp, const struct type *t, int ccode)
1450 fprintf(fp, "static inline ");
1451 fprintf(fp, "int\n");
1452 fprintf(fp, "isok_%s(enum %s s)\n", t->name, t->name);
1454 fprintf(fp, " switch (s) {\n");
1456 const struct enums *e;
1457 TAILQ_FOREACH(e, &t->enums, link) {
1458 fprintf(fp, "\t case %s_", t->name);
1459 unminus(fp, e->name);
1463 fprintf(fp, " return (1);\n");
1464 fprintf(fp, " }\n");
1465 fprintf(fp, " return (0);\n");
1466 fprintf(fp, "}\n\n");
1469 fprintf(fp, "static inline ");
1470 fprintf(fp, "const char *\n");
1471 fprintf(fp, "tostr_%s(enum %s s)\n", t->name, t->name);
1473 fprintf(fp, " static const char *vals[] = { STRING_%s };\n", t->name);
1475 fprintf(fp, " if (isok_%s(s))\n", t->name);
1476 fprintf(fp, " return (vals[(int)s - STROFF_%s]);\n", t->name);
1477 fprintf(fp, " return (\"%s???\");\n", t->name);
1478 fprintf(fp, "}\n\n");
1481 fprintf(fp, "static inline ");
1482 fprintf(fp, "int\n");
1483 fprintf(fp, "fromstr_%s(const char *str, enum %s *s)\n",
1486 fprintf(fp, " static const char *vals[] = { STRING_%s };\n", t->name);
1488 fprintf(fp, " for (size_t i = 0; i < sizeof(vals)/sizeof(vals[0]); i++) {\n");
1489 fprintf(fp, " if (vals[i] != NULL && strcmp(vals[i], str) == 0) {\n");
1490 fprintf(fp, " *s = i + STROFF_%s;\n", t->name);
1491 fprintf(fp, " return (1);\n");
1492 fprintf(fp, " }\n");
1493 fprintf(fp, " }\n");
1494 fprintf(fp, " return (0);\n");
1499 * Generate a definition for the enum packed into a guard against multiple
1502 * \param fp file to write definition to
1504 * \param dof generate functions too
1507 gen_enum(FILE *fp, const struct type *t, int dof)
1509 const struct enums *e;
1510 long min = LONG_MAX;
1513 fprintf(fp, "#ifndef %s_defined__\n", t->name);
1514 fprintf(fp, "#define %s_defined__\n", t->name);
1515 fprintf(fp, "/*\n");
1516 fprintf(fp, " * From %s:%u\n", t->from_fname, t->from_lno);
1517 fprintf(fp, " */\n");
1518 fprintf(fp, "enum %s {\n", t->name);
1519 TAILQ_FOREACH(e, &t->enums, link) {
1520 fprintf(fp, "\t%s_", t->name);
1521 unminus(fp, e->name);
1522 fprintf(fp, " = %ld,\n", e->value);
1526 fprintf(fp, "};\n");
1527 fprintf(fp, "#define STROFF_%s %ld\n", t->name, min);
1528 fprintf(fp, "#define STRING_%s \\\n", t->name);
1529 TAILQ_FOREACH(e, &t->enums, link) {
1530 fprintf(fp, "\t[%ld] = \"%s_", e->value - min, t->name);
1531 unminus(fp, e->name);
1532 fprintf(fp, "\",\\\n");
1536 fprintf(fp, "#ifdef SNMPENUM_FUNCS\n");
1538 gen_enum_funcs(fp, t, 0);
1540 fprintf(fp, "#endif\n");
1543 fprintf(fp, "#endif /* %s_defined__ */\n", t->name);
1547 * Generate helper functions for an enum. This generates code for a c file.
1549 * \param fp file to write to
1550 * \param name enum name
1553 gen_enum_funcs_str(FILE *fp, const char *name)
1555 const struct type *t;
1557 LIST_FOREACH(t, &types, link)
1558 if ((t->is_enum || t->is_bits) && strcmp(t->name, name) == 0) {
1559 gen_enum_funcs(fp, t, 1);
1567 * Generate helper functions for all enums.
1569 * \param fp file to write to
1570 * \param ccode generate externally visible non-inline functions
1573 gen_all_enum_funcs(FILE *fp, int ccode)
1575 const struct type *t;
1577 LIST_FOREACH(t, &types, link)
1578 if (t->is_enum || t->is_bits)
1579 gen_enum_funcs(fp, t, ccode);
1583 gen_enums(FILE *fp, int dof)
1585 const struct type *t;
1587 LIST_FOREACH(t, &types, link)
1588 if (t->is_enum || t->is_bits)
1589 gen_enum(fp, t, dof);
1593 * Extract a given enum to the specified file and optionally generate static
1594 * inline helper functions for them.
1596 * \param fp file to print on
1597 * \param name name of the enum
1598 * \param gen_funcs generate the functions too
1600 * \return 0 if found, -1 otherwise
1603 extract_enum(FILE *fp, const char *name, int gen_funcs)
1605 const struct type *t;
1607 LIST_FOREACH(t, &types, link)
1608 if ((t->is_enum || t->is_bits) && strcmp(t->name, name) == 0) {
1609 gen_enum(fp, t, gen_funcs);
1616 * Extract all enums to the given file and optionally generate static inline
1617 * helper functions for them.
1619 * \param fp file to print on
1620 * \param gen_funcs generate the functions too
1623 extract_all_enums(FILE *fp, int gen_funcs)
1625 const struct type *t;
1627 LIST_FOREACH(t, &types, link)
1628 if (t->is_enum || t->is_bits)
1629 gen_enum(fp, t, gen_funcs);
1633 * Extract enums and optionally generate some helper functions for them.
1635 * \param argc number of arguments
1636 * \param argv arguments (enum names)
1637 * \param gen_funcs which functions to generate
1640 make_enums(int argc, char *argv[], enum gen_funcs gen_funcs)
1642 if (gen_funcs == GEN_FUNCS_C) {
1644 gen_all_enum_funcs(stdout, 1);
1646 for (int i = 0; i < argc; i++)
1647 if (gen_enum_funcs_str(stdout, argv[i]))
1648 errx(1, "enum not found: %s", argv[i]);
1652 extract_all_enums(stdout, gen_funcs == GEN_FUNCS_H);
1654 for (int i = 0; i < argc; i++)
1655 if (extract_enum(stdout, argv[i],
1656 gen_funcs == GEN_FUNCS_H))
1657 errx(1, "enum not found: %s", argv[i]);
1663 * Produce the operation tables for the daemon or a module.
1665 * \param root tree root
1666 * \param gen_funcs generate enum funcs
1669 make_table(const struct node *root, int gen_funcs)
1673 char fname[MAXPATHLEN + 1];
1674 sprintf(fname, "%stree.h", file_prefix);
1675 if ((fp = fopen(fname, "w")) == NULL)
1676 err(1, "%s: ", fname);
1677 gen_header(fp, root, PREFIX_LEN, NULL);
1679 fprintf(fp, "\n#ifdef SNMPTREE_TYPES\n");
1680 gen_enums(fp, gen_funcs);
1681 fprintf(fp, "\n#endif /* SNMPTREE_TYPES */\n\n");
1683 fprintf(fp, "#define %sCTREE_SIZE %u\n", file_prefix, tree_size);
1684 fprintf(fp, "extern const struct snmp_node %sctree[];\n", file_prefix);
1688 sprintf(fname, "%stree.c", file_prefix);
1689 if ((fp = fopen(fname, "w")) == NULL)
1690 err(1, "%s: ", fname);
1691 gen_table(fp, root);
1696 main(int argc, char *argv[])
1698 enum op op = OP_GEN;
1699 enum gen_funcs gen_funcs = GEN_FUNCS_NONE;
1701 char *infile = NULL;
1704 while ((opt = getopt(argc, argv, "dEeFfhI:i:lp:t")) != EOF)
1712 if (op != OP_GEN && op != OP_ENUMS)
1713 errx(1, "-E conflicts with earlier options");
1718 if (op != OP_GEN && op != OP_EXTRACT)
1719 errx(1, "-e conflicts with earlier options");
1724 if (gen_funcs != GEN_FUNCS_NONE &&
1725 gen_funcs != GEN_FUNCS_C)
1726 errx(1, "-F conflicts with -f");
1727 gen_funcs = GEN_FUNCS_C;
1731 if (gen_funcs != GEN_FUNCS_NONE &&
1732 gen_funcs != GEN_FUNCS_H)
1733 errx(1, "-f conflicts with -F");
1734 gen_funcs = GEN_FUNCS_H;
1738 fprintf(stderr, "%s", usgtxt);
1754 file_prefix = optarg;
1755 if (strlen(file_prefix) + strlen("tree.c") >
1757 errx(1, "prefix too long");
1761 if (op != OP_GEN && op != OP_TREE)
1762 errx(1, "-t conflicts with earlier options");
1771 if (infile == NULL) {
1772 input_new(stdin, NULL, "<stdin>");
1775 if ((fp = fopen(infile, "r")) == NULL)
1776 err(1, "%s", infile);
1777 input_new(fp, NULL, infile);
1780 /* parse and check input */
1781 struct node *root = parse_top(gettoken());
1784 while ((tok = gettoken()) != TOK_EOF)
1785 merge(&root, parse_top(tok));
1790 /* do what the user has requested */
1795 errx(1, "-e requires arguments");
1797 for (int i = 0; i < argc; i++)
1798 if (gen_extract(stdout, root, argv[i]))
1799 errx(1, "object not found: %s", argv[i]);
1803 make_enums(argc, argv, gen_funcs);
1808 errx(1, "-t allows no arguments");
1814 errx(1, "tree generation allows no arguments");
1815 make_table(root, gen_funcs == GEN_FUNCS_H);