xref: /freebsd/sbin/ipfw/tables.c (revision ad6fc754f3d0dc2047171b41cb4d6e13da3deb98)
1 /*
2  * Copyright (c) 2014 Yandex LLC
3  * Copyright (c) 2014 Alexander V. Chernikov
4  *
5  * Redistribution and use in source forms, with and without modification,
6  * are permitted provided that this entire comment appears intact.
7  *
8  * Redistribution in binary form may occur without any restrictions.
9  * Obviously, it would be nice if you gave credit where credit is due
10  * but requiring it would be too onerous.
11  *
12  * This software is provided ``AS IS'' without any warranties of any kind.
13  *
14  * in-kernel ipfw tables support.
15  *
16  * $FreeBSD$
17  */
18 
19 
20 #include <sys/types.h>
21 #include <sys/param.h>
22 #include <sys/socket.h>
23 #include <sys/sysctl.h>
24 
25 #include <ctype.h>
26 #include <err.h>
27 #include <errno.h>
28 #include <netdb.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <sysexits.h>
33 
34 #include <net/if.h>
35 #include <netinet/in.h>
36 #include <netinet/ip_fw.h>
37 #include <arpa/inet.h>
38 #include <netdb.h>
39 
40 #include "ipfw2.h"
41 
42 static void table_modify_record(ipfw_obj_header *oh, int ac, char *av[],
43     int add, int quiet, int update, int atomic);
44 static int table_flush(ipfw_obj_header *oh);
45 static int table_destroy(ipfw_obj_header *oh);
46 static int table_do_create(ipfw_obj_header *oh, ipfw_xtable_info *i);
47 static int table_do_modify(ipfw_obj_header *oh, ipfw_xtable_info *i);
48 static int table_do_swap(ipfw_obj_header *oh, char *second);
49 static void table_create(ipfw_obj_header *oh, int ac, char *av[]);
50 static void table_modify(ipfw_obj_header *oh, int ac, char *av[]);
51 static void table_lookup(ipfw_obj_header *oh, int ac, char *av[]);
52 static void table_lock(ipfw_obj_header *oh, int lock);
53 static int table_swap(ipfw_obj_header *oh, char *second);
54 static int table_get_info(ipfw_obj_header *oh, ipfw_xtable_info *i);
55 static int table_show_info(ipfw_xtable_info *i, void *arg);
56 static void table_fill_ntlv(ipfw_obj_ntlv *ntlv, char *name, uint32_t set,
57     uint16_t uidx);
58 
59 static int table_flush_one(ipfw_xtable_info *i, void *arg);
60 static int table_show_one(ipfw_xtable_info *i, void *arg);
61 static int table_do_get_list(ipfw_xtable_info *i, ipfw_obj_header **poh);
62 static void table_show_list(ipfw_obj_header *oh, int need_header);
63 static void table_show_entry(ipfw_xtable_info *i, ipfw_obj_tentry *tent);
64 
65 static void tentry_fill_key(ipfw_obj_header *oh, ipfw_obj_tentry *tent,
66     char *key, int add, uint8_t *ptype, uint32_t *pvmask, ipfw_xtable_info *xi);
67 static void tentry_fill_value(ipfw_obj_header *oh, ipfw_obj_tentry *tent,
68     char *arg, uint8_t type, uint32_t vmask);
69 static void table_show_value(char *buf, size_t bufsize, ipfw_table_value *v,
70     uint32_t vmask, int print_ip);
71 
72 typedef int (table_cb_t)(ipfw_xtable_info *i, void *arg);
73 static int tables_foreach(table_cb_t *f, void *arg, int sort);
74 
75 #ifndef s6_addr32
76 #define s6_addr32 __u6_addr.__u6_addr32
77 #endif
78 
79 static struct _s_x tabletypes[] = {
80       { "addr",		IPFW_TABLE_ADDR },
81       { "iface",	IPFW_TABLE_INTERFACE },
82       { "number",	IPFW_TABLE_NUMBER },
83       { "flow",		IPFW_TABLE_FLOW },
84       { NULL, 0 }
85 };
86 
87 static struct _s_x tablevaltypes[] = {
88       { "skipto",	IPFW_VTYPE_SKIPTO },
89       { "pipe",		IPFW_VTYPE_PIPE },
90       { "fib",		IPFW_VTYPE_FIB },
91       { "nat",		IPFW_VTYPE_NAT },
92       { "dscp",		IPFW_VTYPE_DSCP },
93       { "tag",		IPFW_VTYPE_TAG },
94       { "divert",	IPFW_VTYPE_DIVERT },
95       { "netgraph",	IPFW_VTYPE_NETGRAPH },
96       { "limit",	IPFW_VTYPE_LIMIT },
97       { "ipv4",		IPFW_VTYPE_NH4 },
98       { "ipv6",		IPFW_VTYPE_NH6 },
99       { NULL, 0 }
100 };
101 
102 static struct _s_x tablecmds[] = {
103       { "add",		TOK_ADD },
104       { "delete",	TOK_DEL },
105       { "create",	TOK_CREATE },
106       { "destroy",	TOK_DESTROY },
107       { "flush",	TOK_FLUSH },
108       { "modify",	TOK_MODIFY },
109       { "swap",		TOK_SWAP },
110       { "info",		TOK_INFO },
111       { "detail",	TOK_DETAIL },
112       { "list",		TOK_LIST },
113       { "lookup",	TOK_LOOKUP },
114       { "atomic",	TOK_ATOMIC },
115       { "lock",		TOK_LOCK },
116       { "unlock",	TOK_UNLOCK },
117       { NULL, 0 }
118 };
119 
120 static int
121 lookup_host (char *host, struct in_addr *ipaddr)
122 {
123 	struct hostent *he;
124 
125 	if (!inet_aton(host, ipaddr)) {
126 		if ((he = gethostbyname(host)) == NULL)
127 			return(-1);
128 		*ipaddr = *(struct in_addr *)he->h_addr_list[0];
129 	}
130 	return(0);
131 }
132 
133 static int
134 get_token(struct _s_x *table, char *string, char *errbase)
135 {
136 	int tcmd;
137 
138 	if ((tcmd = match_token_relaxed(table, string)) < 0)
139 		errx(EX_USAGE, "%s %s %s",
140 		    (tcmd == 0) ? "invalid" : "ambiguous", errbase, string);
141 
142 	return (tcmd);
143 }
144 
145 /*
146  * This one handles all table-related commands
147  * 	ipfw table NAME create ...
148  * 	ipfw table NAME modify ...
149  * 	ipfw table NAME destroy
150  * 	ipfw table NAME swap NAME
151  * 	ipfw table NAME lock
152  * 	ipfw table NAME unlock
153  * 	ipfw table NAME add addr[/masklen] [value]
154  * 	ipfw table NAME add [addr[/masklen] value] [addr[/masklen] value] ..
155  * 	ipfw table NAME delete addr[/masklen] [addr[/masklen]] ..
156  * 	ipfw table NAME lookup addr
157  * 	ipfw table {NAME | all} flush
158  * 	ipfw table {NAME | all} list
159  * 	ipfw table {NAME | all} info
160  * 	ipfw table {NAME | all} detail
161  */
162 void
163 ipfw_table_handler(int ac, char *av[])
164 {
165 	int do_add, is_all;
166 	int atomic, error, tcmd;
167 	ipfw_xtable_info i;
168 	ipfw_obj_header oh;
169 	char *tablename;
170 	uint32_t set;
171 	void *arg;
172 
173 	memset(&oh, 0, sizeof(oh));
174 	is_all = 0;
175 	if (co.use_set != 0)
176 		set = co.use_set - 1;
177 	else
178 		set = 0;
179 
180 	ac--; av++;
181 	NEED1("table needs name");
182 	tablename = *av;
183 
184 	if (table_check_name(tablename) == 0) {
185 		table_fill_ntlv(&oh.ntlv, *av, set, 1);
186 		oh.idx = 1;
187 	} else {
188 		if (strcmp(tablename, "all") == 0)
189 			is_all = 1;
190 		else
191 			errx(EX_USAGE, "table name %s is invalid", tablename);
192 	}
193 	ac--; av++;
194 	NEED1("table needs command");
195 
196 	tcmd = get_token(tablecmds, *av, "table command");
197 	/* Check if atomic operation was requested */
198 	atomic = 0;
199 	if (tcmd == TOK_ATOMIC) {
200 		ac--; av++;
201 		NEED1("atomic needs command");
202 		tcmd = get_token(tablecmds, *av, "table command");
203 		switch (tcmd) {
204 		case TOK_ADD:
205 			break;
206 		default:
207 			errx(EX_USAGE, "atomic is not compatible with %s", *av);
208 		}
209 		atomic = 1;
210 	}
211 
212 	switch (tcmd) {
213 	case TOK_LIST:
214 	case TOK_INFO:
215 	case TOK_DETAIL:
216 	case TOK_FLUSH:
217 		break;
218 	default:
219 		if (is_all != 0)
220 			errx(EX_USAGE, "table name required");
221 	}
222 
223 	switch (tcmd) {
224 	case TOK_ADD:
225 	case TOK_DEL:
226 		do_add = **av == 'a';
227 		ac--; av++;
228 		table_modify_record(&oh, ac, av, do_add, co.do_quiet,
229 		    co.do_quiet, atomic);
230 		break;
231 	case TOK_CREATE:
232 		ac--; av++;
233 		table_create(&oh, ac, av);
234 		break;
235 	case TOK_MODIFY:
236 		ac--; av++;
237 		table_modify(&oh, ac, av);
238 		break;
239 	case TOK_DESTROY:
240 		if (table_destroy(&oh) != 0)
241 			err(EX_OSERR, "failed to destroy table %s", tablename);
242 		break;
243 	case TOK_FLUSH:
244 		if (is_all == 0) {
245 			if ((error = table_flush(&oh)) != 0)
246 				err(EX_OSERR, "failed to flush table %s info",
247 				    tablename);
248 		} else {
249 			error = tables_foreach(table_flush_one, &oh, 1);
250 			if (error != 0)
251 				err(EX_OSERR, "failed to flush tables list");
252 		}
253 		break;
254 	case TOK_SWAP:
255 		ac--; av++;
256 		NEED1("second table name required");
257 		table_swap(&oh, *av);
258 		break;
259 	case TOK_LOCK:
260 	case TOK_UNLOCK:
261 		table_lock(&oh, (tcmd == TOK_LOCK));
262 		break;
263 	case TOK_DETAIL:
264 	case TOK_INFO:
265 		arg = (tcmd == TOK_DETAIL) ? (void *)1 : NULL;
266 		if (is_all == 0) {
267 			if ((error = table_get_info(&oh, &i)) != 0)
268 				err(EX_OSERR, "failed to request table info");
269 			table_show_info(&i, arg);
270 		} else {
271 			error = tables_foreach(table_show_info, arg, 1);
272 			if (error != 0)
273 				err(EX_OSERR, "failed to request tables list");
274 		}
275 		break;
276 	case TOK_LIST:
277 		if (is_all == 0) {
278 			ipfw_xtable_info i;
279 			if ((error = table_get_info(&oh, &i)) != 0)
280 				err(EX_OSERR, "failed to request table info");
281 			table_show_one(&i, NULL);
282 		} else {
283 			error = tables_foreach(table_show_one, NULL, 1);
284 			if (error != 0)
285 				err(EX_OSERR, "failed to request tables list");
286 		}
287 		break;
288 	case TOK_LOOKUP:
289 		ac--; av++;
290 		table_lookup(&oh, ac, av);
291 		break;
292 	}
293 }
294 
295 static void
296 table_fill_ntlv(ipfw_obj_ntlv *ntlv, char *name, uint32_t set, uint16_t uidx)
297 {
298 
299 	ntlv->head.type = IPFW_TLV_TBL_NAME;
300 	ntlv->head.length = sizeof(ipfw_obj_ntlv);
301 	ntlv->idx = uidx;
302 	ntlv->set = set;
303 	strlcpy(ntlv->name, name, sizeof(ntlv->name));
304 }
305 
306 static void
307 table_fill_objheader(ipfw_obj_header *oh, ipfw_xtable_info *i)
308 {
309 
310 	oh->idx = 1;
311 	table_fill_ntlv(&oh->ntlv, i->tablename, i->set, 1);
312 }
313 
314 static struct _s_x tablenewcmds[] = {
315       { "type",		TOK_TYPE },
316       { "valtype",	TOK_VALTYPE },
317       { "algo",		TOK_ALGO },
318       { "limit",	TOK_LIMIT },
319       { "locked",	TOK_LOCK },
320       { NULL, 0 }
321 };
322 
323 static struct _s_x flowtypecmds[] = {
324       { "src-ip",	IPFW_TFFLAG_SRCIP },
325       { "proto",	IPFW_TFFLAG_PROTO },
326       { "src-port",	IPFW_TFFLAG_SRCPORT },
327       { "dst-ip",	IPFW_TFFLAG_DSTIP },
328       { "dst-port",	IPFW_TFFLAG_DSTPORT },
329       { NULL, 0 }
330 };
331 
332 int
333 table_parse_type(uint8_t ttype, char *p, uint8_t *tflags)
334 {
335 	uint32_t fset, fclear;
336 	char *e;
337 
338 	/* Parse type options */
339 	switch(ttype) {
340 	case IPFW_TABLE_FLOW:
341 		fset = fclear = 0;
342 		if (fill_flags(flowtypecmds, p, &e, &fset, &fclear) != 0)
343 			errx(EX_USAGE,
344 			    "unable to parse flow option %s", e);
345 		*tflags = fset;
346 		break;
347 	default:
348 		return (EX_USAGE);
349 	}
350 
351 	return (0);
352 }
353 
354 void
355 table_print_type(char *tbuf, size_t size, uint8_t type, uint8_t tflags)
356 {
357 	const char *tname;
358 	int l;
359 
360 	if ((tname = match_value(tabletypes, type)) == NULL)
361 		tname = "unknown";
362 
363 	l = snprintf(tbuf, size, "%s", tname);
364 	tbuf += l;
365 	size -= l;
366 
367 	switch(type) {
368 	case IPFW_TABLE_FLOW:
369 		if (tflags != 0) {
370 			*tbuf++ = ':';
371 			l--;
372 			print_flags_buffer(tbuf, size, flowtypecmds, tflags);
373 		}
374 		break;
375 	}
376 }
377 
378 /*
379  * Creates new table
380  *
381  * ipfw table NAME create [ type { addr | iface | number | flow } ]
382  *     [ algo algoname ]
383  */
384 static void
385 table_create(ipfw_obj_header *oh, int ac, char *av[])
386 {
387 	ipfw_xtable_info xi;
388 	int error, tcmd, val;
389 	uint32_t fset, fclear;
390 	size_t sz;
391 	char *e, *p;
392 	char tbuf[128];
393 
394 	sz = sizeof(tbuf);
395 	memset(&xi, 0, sizeof(xi));
396 
397 	while (ac > 0) {
398 		tcmd = get_token(tablenewcmds, *av, "option");
399 		ac--; av++;
400 
401 		switch (tcmd) {
402 		case TOK_LIMIT:
403 			NEED1("limit value required");
404 			xi.limit = strtol(*av, NULL, 10);
405 			ac--; av++;
406 			break;
407 		case TOK_TYPE:
408 			NEED1("table type required");
409 			/* Type may have suboptions after ':' */
410 			if ((p = strchr(*av, ':')) != NULL)
411 				*p++ = '\0';
412 			val = match_token(tabletypes, *av);
413 			if (val == -1) {
414 				concat_tokens(tbuf, sizeof(tbuf), tabletypes,
415 				    ", ");
416 				errx(EX_USAGE,
417 				    "Unknown tabletype: %s. Supported: %s",
418 				    *av, tbuf);
419 			}
420 			xi.type = val;
421 			if (p != NULL) {
422 				error = table_parse_type(val, p, &xi.tflags);
423 				if (error != 0)
424 					errx(EX_USAGE,
425 					    "Unsupported suboptions: %s", p);
426 			}
427 			ac--; av++;
428 			break;
429 		case TOK_VALTYPE:
430 			NEED1("table value type required");
431 			fset = fclear = 0;
432 			val = fill_flags(tablevaltypes, *av, &e, &fset, &fclear);
433 			if (val != -1) {
434 				xi.vmask = fset;
435 				ac--; av++;
436 				break;
437 			}
438 			concat_tokens(tbuf, sizeof(tbuf), tablevaltypes, ", ");
439 			errx(EX_USAGE, "Unknown value type: %s. Supported: %s",
440 			    e, tbuf);
441 			break;
442 		case TOK_ALGO:
443 			NEED1("table algorithm name required");
444 			if (strlen(*av) > sizeof(xi.algoname))
445 				errx(EX_USAGE, "algorithm name too long");
446 			strlcpy(xi.algoname, *av, sizeof(xi.algoname));
447 			ac--; av++;
448 			break;
449 		case TOK_LOCK:
450 			xi.flags |= IPFW_TGFLAGS_LOCKED;
451 			break;
452 		}
453 	}
454 
455 	/* Set some defaults to preserve compability */
456 	if (xi.algoname[0] == '\0' && xi.type == 0)
457 		xi.type = IPFW_TABLE_ADDR;
458 	if (xi.vmask == 0)
459 		xi.vmask = IPFW_VTYPE_LEGACY;
460 
461 	if ((error = table_do_create(oh, &xi)) != 0)
462 		err(EX_OSERR, "Table creation failed");
463 }
464 
465 /*
466  * Creates new table
467  *
468  * Request: [ ipfw_obj_header ipfw_xtable_info ]
469  *
470  * Returns 0 on success.
471  */
472 static int
473 table_do_create(ipfw_obj_header *oh, ipfw_xtable_info *i)
474 {
475 	char tbuf[sizeof(ipfw_obj_header) + sizeof(ipfw_xtable_info)];
476 	int error;
477 
478 	memcpy(tbuf, oh, sizeof(*oh));
479 	memcpy(tbuf + sizeof(*oh), i, sizeof(*i));
480 	oh = (ipfw_obj_header *)tbuf;
481 
482 	error = do_set3(IP_FW_TABLE_XCREATE, &oh->opheader, sizeof(tbuf));
483 
484 	return (error);
485 }
486 
487 /*
488  * Modifies existing table
489  *
490  * ipfw table NAME modify [ limit number ]
491  */
492 static void
493 table_modify(ipfw_obj_header *oh, int ac, char *av[])
494 {
495 	ipfw_xtable_info xi;
496 	int tcmd;
497 	size_t sz;
498 	char tbuf[128];
499 
500 	sz = sizeof(tbuf);
501 	memset(&xi, 0, sizeof(xi));
502 
503 	while (ac > 0) {
504 		tcmd = get_token(tablenewcmds, *av, "option");
505 		ac--; av++;
506 
507 		switch (tcmd) {
508 		case TOK_LIMIT:
509 			NEED1("limit value required");
510 			xi.limit = strtol(*av, NULL, 10);
511 			xi.mflags |= IPFW_TMFLAGS_LIMIT;
512 			ac--; av++;
513 			break;
514 		default:
515 			errx(EX_USAGE, "cmd is not supported for modificatiob");
516 		}
517 	}
518 
519 	if (table_do_modify(oh, &xi) != 0)
520 		err(EX_OSERR, "Table modification failed");
521 }
522 
523 /*
524  * Modifies existing table.
525  *
526  * Request: [ ipfw_obj_header ipfw_xtable_info ]
527  *
528  * Returns 0 on success.
529  */
530 static int
531 table_do_modify(ipfw_obj_header *oh, ipfw_xtable_info *i)
532 {
533 	char tbuf[sizeof(ipfw_obj_header) + sizeof(ipfw_xtable_info)];
534 	int error;
535 
536 	memcpy(tbuf, oh, sizeof(*oh));
537 	memcpy(tbuf + sizeof(*oh), i, sizeof(*i));
538 	oh = (ipfw_obj_header *)tbuf;
539 
540 	error = do_set3(IP_FW_TABLE_XMODIFY, &oh->opheader, sizeof(tbuf));
541 
542 	return (error);
543 }
544 
545 /*
546  * Locks or unlocks given table
547  */
548 static void
549 table_lock(ipfw_obj_header *oh, int lock)
550 {
551 	ipfw_xtable_info xi;
552 
553 	memset(&xi, 0, sizeof(xi));
554 
555 	xi.mflags |= IPFW_TMFLAGS_LOCK;
556 	xi.flags |= (lock != 0) ? IPFW_TGFLAGS_LOCKED : 0;
557 
558 	if (table_do_modify(oh, &xi) != 0)
559 		err(EX_OSERR, "Table %s failed", lock != 0 ? "lock" : "unlock");
560 }
561 
562 /*
563  * Destroys given table specified by @oh->ntlv.
564  * Returns 0 on success.
565  */
566 static int
567 table_destroy(ipfw_obj_header *oh)
568 {
569 
570 	if (do_set3(IP_FW_TABLE_XDESTROY, &oh->opheader, sizeof(*oh)) != 0)
571 		return (-1);
572 
573 	return (0);
574 }
575 
576 /*
577  * Flushes given table specified by @oh->ntlv.
578  * Returns 0 on success.
579  */
580 static int
581 table_flush(ipfw_obj_header *oh)
582 {
583 
584 	if (do_set3(IP_FW_TABLE_XFLUSH, &oh->opheader, sizeof(*oh)) != 0)
585 		return (-1);
586 
587 	return (0);
588 }
589 
590 static int
591 table_do_swap(ipfw_obj_header *oh, char *second)
592 {
593 	char tbuf[sizeof(ipfw_obj_header) + sizeof(ipfw_obj_ntlv)];
594 	int error;
595 
596 	memset(tbuf, 0, sizeof(tbuf));
597 	memcpy(tbuf, oh, sizeof(*oh));
598 	oh = (ipfw_obj_header *)tbuf;
599 	table_fill_ntlv((ipfw_obj_ntlv *)(oh + 1), second, oh->ntlv.set, 1);
600 
601 	error = do_set3(IP_FW_TABLE_XSWAP, &oh->opheader, sizeof(tbuf));
602 
603 	return (error);
604 }
605 
606 /*
607  * Swaps given table with @second one.
608  */
609 static int
610 table_swap(ipfw_obj_header *oh, char *second)
611 {
612 	int error;
613 
614 	if (table_check_name(second) != 0)
615 		errx(EX_USAGE, "table name %s is invalid", second);
616 
617 	error = table_do_swap(oh, second);
618 
619 	switch (error) {
620 	case EINVAL:
621 		errx(EX_USAGE, "Unable to swap table: check types");
622 	case EFBIG:
623 		errx(EX_USAGE, "Unable to swap table: check limits");
624 	}
625 
626 	return (0);
627 }
628 
629 
630 /*
631  * Retrieves table in given table specified by @oh->ntlv.
632  * it inside @i.
633  * Returns 0 on success.
634  */
635 static int
636 table_get_info(ipfw_obj_header *oh, ipfw_xtable_info *i)
637 {
638 	char tbuf[sizeof(ipfw_obj_header) + sizeof(ipfw_xtable_info)];
639 	size_t sz;
640 
641 	sz = sizeof(tbuf);
642 	memset(tbuf, 0, sizeof(tbuf));
643 	memcpy(tbuf, oh, sizeof(*oh));
644 	oh = (ipfw_obj_header *)tbuf;
645 
646 	if (do_get3(IP_FW_TABLE_XINFO, &oh->opheader, &sz) != 0)
647 		return (errno);
648 
649 	if (sz < sizeof(tbuf))
650 		return (EINVAL);
651 
652 	*i = *(ipfw_xtable_info *)(oh + 1);
653 
654 	return (0);
655 }
656 
657 static struct _s_x tablealgoclass[] = {
658       { "hash",		IPFW_TACLASS_HASH },
659       { "array",	IPFW_TACLASS_ARRAY },
660       { "radix",	IPFW_TACLASS_RADIX },
661       { NULL, 0 }
662 };
663 
664 struct ta_cldata {
665 	uint8_t		taclass;
666 	uint8_t		spare4;
667 	uint16_t	itemsize;
668 	uint16_t	itemsize6;
669 	uint32_t	size;
670 	uint32_t	count;
671 };
672 
673 /*
674  * Print global/per-AF table @i algorithm info.
675  */
676 static void
677 table_show_tainfo(ipfw_xtable_info *i, struct ta_cldata *d,
678     const char *af, const char *taclass)
679 {
680 
681 	switch (d->taclass) {
682 	case IPFW_TACLASS_HASH:
683 	case IPFW_TACLASS_ARRAY:
684 		printf(" %salgorithm %s info\n", af, taclass);
685 		if (d->itemsize == d->itemsize6)
686 			printf("  size: %u items: %u itemsize: %u\n",
687 			    d->size, d->count, d->itemsize);
688 		else
689 			printf("  size: %u items: %u "
690 			    "itemsize4: %u itemsize6: %u\n",
691 			    d->size, d->count,
692 			    d->itemsize, d->itemsize6);
693 		break;
694 	case IPFW_TACLASS_RADIX:
695 		printf(" %salgorithm %s info\n", af, taclass);
696 		if (d->itemsize == d->itemsize6)
697 			printf("  items: %u itemsize: %u\n",
698 			    d->count, d->itemsize);
699 		else
700 			printf("  items: %u "
701 			    "itemsize4: %u itemsize6: %u\n",
702 			    d->count, d->itemsize, d->itemsize6);
703 		break;
704 	default:
705 		printf(" algo class: %s\n", taclass);
706 	}
707 }
708 
709 static void
710 table_print_valheader(char *buf, size_t bufsize, uint32_t vmask)
711 {
712 
713 	if (vmask == IPFW_VTYPE_LEGACY) {
714 		snprintf(buf, bufsize, "legacy");
715 		return;
716 	}
717 
718 	print_flags_buffer(buf, bufsize, tablevaltypes, vmask);
719 }
720 
721 /*
722  * Prints table info struct @i in human-readable form.
723  */
724 static int
725 table_show_info(ipfw_xtable_info *i, void *arg)
726 {
727 	const char *vtype;
728 	ipfw_ta_tinfo *tainfo;
729 	int afdata, afitem;
730 	struct ta_cldata d;
731 	char ttype[64], tvtype[64];
732 
733 	table_print_type(ttype, sizeof(ttype), i->type, i->tflags);
734 	table_print_valheader(tvtype, sizeof(tvtype), i->vmask);
735 
736 	printf("--- table(%s), set(%u) ---\n", i->tablename, i->set);
737 	if ((i->flags & IPFW_TGFLAGS_LOCKED) != 0)
738 		printf(" kindex: %d, type: %s, locked\n", i->kidx, ttype);
739 	else
740 		printf(" kindex: %d, type: %s\n", i->kidx, ttype);
741 	printf(" references: %u, valtype: %s\n", i->refcnt, tvtype);
742 	printf(" algorithm: %s\n", i->algoname);
743 	printf(" items: %u, size: %u\n", i->count, i->size);
744 	if (i->limit > 0)
745 		printf(" limit: %u\n", i->limit);
746 
747 	/* Print algo-specific info if requested & set  */
748 	if (arg == NULL)
749 		return (0);
750 
751 	if ((i->ta_info.flags & IPFW_TATFLAGS_DATA) == 0)
752 		return (0);
753 	tainfo = &i->ta_info;
754 
755 	afdata = 0;
756 	afitem = 0;
757 	if (tainfo->flags & IPFW_TATFLAGS_AFDATA)
758 		afdata = 1;
759 	if (tainfo->flags & IPFW_TATFLAGS_AFITEM)
760 		afitem = 1;
761 
762 	memset(&d, 0, sizeof(d));
763 	d.taclass = tainfo->taclass4;
764 	d.size = tainfo->size4;
765 	d.count = tainfo->count4;
766 	d.itemsize = tainfo->itemsize4;
767 	if (afdata == 0 && afitem != 0)
768 		d.itemsize6 = tainfo->itemsize6;
769 	else
770 		d.itemsize6 = d.itemsize;
771 	if ((vtype = match_value(tablealgoclass, d.taclass)) == NULL)
772 		vtype = "unknown";
773 
774 	if (afdata == 0) {
775 		table_show_tainfo(i, &d, "", vtype);
776 	} else {
777 		table_show_tainfo(i, &d, "IPv4 ", vtype);
778 		memset(&d, 0, sizeof(d));
779 		d.taclass = tainfo->taclass6;
780 		if ((vtype = match_value(tablealgoclass, d.taclass)) == NULL)
781 			vtype = "unknown";
782 		d.size = tainfo->size6;
783 		d.count = tainfo->count6;
784 		d.itemsize = tainfo->itemsize6;
785 		d.itemsize6 = d.itemsize;
786 		table_show_tainfo(i, &d, "IPv6 ", vtype);
787 	}
788 
789 	return (0);
790 }
791 
792 
793 /*
794  * Function wrappers which can be used either
795  * as is or as foreach function parameter.
796  */
797 
798 static int
799 table_show_one(ipfw_xtable_info *i, void *arg)
800 {
801 	ipfw_obj_header *oh;
802 	int error;
803 
804 	if ((error = table_do_get_list(i, &oh)) != 0) {
805 		err(EX_OSERR, "Error requesting table %s list", i->tablename);
806 		return (error);
807 	}
808 
809 	table_show_list(oh, 1);
810 
811 	free(oh);
812 	return (0);
813 }
814 
815 static int
816 table_flush_one(ipfw_xtable_info *i, void *arg)
817 {
818 	ipfw_obj_header *oh;
819 
820 	oh = (ipfw_obj_header *)arg;
821 
822 	table_fill_ntlv(&oh->ntlv, i->tablename, i->set, 1);
823 
824 	return (table_flush(oh));
825 }
826 
827 static int
828 table_do_modify_record(int cmd, ipfw_obj_header *oh,
829     ipfw_obj_tentry *tent, int count, int atomic)
830 {
831 	ipfw_obj_ctlv *ctlv;
832 	ipfw_obj_tentry *tent_base;
833 	caddr_t pbuf;
834 	char xbuf[sizeof(*oh) + sizeof(ipfw_obj_ctlv) + sizeof(*tent)];
835 	int error, i;
836 	size_t sz;
837 
838 	sz = sizeof(*ctlv) + sizeof(*tent) * count;
839 	if (count == 1) {
840 		memset(xbuf, 0, sizeof(xbuf));
841 		pbuf = xbuf;
842 	} else {
843 		if ((pbuf = calloc(1, sizeof(*oh) + sz)) == NULL)
844 			return (ENOMEM);
845 	}
846 
847 	memcpy(pbuf, oh, sizeof(*oh));
848 	oh = (ipfw_obj_header *)pbuf;
849 	oh->opheader.version = 1;
850 
851 	ctlv = (ipfw_obj_ctlv *)(oh + 1);
852 	ctlv->count = count;
853 	ctlv->head.length = sz;
854 	if (atomic != 0)
855 		ctlv->flags |= IPFW_CTF_ATOMIC;
856 
857 	tent_base = tent;
858 	memcpy(ctlv + 1, tent, sizeof(*tent) * count);
859 	tent = (ipfw_obj_tentry *)(ctlv + 1);
860 	for (i = 0; i < count; i++, tent++) {
861 		tent->head.length = sizeof(ipfw_obj_tentry);
862 		tent->idx = oh->idx;
863 	}
864 
865 	sz += sizeof(*oh);
866 	error = do_get3(cmd, &oh->opheader, &sz);
867 	tent = (ipfw_obj_tentry *)(ctlv + 1);
868 	/* Copy result back to provided buffer */
869 	memcpy(tent_base, ctlv + 1, sizeof(*tent) * count);
870 
871 	if (pbuf != xbuf)
872 		free(pbuf);
873 
874 	return (error);
875 }
876 
877 static void
878 table_modify_record(ipfw_obj_header *oh, int ac, char *av[], int add,
879     int quiet, int update, int atomic)
880 {
881 	ipfw_obj_tentry *ptent, tent, *tent_buf;
882 	ipfw_xtable_info xi;
883 	uint8_t type;
884 	uint32_t vmask;
885 	int cmd, count, error, i, ignored;
886 	char *texterr, *etxt, *px;
887 
888 	if (ac == 0)
889 		errx(EX_USAGE, "address required");
890 
891 	if (add != 0) {
892 		cmd = IP_FW_TABLE_XADD;
893 		texterr = "Adding record failed";
894 	} else {
895 		cmd = IP_FW_TABLE_XDEL;
896 		texterr = "Deleting record failed";
897 	}
898 
899 	/*
900 	 * Calculate number of entries:
901 	 * Assume [key val] x N for add
902 	 * and
903 	 * key x N for delete
904 	 */
905 	count = (add != 0) ? ac / 2 + 1 : ac;
906 
907 	if (count <= 1) {
908 		/* Adding single entry with/without value */
909 		memset(&tent, 0, sizeof(tent));
910 		tent_buf = &tent;
911 	} else {
912 
913 		if ((tent_buf = calloc(count, sizeof(tent))) == NULL)
914 			errx(EX_OSERR,
915 			    "Unable to allocate memory for all entries");
916 	}
917 	ptent = tent_buf;
918 
919 	memset(&xi, 0, sizeof(xi));
920 	count = 0;
921 	while (ac > 0) {
922 		tentry_fill_key(oh, ptent, *av, add, &type, &vmask, &xi);
923 
924 		/*
925 		 * compability layer: auto-create table if not exists
926 		 */
927 		if (xi.tablename[0] == '\0') {
928 			xi.type = type;
929 			xi.vmask = vmask;
930 			strlcpy(xi.tablename, oh->ntlv.name,
931 			    sizeof(xi.tablename));
932 			fprintf(stderr, "DEPRECATED: inserting data info "
933 			    "non-existent table %s. (auto-created)\n",
934 			    xi.tablename);
935 			table_do_create(oh, &xi);
936 		}
937 
938 		oh->ntlv.type = type;
939 		ac--; av++;
940 
941 		if (add != 0 && ac > 0) {
942 			tentry_fill_value(oh, ptent, *av, type, vmask);
943 			ac--; av++;
944 		}
945 
946 		if (update != 0)
947 			ptent->head.flags |= IPFW_TF_UPDATE;
948 
949 		count++;
950 		ptent++;
951 	}
952 
953 	error = table_do_modify_record(cmd, oh, tent_buf, count, atomic);
954 
955 	quiet = 0;
956 
957 	/*
958 	 * Compatibility stuff: do not yell on duplicate keys or
959 	 * failed deletions.
960 	 */
961 	if (error == 0 || (error == EEXIST && add != 0) ||
962 	    (error == ENOENT && add == 0)) {
963 		if (quiet != 0) {
964 			if (tent_buf != &tent)
965 				free(tent_buf);
966 			return;
967 		}
968 	}
969 
970 	/* Report results back */
971 	ptent = tent_buf;
972 	for (i = 0; i < count; ptent++, i++) {
973 		ignored = 0;
974 		switch (ptent->result) {
975 		case IPFW_TR_ADDED:
976 			px = "added";
977 			break;
978 		case IPFW_TR_DELETED:
979 			px = "deleted";
980 			break;
981 		case IPFW_TR_UPDATED:
982 			px = "updated";
983 			break;
984 		case IPFW_TR_LIMIT:
985 			px = "limit";
986 			ignored = 1;
987 			break;
988 		case IPFW_TR_ERROR:
989 			px = "error";
990 			ignored = 1;
991 			break;
992 		case IPFW_TR_NOTFOUND:
993 			px = "notfound";
994 			ignored = 1;
995 			break;
996 		case IPFW_TR_EXISTS:
997 			px = "exists";
998 			ignored = 1;
999 			break;
1000 		case IPFW_TR_IGNORED:
1001 			px = "ignored";
1002 			ignored = 1;
1003 			break;
1004 		default:
1005 			px = "unknown";
1006 			ignored = 1;
1007 		}
1008 
1009 		if (error != 0 && atomic != 0 && ignored == 0)
1010 			printf("%s(reverted): ", px);
1011 		else
1012 			printf("%s: ", px);
1013 
1014 		table_show_entry(&xi, ptent);
1015 	}
1016 
1017 	if (tent_buf != &tent)
1018 		free(tent_buf);
1019 
1020 	if (error == 0)
1021 		return;
1022 	/* Get real OS error */
1023 	error = errno;
1024 
1025 	/* Try to provide more human-readable error */
1026 	switch (error) {
1027 	case EEXIST:
1028 		etxt = "record already exists";
1029 		break;
1030 	case EFBIG:
1031 		etxt = "limit hit";
1032 		break;
1033 	case ESRCH:
1034 		etxt = "table not found";
1035 		break;
1036 	case ENOENT:
1037 		etxt = "record not found";
1038 		break;
1039 	case EACCES:
1040 		etxt = "table is locked";
1041 		break;
1042 	default:
1043 		etxt = strerror(error);
1044 	}
1045 
1046 	errx(EX_OSERR, "%s: %s", texterr, etxt);
1047 }
1048 
1049 static int
1050 table_do_lookup(ipfw_obj_header *oh, char *key, ipfw_xtable_info *xi,
1051     ipfw_obj_tentry *xtent)
1052 {
1053 	char xbuf[sizeof(ipfw_obj_header) + sizeof(ipfw_obj_tentry)];
1054 	ipfw_obj_tentry *tent;
1055 	uint8_t type;
1056 	uint32_t vmask;
1057 	size_t sz;
1058 
1059 	memcpy(xbuf, oh, sizeof(*oh));
1060 	oh = (ipfw_obj_header *)xbuf;
1061 	tent = (ipfw_obj_tentry *)(oh + 1);
1062 
1063 	memset(tent, 0, sizeof(*tent));
1064 	tent->head.length = sizeof(*tent);
1065 	tent->idx = 1;
1066 
1067 	tentry_fill_key(oh, tent, key, 0, &type, &vmask, xi);
1068 	oh->ntlv.type = type;
1069 
1070 	sz = sizeof(xbuf);
1071 	if (do_get3(IP_FW_TABLE_XFIND, &oh->opheader, &sz) != 0)
1072 		return (errno);
1073 
1074 	if (sz < sizeof(xbuf))
1075 		return (EINVAL);
1076 
1077 	*xtent = *tent;
1078 
1079 	return (0);
1080 }
1081 
1082 static void
1083 table_lookup(ipfw_obj_header *oh, int ac, char *av[])
1084 {
1085 	ipfw_obj_tentry xtent;
1086 	ipfw_xtable_info xi;
1087 	char key[64];
1088 	int error;
1089 
1090 	if (ac == 0)
1091 		errx(EX_USAGE, "address required");
1092 
1093 	strlcpy(key, *av, sizeof(key));
1094 
1095 	memset(&xi, 0, sizeof(xi));
1096 	error = table_do_lookup(oh, key, &xi, &xtent);
1097 
1098 	switch (error) {
1099 	case 0:
1100 		break;
1101 	case ESRCH:
1102 		errx(EX_UNAVAILABLE, "Table %s not found", oh->ntlv.name);
1103 	case ENOENT:
1104 		errx(EX_UNAVAILABLE, "Entry %s not found", *av);
1105 	case ENOTSUP:
1106 		errx(EX_UNAVAILABLE, "Table %s algo does not support "
1107 		    "\"lookup\" method", oh->ntlv.name);
1108 	default:
1109 		err(EX_OSERR, "getsockopt(IP_FW_TABLE_XFIND)");
1110 	}
1111 
1112 	table_show_entry(&xi, &xtent);
1113 }
1114 
1115 static void
1116 tentry_fill_key_type(char *arg, ipfw_obj_tentry *tentry, uint8_t type,
1117     uint8_t tflags)
1118 {
1119 	char *p, *pp;
1120 	int mask, af;
1121 	struct in6_addr *paddr, tmp;
1122 	struct tflow_entry *tfe;
1123 	uint32_t key, *pkey;
1124 	uint16_t port;
1125 	struct protoent *pent;
1126 	struct servent *sent;
1127 	int masklen;
1128 
1129 	masklen = 0;
1130 	af = 0;
1131 	paddr = (struct in6_addr *)&tentry->k;
1132 
1133 	switch (type) {
1134 	case IPFW_TABLE_ADDR:
1135 		/* Remove / if exists */
1136 		if ((p = strchr(arg, '/')) != NULL) {
1137 			*p = '\0';
1138 			mask = atoi(p + 1);
1139 		}
1140 
1141 		if (inet_pton(AF_INET, arg, paddr) == 1) {
1142 			if (p != NULL && mask > 32)
1143 				errx(EX_DATAERR, "bad IPv4 mask width: %s",
1144 				    p + 1);
1145 
1146 			masklen = p ? mask : 32;
1147 			af = AF_INET;
1148 		} else if (inet_pton(AF_INET6, arg, paddr) == 1) {
1149 			if (IN6_IS_ADDR_V4COMPAT(paddr))
1150 				errx(EX_DATAERR,
1151 				    "Use IPv4 instead of v4-compatible");
1152 			if (p != NULL && mask > 128)
1153 				errx(EX_DATAERR, "bad IPv6 mask width: %s",
1154 				    p + 1);
1155 
1156 			masklen = p ? mask : 128;
1157 			af = AF_INET6;
1158 		} else {
1159 			/* Assume FQDN */
1160 			if (lookup_host(arg, (struct in_addr *)paddr) != 0)
1161 				errx(EX_NOHOST, "hostname ``%s'' unknown", arg);
1162 
1163 			masklen = 32;
1164 			type = IPFW_TABLE_ADDR;
1165 			af = AF_INET;
1166 		}
1167 		break;
1168 	case IPFW_TABLE_INTERFACE:
1169 		/* Assume interface name. Copy significant data only */
1170 		mask = MIN(strlen(arg), IF_NAMESIZE - 1);
1171 		memcpy(paddr, arg, mask);
1172 		/* Set mask to exact match */
1173 		masklen = 8 * IF_NAMESIZE;
1174 		break;
1175 	case IPFW_TABLE_NUMBER:
1176 		/* Port or any other key */
1177 		key = strtol(arg, &p, 10);
1178 		if (*p != '\0')
1179 			errx(EX_DATAERR, "Invalid number: %s", arg);
1180 
1181 		pkey = (uint32_t *)paddr;
1182 		*pkey = key;
1183 		masklen = 32;
1184 		break;
1185 	case IPFW_TABLE_FLOW:
1186 		/* Assume [src-ip][,proto][,src-port][,dst-ip][,dst-port] */
1187 		tfe = &tentry->k.flow;
1188 		af = 0;
1189 
1190 		/* Handle <ipv4|ipv6> */
1191 		if ((tflags & IPFW_TFFLAG_SRCIP) != 0) {
1192 			if ((p = strchr(arg, ',')) != NULL)
1193 				*p++ = '\0';
1194 			/* Determine family using temporary storage */
1195 			if (inet_pton(AF_INET, arg, &tmp) == 1) {
1196 				if (af != 0 && af != AF_INET)
1197 					errx(EX_DATAERR,
1198 					    "Inconsistent address family\n");
1199 				af = AF_INET;
1200 				memcpy(&tfe->a.a4.sip, &tmp, 4);
1201 			} else if (inet_pton(AF_INET6, arg, &tmp) == 1) {
1202 				if (af != 0 && af != AF_INET6)
1203 					errx(EX_DATAERR,
1204 					    "Inconsistent address family\n");
1205 				af = AF_INET6;
1206 				memcpy(&tfe->a.a6.sip6, &tmp, 16);
1207 			}
1208 
1209 			arg = p;
1210 		}
1211 
1212 		/* Handle <proto-num|proto-name> */
1213 		if ((tflags & IPFW_TFFLAG_PROTO) != 0) {
1214 			if (arg == NULL)
1215 				errx(EX_DATAERR, "invalid key: proto missing");
1216 			if ((p = strchr(arg, ',')) != NULL)
1217 				*p++ = '\0';
1218 
1219 			key = strtol(arg, &pp, 10);
1220 			if (*pp != '\0') {
1221 				if ((pent = getprotobyname(arg)) == NULL)
1222 					errx(EX_DATAERR, "Unknown proto: %s",
1223 					    arg);
1224 				else
1225 					key = pent->p_proto;
1226 			}
1227 
1228 			if (key > 255)
1229 				errx(EX_DATAERR, "Bad protocol number: %u",key);
1230 
1231 			tfe->proto = key;
1232 
1233 			arg = p;
1234 		}
1235 
1236 		/* Handle <port-num|service-name> */
1237 		if ((tflags & IPFW_TFFLAG_SRCPORT) != 0) {
1238 			if (arg == NULL)
1239 				errx(EX_DATAERR, "invalid key: src port missing");
1240 			if ((p = strchr(arg, ',')) != NULL)
1241 				*p++ = '\0';
1242 
1243 			if ((port = htons(strtol(arg, NULL, 10))) == 0) {
1244 				if ((sent = getservbyname(arg, NULL)) == NULL)
1245 					errx(EX_DATAERR, "Unknown service: %s",
1246 					    arg);
1247 				else
1248 					key = sent->s_port;
1249 			}
1250 
1251 			tfe->sport = port;
1252 
1253 			arg = p;
1254 		}
1255 
1256 		/* Handle <ipv4|ipv6>*/
1257 		if ((tflags & IPFW_TFFLAG_DSTIP) != 0) {
1258 			if (arg == NULL)
1259 				errx(EX_DATAERR, "invalid key: dst ip missing");
1260 			if ((p = strchr(arg, ',')) != NULL)
1261 				*p++ = '\0';
1262 			/* Determine family using temporary storage */
1263 			if (inet_pton(AF_INET, arg, &tmp) == 1) {
1264 				if (af != 0 && af != AF_INET)
1265 					errx(EX_DATAERR,
1266 					    "Inconsistent address family");
1267 				af = AF_INET;
1268 				memcpy(&tfe->a.a4.dip, &tmp, 4);
1269 			} else if (inet_pton(AF_INET6, arg, &tmp) == 1) {
1270 				if (af != 0 && af != AF_INET6)
1271 					errx(EX_DATAERR,
1272 					    "Inconsistent address family");
1273 				af = AF_INET6;
1274 				memcpy(&tfe->a.a6.dip6, &tmp, 16);
1275 			}
1276 
1277 			arg = p;
1278 		}
1279 
1280 		/* Handle <port-num|service-name> */
1281 		if ((tflags & IPFW_TFFLAG_DSTPORT) != 0) {
1282 			if (arg == NULL)
1283 				errx(EX_DATAERR, "invalid key: dst port missing");
1284 			if ((p = strchr(arg, ',')) != NULL)
1285 				*p++ = '\0';
1286 
1287 			if ((port = htons(strtol(arg, NULL, 10))) == 0) {
1288 				if ((sent = getservbyname(arg, NULL)) == NULL)
1289 					errx(EX_DATAERR, "Unknown service: %s",
1290 					    arg);
1291 				else
1292 					key = sent->s_port;
1293 			}
1294 
1295 			tfe->dport = port;
1296 
1297 			arg = p;
1298 		}
1299 
1300 		tfe->af = af;
1301 
1302 		break;
1303 
1304 	default:
1305 		errx(EX_DATAERR, "Unsupported table type: %d", type);
1306 	}
1307 
1308 	tentry->subtype = af;
1309 	tentry->masklen = masklen;
1310 }
1311 
1312 static void
1313 tentry_fill_key(ipfw_obj_header *oh, ipfw_obj_tentry *tent, char *key,
1314     int add, uint8_t *ptype, uint32_t *pvmask, ipfw_xtable_info *xi)
1315 {
1316 	uint8_t type, tflags;
1317 	uint32_t vmask;
1318 	int error;
1319 	char *del;
1320 
1321 	type = 0;
1322 	tflags = 0;
1323 	vmask = 0;
1324 
1325 	if (xi->tablename[0] == '\0')
1326 		error = table_get_info(oh, xi);
1327 	else
1328 		error = 0;
1329 
1330 	if (error == 0) {
1331 		/* Table found. */
1332 		type = xi->type;
1333 		tflags = xi->tflags;
1334 		vmask = xi->vmask;
1335 	} else {
1336 		if (error != ESRCH)
1337 			errx(EX_OSERR, "Error requesting table %s info",
1338 			    oh->ntlv.name);
1339 		if (add == 0)
1340 			errx(EX_DATAERR, "Table %s does not exist",
1341 			    oh->ntlv.name);
1342 		/*
1343 		 * Table does not exist.
1344 		 * Compability layer: try to interpret data as ADDR
1345 		 * before failing.
1346 		 */
1347 		if ((del = strchr(key, '/')) != NULL)
1348 			*del = '\0';
1349 		if (inet_pton(AF_INET, key, &tent->k.addr6) == 1 ||
1350 		    inet_pton(AF_INET6, key, &tent->k.addr6) == 1) {
1351 			/* OK Prepare and send */
1352 			type = IPFW_TABLE_ADDR;
1353 			vmask = IPFW_VTYPE_LEGACY;
1354 		} else {
1355 			/* Inknown key */
1356 			errx(EX_USAGE, "Table %s does not exist, cannot guess "
1357 			    "key '%s' type", oh->ntlv.name, key);
1358 		}
1359 		if (del != NULL)
1360 			*del = '/';
1361 	}
1362 
1363 	tentry_fill_key_type(key, tent, type, tflags);
1364 
1365 	*ptype = type;
1366 	*pvmask = vmask;
1367 }
1368 
1369 static void
1370 set_legacy_value(uint32_t val, ipfw_table_value *v)
1371 {
1372 	v->tag = val;
1373 	v->pipe = val;
1374 	v->divert = val;
1375 	v->skipto = val;
1376 	v->netgraph = val;
1377 	v->fib = val;
1378 	v->nat = val;
1379 	v->nh4 = val;
1380 	v->dscp = (uint8_t)val;
1381 	v->limit = val;
1382 }
1383 
1384 static void
1385 tentry_fill_value(ipfw_obj_header *oh, ipfw_obj_tentry *tent, char *arg,
1386     uint8_t type, uint32_t vmask)
1387 {
1388 	struct addrinfo hints, *res;
1389 	uint32_t a4, flag, val, vm;
1390 	ipfw_table_value *v;
1391 	uint32_t i;
1392 	int dval;
1393 	char *comma, *e, *etype, *n, *p;
1394 
1395 	v = &tent->v.value;
1396 	vm = vmask;
1397 
1398 	/* Compat layer: keep old behavior for legacy value types */
1399 	if (vmask == IPFW_VTYPE_LEGACY) {
1400 		/* Try to interpret as number first */
1401 		val = strtoul(arg, &p, 0);
1402 		if (*p == '\0') {
1403 			set_legacy_value(val, v);
1404 			return;
1405 		}
1406 		if (inet_pton(AF_INET, arg, &val) == 1) {
1407 			set_legacy_value(ntohl(val), v);
1408 			return;
1409 		}
1410 		/* Try hostname */
1411 		if (lookup_host(arg, (struct in_addr *)&val) == 0) {
1412 			set_legacy_value(val, v);
1413 			return;
1414 		}
1415 		errx(EX_OSERR, "Unable to parse value %s", arg);
1416 	}
1417 
1418 	/*
1419 	 * Shorthands: handle single value if vmask consists
1420 	 * of numbers only. e.g.:
1421 	 * vmask = "fib,skipto" -> treat input "1" as "1,1"
1422 	 */
1423 
1424 	n = arg;
1425 	etype = NULL;
1426 	for (i = 1; i < (1 << 31); i *= 2) {
1427 		if ((flag = (vmask & i)) == 0)
1428 			continue;
1429 		vmask &= ~flag;
1430 
1431 		if ((comma = strchr(n, ',')) != NULL)
1432 			*comma = '\0';
1433 
1434 		switch (flag) {
1435 		case IPFW_VTYPE_TAG:
1436 			v->tag = strtol(n, &e, 10);
1437 			if (*e != '\0')
1438 				etype = "tag";
1439 			break;
1440 		case IPFW_VTYPE_PIPE:
1441 			v->pipe = strtol(n, &e, 10);
1442 			if (*e != '\0')
1443 				etype = "pipe";
1444 			break;
1445 		case IPFW_VTYPE_DIVERT:
1446 			v->divert = strtol(n, &e, 10);
1447 			if (*e != '\0')
1448 				etype = "divert";
1449 			break;
1450 		case IPFW_VTYPE_SKIPTO:
1451 			v->skipto = strtol(n, &e, 10);
1452 			if (*e != '\0')
1453 				etype = "skipto";
1454 			break;
1455 		case IPFW_VTYPE_NETGRAPH:
1456 			v->netgraph = strtol(n, &e, 10);
1457 			if (*e != '\0')
1458 				etype = "netgraph";
1459 			break;
1460 		case IPFW_VTYPE_FIB:
1461 			v->fib = strtol(n, &e, 10);
1462 			if (*e != '\0')
1463 				etype = "fib";
1464 			break;
1465 		case IPFW_VTYPE_NAT:
1466 			v->nat = strtol(n, &e, 10);
1467 			if (*e != '\0')
1468 				etype = "nat";
1469 			break;
1470 		case IPFW_VTYPE_LIMIT:
1471 			v->limit = strtol(n, &e, 10);
1472 			if (*e != '\0')
1473 				etype = "limit";
1474 			break;
1475 		case IPFW_VTYPE_NH4:
1476 			if (strchr(n, '.') != NULL &&
1477 			    inet_pton(AF_INET, n, &a4) == 1) {
1478 				v->nh4 = ntohl(a4);
1479 				break;
1480 			}
1481 			if (lookup_host(n, (struct in_addr *)&v->nh4) == 0)
1482 				break;
1483 			etype = "ipv4";
1484 			break;
1485 		case IPFW_VTYPE_DSCP:
1486 			if (isalpha(*n)) {
1487 				if ((dval = match_token(f_ipdscp, n)) != -1) {
1488 					v->dscp = dval;
1489 					break;
1490 				} else
1491 					etype = "DSCP code";
1492 			} else {
1493 				v->dscp = strtol(n, &e, 10);
1494 				if (v->dscp > 63 || *e != '\0')
1495 					etype = "DSCP value";
1496 			}
1497 			break;
1498 		case IPFW_VTYPE_NH6:
1499 			if (strchr(n, ':') != NULL) {
1500 				memset(&hints, 0, sizeof(hints));
1501 				hints.ai_family = AF_INET6;
1502 				hints.ai_flags = AI_NUMERICHOST;
1503 				if (getaddrinfo(n, NULL, &hints, &res) == 0) {
1504 					v->nh6 = ((struct sockaddr_in6 *)
1505 					    res->ai_addr)->sin6_addr;
1506 					v->zoneid = ((struct sockaddr_in6 *)
1507 					    res->ai_addr)->sin6_scope_id;
1508 					freeaddrinfo(res);
1509 					break;
1510 				}
1511 			}
1512 			etype = "ipv6";
1513 			break;
1514 		}
1515 
1516 		if (etype != NULL)
1517 			errx(EX_USAGE, "Unable to parse %s as %s", n, etype);
1518 
1519 		if (comma != NULL)
1520 			*comma++ = ',';
1521 
1522 		if ((n = comma) != NULL)
1523 			continue;
1524 
1525 		/* End of input. */
1526 		if (vmask != 0)
1527 			errx(EX_USAGE, "Not enough fields inside value");
1528 	}
1529 }
1530 
1531 /*
1532  * Compare table names.
1533  * Honor number comparison.
1534  */
1535 static int
1536 tablename_cmp(const void *a, const void *b)
1537 {
1538 	ipfw_xtable_info *ia, *ib;
1539 
1540 	ia = (ipfw_xtable_info *)a;
1541 	ib = (ipfw_xtable_info *)b;
1542 
1543 	return (stringnum_cmp(ia->tablename, ib->tablename));
1544 }
1545 
1546 /*
1547  * Retrieves table list from kernel,
1548  * optionally sorts it and calls requested function for each table.
1549  * Returns 0 on success.
1550  */
1551 static int
1552 tables_foreach(table_cb_t *f, void *arg, int sort)
1553 {
1554 	ipfw_obj_lheader *olh;
1555 	ipfw_xtable_info *info;
1556 	size_t sz;
1557 	int i, error;
1558 
1559 	/* Start with reasonable default */
1560 	sz = sizeof(*olh) + 16 * sizeof(ipfw_xtable_info);
1561 
1562 	for (;;) {
1563 		if ((olh = calloc(1, sz)) == NULL)
1564 			return (ENOMEM);
1565 
1566 		olh->size = sz;
1567 		if (do_get3(IP_FW_TABLES_XLIST, &olh->opheader, &sz) != 0) {
1568 			sz = olh->size;
1569 			free(olh);
1570 			if (errno != ENOMEM)
1571 				return (errno);
1572 			continue;
1573 		}
1574 
1575 		if (sort != 0)
1576 			qsort(olh + 1, olh->count, olh->objsize, tablename_cmp);
1577 
1578 		info = (ipfw_xtable_info *)(olh + 1);
1579 		for (i = 0; i < olh->count; i++) {
1580 			error = f(info, arg); /* Ignore errors for now */
1581 			info = (ipfw_xtable_info *)((caddr_t)info + olh->objsize);
1582 		}
1583 
1584 		free(olh);
1585 		break;
1586 	}
1587 
1588 	return (0);
1589 }
1590 
1591 
1592 /*
1593  * Retrieves all entries for given table @i in
1594  * eXtended format. Allocate buffer large enough
1595  * to store result. Called needs to free it later.
1596  *
1597  * Returns 0 on success.
1598  */
1599 static int
1600 table_do_get_list(ipfw_xtable_info *i, ipfw_obj_header **poh)
1601 {
1602 	ipfw_obj_header *oh;
1603 	size_t sz;
1604 	int c;
1605 
1606 	sz = 0;
1607 	oh = NULL;
1608 	for (c = 0; c < 8; c++) {
1609 		if (sz < i->size)
1610 			sz = i->size + 44;
1611 		if (oh != NULL)
1612 			free(oh);
1613 		if ((oh = calloc(1, sz)) == NULL)
1614 			continue;
1615 		table_fill_objheader(oh, i);
1616 		oh->opheader.version = 1; /* Current version */
1617 		if (do_get3(IP_FW_TABLE_XLIST, &oh->opheader, &sz) == 0) {
1618 			*poh = oh;
1619 			return (0);
1620 		}
1621 
1622 		if (errno != ENOMEM)
1623 			break;
1624 	}
1625 	free(oh);
1626 
1627 	return (errno);
1628 }
1629 
1630 /*
1631  * Shows all entries from @oh in human-readable format
1632  */
1633 static void
1634 table_show_list(ipfw_obj_header *oh, int need_header)
1635 {
1636 	ipfw_obj_tentry *tent;
1637 	uint32_t count;
1638 	ipfw_xtable_info *i;
1639 
1640 	i = (ipfw_xtable_info *)(oh + 1);
1641 	tent = (ipfw_obj_tentry *)(i + 1);
1642 
1643 	if (need_header)
1644 		printf("--- table(%s), set(%u) ---\n", i->tablename, i->set);
1645 
1646 	count = i->count;
1647 	while (count > 0) {
1648 		table_show_entry(i, tent);
1649 		tent = (ipfw_obj_tentry *)((caddr_t)tent + tent->head.length);
1650 		count--;
1651 	}
1652 }
1653 
1654 static void
1655 table_show_value(char *buf, size_t bufsize, ipfw_table_value *v,
1656     uint32_t vmask, int print_ip)
1657 {
1658 	char abuf[INET6_ADDRSTRLEN + IF_NAMESIZE + 2];
1659 	struct sockaddr_in6 sa6;
1660 	uint32_t flag, i, l;
1661 	size_t sz;
1662 	struct in_addr a4;
1663 
1664 	sz = bufsize;
1665 
1666 	/*
1667 	 * Some shorthands for printing values:
1668 	 * legacy assumes all values are equal, so keep the first one.
1669 	 */
1670 	if (vmask == IPFW_VTYPE_LEGACY) {
1671 		if (print_ip != 0) {
1672 			flag = htonl(v->tag);
1673 			inet_ntop(AF_INET, &flag, buf, sz);
1674 		} else
1675 			snprintf(buf, sz, "%u", v->tag);
1676 		return;
1677 	}
1678 
1679 	for (i = 1; i < (1 << 31); i *= 2) {
1680 		if ((flag = (vmask & i)) == 0)
1681 			continue;
1682 		l = 0;
1683 
1684 		switch (flag) {
1685 		case IPFW_VTYPE_TAG:
1686 			l = snprintf(buf, sz, "%u,", v->tag);
1687 			break;
1688 		case IPFW_VTYPE_PIPE:
1689 			l = snprintf(buf, sz, "%u,", v->pipe);
1690 			break;
1691 		case IPFW_VTYPE_DIVERT:
1692 			l = snprintf(buf, sz, "%d,", v->divert);
1693 			break;
1694 		case IPFW_VTYPE_SKIPTO:
1695 			l = snprintf(buf, sz, "%d,", v->skipto);
1696 			break;
1697 		case IPFW_VTYPE_NETGRAPH:
1698 			l = snprintf(buf, sz, "%u,", v->netgraph);
1699 			break;
1700 		case IPFW_VTYPE_FIB:
1701 			l = snprintf(buf, sz, "%u,", v->fib);
1702 			break;
1703 		case IPFW_VTYPE_NAT:
1704 			l = snprintf(buf, sz, "%u,", v->nat);
1705 			break;
1706 		case IPFW_VTYPE_LIMIT:
1707 			l = snprintf(buf, sz, "%u,", v->limit);
1708 			break;
1709 		case IPFW_VTYPE_NH4:
1710 			a4.s_addr = htonl(v->nh4);
1711 			inet_ntop(AF_INET, &a4, abuf, sizeof(abuf));
1712 			l = snprintf(buf, sz, "%s,", abuf);
1713 			break;
1714 		case IPFW_VTYPE_DSCP:
1715 			l = snprintf(buf, sz, "%d,", v->dscp);
1716 			break;
1717 		case IPFW_VTYPE_NH6:
1718 			sa6.sin6_family = AF_INET6;
1719 			sa6.sin6_len = sizeof(sa6);
1720 			sa6.sin6_addr = v->nh6;
1721 			sa6.sin6_port = 0;
1722 			sa6.sin6_scope_id = v->zoneid;
1723 			if (getnameinfo((const struct sockaddr *)&sa6,
1724 			    sa6.sin6_len, abuf, sizeof(abuf), NULL, 0,
1725 			    NI_NUMERICHOST) == 0)
1726 				l = snprintf(buf, sz, "%s,", abuf);
1727 			break;
1728 		}
1729 
1730 		buf += l;
1731 		sz -= l;
1732 	}
1733 
1734 	if (sz != bufsize)
1735 		*(buf - 1) = '\0';
1736 }
1737 
1738 static void
1739 table_show_entry(ipfw_xtable_info *i, ipfw_obj_tentry *tent)
1740 {
1741 	char *comma, tbuf[128], pval[128];
1742 	void *paddr;
1743 	struct tflow_entry *tfe;
1744 
1745 	table_show_value(pval, sizeof(pval), &tent->v.value, i->vmask,
1746 	    co.do_value_as_ip);
1747 
1748 	switch (i->type) {
1749 	case IPFW_TABLE_ADDR:
1750 		/* IPv4 or IPv6 prefixes */
1751 		inet_ntop(tent->subtype, &tent->k, tbuf, sizeof(tbuf));
1752 		printf("%s/%u %s\n", tbuf, tent->masklen, pval);
1753 		break;
1754 	case IPFW_TABLE_INTERFACE:
1755 		/* Interface names */
1756 		printf("%s %s\n", tent->k.iface, pval);
1757 		break;
1758 	case IPFW_TABLE_NUMBER:
1759 		/* numbers */
1760 		printf("%u %s\n", tent->k.key, pval);
1761 		break;
1762 	case IPFW_TABLE_FLOW:
1763 		/* flows */
1764 		tfe = &tent->k.flow;
1765 		comma = "";
1766 
1767 		if ((i->tflags & IPFW_TFFLAG_SRCIP) != 0) {
1768 			if (tfe->af == AF_INET)
1769 				paddr = &tfe->a.a4.sip;
1770 			else
1771 				paddr = &tfe->a.a6.sip6;
1772 
1773 			inet_ntop(tfe->af, paddr, tbuf, sizeof(tbuf));
1774 			printf("%s%s", comma, tbuf);
1775 			comma = ",";
1776 		}
1777 
1778 		if ((i->tflags & IPFW_TFFLAG_PROTO) != 0) {
1779 			printf("%s%d", comma, tfe->proto);
1780 			comma = ",";
1781 		}
1782 
1783 		if ((i->tflags & IPFW_TFFLAG_SRCPORT) != 0) {
1784 			printf("%s%d", comma, ntohs(tfe->sport));
1785 			comma = ",";
1786 		}
1787 		if ((i->tflags & IPFW_TFFLAG_DSTIP) != 0) {
1788 			if (tfe->af == AF_INET)
1789 				paddr = &tfe->a.a4.dip;
1790 			else
1791 				paddr = &tfe->a.a6.dip6;
1792 
1793 			inet_ntop(tfe->af, paddr, tbuf, sizeof(tbuf));
1794 			printf("%s%s", comma, tbuf);
1795 			comma = ",";
1796 		}
1797 
1798 		if ((i->tflags & IPFW_TFFLAG_DSTPORT) != 0) {
1799 			printf("%s%d", comma, ntohs(tfe->dport));
1800 			comma = ",";
1801 		}
1802 
1803 		printf(" %s\n", pval);
1804 	}
1805 }
1806 
1807 static int
1808 table_do_get_stdlist(uint16_t opcode, ipfw_obj_lheader **polh)
1809 {
1810 	ipfw_obj_lheader req, *olh;
1811 	size_t sz;
1812 
1813 	memset(&req, 0, sizeof(req));
1814 	sz = sizeof(req);
1815 
1816 	if (do_get3(opcode, &req.opheader, &sz) != 0)
1817 		if (errno != ENOMEM)
1818 			return (errno);
1819 
1820 	sz = req.size;
1821 	if ((olh = calloc(1, sz)) == NULL)
1822 		return (ENOMEM);
1823 
1824 	olh->size = sz;
1825 	if (do_get3(opcode, &olh->opheader, &sz) != 0) {
1826 		free(olh);
1827 		return (errno);
1828 	}
1829 
1830 	*polh = olh;
1831 	return (0);
1832 }
1833 
1834 static int
1835 table_do_get_algolist(ipfw_obj_lheader **polh)
1836 {
1837 
1838 	return (table_do_get_stdlist(IP_FW_TABLES_ALIST, polh));
1839 }
1840 
1841 static int
1842 table_do_get_vlist(ipfw_obj_lheader **polh)
1843 {
1844 
1845 	return (table_do_get_stdlist(IP_FW_TABLE_VLIST, polh));
1846 }
1847 
1848 void
1849 ipfw_list_ta(int ac, char *av[])
1850 {
1851 	ipfw_obj_lheader *olh;
1852 	ipfw_ta_info *info;
1853 	int error, i;
1854 	const char *atype;
1855 
1856 	error = table_do_get_algolist(&olh);
1857 	if (error != 0)
1858 		err(EX_OSERR, "Unable to request algorithm list");
1859 
1860 	info = (ipfw_ta_info *)(olh + 1);
1861 	for (i = 0; i < olh->count; i++) {
1862 		if ((atype = match_value(tabletypes, info->type)) == NULL)
1863 			atype = "unknown";
1864 		printf("--- %s ---\n", info->algoname);
1865 		printf(" type: %s\n refcount: %u\n", atype, info->refcnt);
1866 
1867 		info = (ipfw_ta_info *)((caddr_t)info + olh->objsize);
1868 	}
1869 
1870 	free(olh);
1871 }
1872 
1873 
1874 /* Copy of current kernel table_value structure */
1875 struct _table_value {
1876 	uint32_t	tag;		/* O_TAG/O_TAGGED */
1877 	uint32_t	pipe;		/* O_PIPE/O_QUEUE */
1878 	uint16_t	divert;		/* O_DIVERT/O_TEE */
1879 	uint16_t	skipto;		/* skipto, CALLRET */
1880 	uint32_t	netgraph;	/* O_NETGRAPH/O_NGTEE */
1881 	uint32_t	fib;		/* O_SETFIB */
1882 	uint32_t	nat;		/* O_NAT */
1883 	uint32_t	nh4;
1884 	uint8_t		dscp;
1885 	uint8_t		spare0;
1886 	uint16_t	spare1;
1887 	/* -- 32 bytes -- */
1888 	struct in6_addr	nh6;
1889 	uint32_t	limit;		/* O_LIMIT */
1890 	uint32_t	zoneid;
1891 	uint64_t	refcnt;		/* Number of references */
1892 };
1893 
1894 int
1895 compare_values(const void *_a, const void *_b)
1896 {
1897 	struct _table_value *a, *b;
1898 
1899 	a = (struct _table_value *)_a;
1900 	b = (struct _table_value *)_b;
1901 
1902 	if (a->spare1 < b->spare1)
1903 		return (-1);
1904 	else if (a->spare1 > b->spare1)
1905 		return (1);
1906 
1907 	return (0);
1908 }
1909 
1910 void
1911 ipfw_list_values(int ac, char *av[])
1912 {
1913 	ipfw_obj_lheader *olh;
1914 	struct _table_value *v;
1915 	int error, i;
1916 	uint32_t vmask;
1917 	char buf[128];
1918 
1919 	error = table_do_get_vlist(&olh);
1920 	if (error != 0)
1921 		err(EX_OSERR, "Unable to request value list");
1922 
1923 	vmask = 0x7FFFFFFF; /* Similar to IPFW_VTYPE_LEGACY */
1924 
1925 	table_print_valheader(buf, sizeof(buf), vmask);
1926 	printf("HEADER: %s\n", buf);
1927 	v = (struct _table_value *)(olh + 1);
1928 	qsort(v, olh->count, olh->objsize, compare_values);
1929 	for (i = 0; i < olh->count; i++) {
1930 		table_show_value(buf, sizeof(buf), (ipfw_table_value *)v,
1931 		    vmask, 0);
1932 		printf("[%u] refs=%lu %s\n", v->spare1, (u_long)v->refcnt, buf);
1933 		v = (struct _table_value *)((caddr_t)v + olh->objsize);
1934 	}
1935 
1936 	free(olh);
1937 }
1938 
1939 int
1940 compare_ntlv(const void *_a, const void *_b)
1941 {
1942 	ipfw_obj_ntlv *a, *b;
1943 
1944 	a = (ipfw_obj_ntlv *)_a;
1945 	b = (ipfw_obj_ntlv *)_b;
1946 
1947 	if (a->set < b->set)
1948 		return (-1);
1949 	else if (a->set > b->set)
1950 		return (1);
1951 
1952 	if (a->idx < b->idx)
1953 		return (-1);
1954 	else if (a->idx > b->idx)
1955 		return (1);
1956 
1957 	return (0);
1958 }
1959 
1960 int
1961 compare_kntlv(const void *k, const void *v)
1962 {
1963 	ipfw_obj_ntlv *ntlv;
1964 	uint16_t key;
1965 
1966 	key = *((uint16_t *)k);
1967 	ntlv = (ipfw_obj_ntlv *)v;
1968 
1969 	if (key < ntlv->idx)
1970 		return (-1);
1971 	else if (key > ntlv->idx)
1972 		return (1);
1973 
1974 	return (0);
1975 }
1976 
1977 /*
1978  * Finds table name in @ctlv by @idx.
1979  * Uses the following facts:
1980  * 1) All TLVs are the same size
1981  * 2) Kernel implementation provides already sorted list.
1982  *
1983  * Returns table name or NULL.
1984  */
1985 char *
1986 table_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx)
1987 {
1988 	ipfw_obj_ntlv *ntlv;
1989 
1990 	ntlv = bsearch(&idx, (ctlv + 1), ctlv->count, ctlv->objsize,
1991 	    compare_kntlv);
1992 
1993 	if (ntlv != 0)
1994 		return (ntlv->name);
1995 
1996 	return (NULL);
1997 }
1998 
1999 void
2000 table_sort_ctlv(ipfw_obj_ctlv *ctlv)
2001 {
2002 
2003 	qsort(ctlv + 1, ctlv->count, ctlv->objsize, compare_ntlv);
2004 }
2005 
2006 int
2007 table_check_name(char *tablename)
2008 {
2009 	int c, i, l;
2010 
2011 	/*
2012 	 * Check if tablename is null-terminated and contains
2013 	 * valid symbols only. Valid mask is:
2014 	 * [a-zA-Z0-9\-_\.]{1,63}
2015 	 */
2016 	l = strlen(tablename);
2017 	if (l == 0 || l >= 64)
2018 		return (EINVAL);
2019 	for (i = 0; i < l; i++) {
2020 		c = tablename[i];
2021 		if (isalpha(c) || isdigit(c) || c == '_' ||
2022 		    c == '-' || c == '.')
2023 			continue;
2024 		return (EINVAL);
2025 	}
2026 
2027 	/* Restrict some 'special' names */
2028 	if (strcmp(tablename, "all") == 0)
2029 		return (EINVAL);
2030 
2031 	return (0);
2032 }
2033 
2034