xref: /freebsd/sbin/ipf/libipf/parsefields.c (revision 41edb306f05651fcaf6c74f9e3557f59f80292e1)
1*41edb306SCy Schubert #include "ipf.h"
2*41edb306SCy Schubert #include <err.h>
3*41edb306SCy Schubert 
4*41edb306SCy Schubert extern int nohdrfields;
5*41edb306SCy Schubert 
6*41edb306SCy Schubert wordtab_t *parsefields(table, arg)
7*41edb306SCy Schubert 	wordtab_t *table;
8*41edb306SCy Schubert 	char *arg;
9*41edb306SCy Schubert {
10*41edb306SCy Schubert 	wordtab_t *f, *fields;
11*41edb306SCy Schubert 	char *s, *t;
12*41edb306SCy Schubert 	int num;
13*41edb306SCy Schubert 
14*41edb306SCy Schubert 	fields = NULL;
15*41edb306SCy Schubert 	num = 0;
16*41edb306SCy Schubert 
17*41edb306SCy Schubert 	for (s = strtok(arg, ","); s != NULL; s = strtok(NULL, ",")) {
18*41edb306SCy Schubert 		t = strchr(s, '=');
19*41edb306SCy Schubert 		if (t != NULL) {
20*41edb306SCy Schubert 			*t++ = '\0';
21*41edb306SCy Schubert 			if (*t == '\0')
22*41edb306SCy Schubert 				nohdrfields = 1;
23*41edb306SCy Schubert 		}
24*41edb306SCy Schubert 
25*41edb306SCy Schubert 		f = findword(table, s);
26*41edb306SCy Schubert 		if (f == NULL) {
27*41edb306SCy Schubert 			fprintf(stderr, "Unknown field '%s'\n", s);
28*41edb306SCy Schubert 			exit(1);
29*41edb306SCy Schubert 		}
30*41edb306SCy Schubert 
31*41edb306SCy Schubert 		num++;
32*41edb306SCy Schubert 		if (fields == NULL) {
33*41edb306SCy Schubert 			fields = malloc(2 * sizeof(*fields));
34*41edb306SCy Schubert 		} else {
35*41edb306SCy Schubert 			fields = reallocarray(fields, num + 1, sizeof(*fields));
36*41edb306SCy Schubert 			if (fields == NULL) {
37*41edb306SCy Schubert 				warnx("memory allocation error at %d in %s in %s", __LINE__, __FUNCTION__, __FILE__);
38*41edb306SCy Schubert 				abort();
39*41edb306SCy Schubert 			}
40*41edb306SCy Schubert 		}
41*41edb306SCy Schubert 
42*41edb306SCy Schubert 		if (t == NULL) {
43*41edb306SCy Schubert 			fields[num - 1].w_word = f->w_word;
44*41edb306SCy Schubert 		} else {
45*41edb306SCy Schubert 			fields[num - 1].w_word = t;
46*41edb306SCy Schubert 		}
47*41edb306SCy Schubert 		fields[num - 1].w_value = f->w_value;
48*41edb306SCy Schubert 		fields[num].w_word = NULL;
49*41edb306SCy Schubert 		fields[num].w_value = 0;
50*41edb306SCy Schubert 	}
51*41edb306SCy Schubert 
52*41edb306SCy Schubert 	return fields;
53*41edb306SCy Schubert }
54