xref: /freebsd/sbin/ipfw/tables.c (revision b00fe64f4acfe315181f65999af16e9a7bdc600b)
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 	memset(buf, 0, bufsize);
719 	print_flags_buffer(buf, bufsize, tablevaltypes, vmask);
720 }
721 
722 /*
723  * Prints table info struct @i in human-readable form.
724  */
725 static int
726 table_show_info(ipfw_xtable_info *i, void *arg)
727 {
728 	const char *vtype;
729 	ipfw_ta_tinfo *tainfo;
730 	int afdata, afitem;
731 	struct ta_cldata d;
732 	char ttype[64], tvtype[64];
733 
734 	table_print_type(ttype, sizeof(ttype), i->type, i->tflags);
735 	table_print_valheader(tvtype, sizeof(tvtype), i->vmask);
736 
737 	printf("--- table(%s), set(%u) ---\n", i->tablename, i->set);
738 	if ((i->flags & IPFW_TGFLAGS_LOCKED) != 0)
739 		printf(" kindex: %d, type: %s, locked\n", i->kidx, ttype);
740 	else
741 		printf(" kindex: %d, type: %s\n", i->kidx, ttype);
742 	printf(" references: %u, valtype: %s\n", i->refcnt, tvtype);
743 	printf(" algorithm: %s\n", i->algoname);
744 	printf(" items: %u, size: %u\n", i->count, i->size);
745 	if (i->limit > 0)
746 		printf(" limit: %u\n", i->limit);
747 
748 	/* Print algo-specific info if requested & set  */
749 	if (arg == NULL)
750 		return (0);
751 
752 	if ((i->ta_info.flags & IPFW_TATFLAGS_DATA) == 0)
753 		return (0);
754 	tainfo = &i->ta_info;
755 
756 	afdata = 0;
757 	afitem = 0;
758 	if (tainfo->flags & IPFW_TATFLAGS_AFDATA)
759 		afdata = 1;
760 	if (tainfo->flags & IPFW_TATFLAGS_AFITEM)
761 		afitem = 1;
762 
763 	memset(&d, 0, sizeof(d));
764 	d.taclass = tainfo->taclass4;
765 	d.size = tainfo->size4;
766 	d.count = tainfo->count4;
767 	d.itemsize = tainfo->itemsize4;
768 	if (afdata == 0 && afitem != 0)
769 		d.itemsize6 = tainfo->itemsize6;
770 	else
771 		d.itemsize6 = d.itemsize;
772 	if ((vtype = match_value(tablealgoclass, d.taclass)) == NULL)
773 		vtype = "unknown";
774 
775 	if (afdata == 0) {
776 		table_show_tainfo(i, &d, "", vtype);
777 	} else {
778 		table_show_tainfo(i, &d, "IPv4 ", vtype);
779 		memset(&d, 0, sizeof(d));
780 		d.taclass = tainfo->taclass6;
781 		if ((vtype = match_value(tablealgoclass, d.taclass)) == NULL)
782 			vtype = "unknown";
783 		d.size = tainfo->size6;
784 		d.count = tainfo->count6;
785 		d.itemsize = tainfo->itemsize6;
786 		d.itemsize6 = d.itemsize;
787 		table_show_tainfo(i, &d, "IPv6 ", vtype);
788 	}
789 
790 	return (0);
791 }
792 
793 
794 /*
795  * Function wrappers which can be used either
796  * as is or as foreach function parameter.
797  */
798 
799 static int
800 table_show_one(ipfw_xtable_info *i, void *arg)
801 {
802 	ipfw_obj_header *oh;
803 	int error;
804 
805 	if ((error = table_do_get_list(i, &oh)) != 0) {
806 		err(EX_OSERR, "Error requesting table %s list", i->tablename);
807 		return (error);
808 	}
809 
810 	table_show_list(oh, 1);
811 
812 	free(oh);
813 	return (0);
814 }
815 
816 static int
817 table_flush_one(ipfw_xtable_info *i, void *arg)
818 {
819 	ipfw_obj_header *oh;
820 
821 	oh = (ipfw_obj_header *)arg;
822 
823 	table_fill_ntlv(&oh->ntlv, i->tablename, i->set, 1);
824 
825 	return (table_flush(oh));
826 }
827 
828 static int
829 table_do_modify_record(int cmd, ipfw_obj_header *oh,
830     ipfw_obj_tentry *tent, int count, int atomic)
831 {
832 	ipfw_obj_ctlv *ctlv;
833 	ipfw_obj_tentry *tent_base;
834 	caddr_t pbuf;
835 	char xbuf[sizeof(*oh) + sizeof(ipfw_obj_ctlv) + sizeof(*tent)];
836 	int error, i;
837 	size_t sz;
838 
839 	sz = sizeof(*ctlv) + sizeof(*tent) * count;
840 	if (count == 1) {
841 		memset(xbuf, 0, sizeof(xbuf));
842 		pbuf = xbuf;
843 	} else {
844 		if ((pbuf = calloc(1, sizeof(*oh) + sz)) == NULL)
845 			return (ENOMEM);
846 	}
847 
848 	memcpy(pbuf, oh, sizeof(*oh));
849 	oh = (ipfw_obj_header *)pbuf;
850 	oh->opheader.version = 1;
851 
852 	ctlv = (ipfw_obj_ctlv *)(oh + 1);
853 	ctlv->count = count;
854 	ctlv->head.length = sz;
855 	if (atomic != 0)
856 		ctlv->flags |= IPFW_CTF_ATOMIC;
857 
858 	tent_base = tent;
859 	memcpy(ctlv + 1, tent, sizeof(*tent) * count);
860 	tent = (ipfw_obj_tentry *)(ctlv + 1);
861 	for (i = 0; i < count; i++, tent++) {
862 		tent->head.length = sizeof(ipfw_obj_tentry);
863 		tent->idx = oh->idx;
864 	}
865 
866 	sz += sizeof(*oh);
867 	error = do_get3(cmd, &oh->opheader, &sz);
868 	tent = (ipfw_obj_tentry *)(ctlv + 1);
869 	/* Copy result back to provided buffer */
870 	memcpy(tent_base, ctlv + 1, sizeof(*tent) * count);
871 
872 	if (pbuf != xbuf)
873 		free(pbuf);
874 
875 	return (error);
876 }
877 
878 static void
879 table_modify_record(ipfw_obj_header *oh, int ac, char *av[], int add,
880     int quiet, int update, int atomic)
881 {
882 	ipfw_obj_tentry *ptent, tent, *tent_buf;
883 	ipfw_xtable_info xi;
884 	uint8_t type;
885 	uint32_t vmask;
886 	int cmd, count, error, i, ignored;
887 	char *texterr, *etxt, *px;
888 
889 	if (ac == 0)
890 		errx(EX_USAGE, "address required");
891 
892 	if (add != 0) {
893 		cmd = IP_FW_TABLE_XADD;
894 		texterr = "Adding record failed";
895 	} else {
896 		cmd = IP_FW_TABLE_XDEL;
897 		texterr = "Deleting record failed";
898 	}
899 
900 	/*
901 	 * Calculate number of entries:
902 	 * Assume [key val] x N for add
903 	 * and
904 	 * key x N for delete
905 	 */
906 	count = (add != 0) ? ac / 2 + 1 : ac;
907 
908 	if (count <= 1) {
909 		/* Adding single entry with/without value */
910 		memset(&tent, 0, sizeof(tent));
911 		tent_buf = &tent;
912 	} else {
913 
914 		if ((tent_buf = calloc(count, sizeof(tent))) == NULL)
915 			errx(EX_OSERR,
916 			    "Unable to allocate memory for all entries");
917 	}
918 	ptent = tent_buf;
919 
920 	memset(&xi, 0, sizeof(xi));
921 	count = 0;
922 	while (ac > 0) {
923 		tentry_fill_key(oh, ptent, *av, add, &type, &vmask, &xi);
924 
925 		/*
926 		 * compability layer: auto-create table if not exists
927 		 */
928 		if (xi.tablename[0] == '\0') {
929 			xi.type = type;
930 			xi.vmask = vmask;
931 			strlcpy(xi.tablename, oh->ntlv.name,
932 			    sizeof(xi.tablename));
933 			fprintf(stderr, "DEPRECATED: inserting data info "
934 			    "non-existent table %s. (auto-created)\n",
935 			    xi.tablename);
936 			table_do_create(oh, &xi);
937 		}
938 
939 		oh->ntlv.type = type;
940 		ac--; av++;
941 
942 		if (add != 0 && ac > 0) {
943 			tentry_fill_value(oh, ptent, *av, type, vmask);
944 			ac--; av++;
945 		}
946 
947 		if (update != 0)
948 			ptent->head.flags |= IPFW_TF_UPDATE;
949 
950 		count++;
951 		ptent++;
952 	}
953 
954 	error = table_do_modify_record(cmd, oh, tent_buf, count, atomic);
955 
956 	quiet = 0;
957 
958 	/*
959 	 * Compatibility stuff: do not yell on duplicate keys or
960 	 * failed deletions.
961 	 */
962 	if (error == 0 || (error == EEXIST && add != 0) ||
963 	    (error == ENOENT && add == 0)) {
964 		if (quiet != 0) {
965 			if (tent_buf != &tent)
966 				free(tent_buf);
967 			return;
968 		}
969 	}
970 
971 	/* Report results back */
972 	ptent = tent_buf;
973 	for (i = 0; i < count; ptent++, i++) {
974 		ignored = 0;
975 		switch (ptent->result) {
976 		case IPFW_TR_ADDED:
977 			px = "added";
978 			break;
979 		case IPFW_TR_DELETED:
980 			px = "deleted";
981 			break;
982 		case IPFW_TR_UPDATED:
983 			px = "updated";
984 			break;
985 		case IPFW_TR_LIMIT:
986 			px = "limit";
987 			ignored = 1;
988 			break;
989 		case IPFW_TR_ERROR:
990 			px = "error";
991 			ignored = 1;
992 			break;
993 		case IPFW_TR_NOTFOUND:
994 			px = "notfound";
995 			ignored = 1;
996 			break;
997 		case IPFW_TR_EXISTS:
998 			px = "exists";
999 			ignored = 1;
1000 			break;
1001 		case IPFW_TR_IGNORED:
1002 			px = "ignored";
1003 			ignored = 1;
1004 			break;
1005 		default:
1006 			px = "unknown";
1007 			ignored = 1;
1008 		}
1009 
1010 		if (error != 0 && atomic != 0 && ignored == 0)
1011 			printf("%s(reverted): ", px);
1012 		else
1013 			printf("%s: ", px);
1014 
1015 		table_show_entry(&xi, ptent);
1016 	}
1017 
1018 	if (tent_buf != &tent)
1019 		free(tent_buf);
1020 
1021 	if (error == 0)
1022 		return;
1023 	/* Get real OS error */
1024 	error = errno;
1025 
1026 	/* Try to provide more human-readable error */
1027 	switch (error) {
1028 	case EEXIST:
1029 		etxt = "record already exists";
1030 		break;
1031 	case EFBIG:
1032 		etxt = "limit hit";
1033 		break;
1034 	case ESRCH:
1035 		etxt = "table not found";
1036 		break;
1037 	case ENOENT:
1038 		etxt = "record not found";
1039 		break;
1040 	case EACCES:
1041 		etxt = "table is locked";
1042 		break;
1043 	default:
1044 		etxt = strerror(error);
1045 	}
1046 
1047 	errx(EX_OSERR, "%s: %s", texterr, etxt);
1048 }
1049 
1050 static int
1051 table_do_lookup(ipfw_obj_header *oh, char *key, ipfw_xtable_info *xi,
1052     ipfw_obj_tentry *xtent)
1053 {
1054 	char xbuf[sizeof(ipfw_obj_header) + sizeof(ipfw_obj_tentry)];
1055 	ipfw_obj_tentry *tent;
1056 	uint8_t type;
1057 	uint32_t vmask;
1058 	size_t sz;
1059 
1060 	memcpy(xbuf, oh, sizeof(*oh));
1061 	oh = (ipfw_obj_header *)xbuf;
1062 	tent = (ipfw_obj_tentry *)(oh + 1);
1063 
1064 	memset(tent, 0, sizeof(*tent));
1065 	tent->head.length = sizeof(*tent);
1066 	tent->idx = 1;
1067 
1068 	tentry_fill_key(oh, tent, key, 0, &type, &vmask, xi);
1069 	oh->ntlv.type = type;
1070 
1071 	sz = sizeof(xbuf);
1072 	if (do_get3(IP_FW_TABLE_XFIND, &oh->opheader, &sz) != 0)
1073 		return (errno);
1074 
1075 	if (sz < sizeof(xbuf))
1076 		return (EINVAL);
1077 
1078 	*xtent = *tent;
1079 
1080 	return (0);
1081 }
1082 
1083 static void
1084 table_lookup(ipfw_obj_header *oh, int ac, char *av[])
1085 {
1086 	ipfw_obj_tentry xtent;
1087 	ipfw_xtable_info xi;
1088 	char key[64];
1089 	int error;
1090 
1091 	if (ac == 0)
1092 		errx(EX_USAGE, "address required");
1093 
1094 	strlcpy(key, *av, sizeof(key));
1095 
1096 	memset(&xi, 0, sizeof(xi));
1097 	error = table_do_lookup(oh, key, &xi, &xtent);
1098 
1099 	switch (error) {
1100 	case 0:
1101 		break;
1102 	case ESRCH:
1103 		errx(EX_UNAVAILABLE, "Table %s not found", oh->ntlv.name);
1104 	case ENOENT:
1105 		errx(EX_UNAVAILABLE, "Entry %s not found", *av);
1106 	case ENOTSUP:
1107 		errx(EX_UNAVAILABLE, "Table %s algo does not support "
1108 		    "\"lookup\" method", oh->ntlv.name);
1109 	default:
1110 		err(EX_OSERR, "getsockopt(IP_FW_TABLE_XFIND)");
1111 	}
1112 
1113 	table_show_entry(&xi, &xtent);
1114 }
1115 
1116 static void
1117 tentry_fill_key_type(char *arg, ipfw_obj_tentry *tentry, uint8_t type,
1118     uint8_t tflags)
1119 {
1120 	char *p, *pp;
1121 	int mask, af;
1122 	struct in6_addr *paddr, tmp;
1123 	struct tflow_entry *tfe;
1124 	uint32_t key, *pkey;
1125 	uint16_t port;
1126 	struct protoent *pent;
1127 	struct servent *sent;
1128 	int masklen;
1129 
1130 	masklen = 0;
1131 	af = 0;
1132 	paddr = (struct in6_addr *)&tentry->k;
1133 
1134 	switch (type) {
1135 	case IPFW_TABLE_ADDR:
1136 		/* Remove / if exists */
1137 		if ((p = strchr(arg, '/')) != NULL) {
1138 			*p = '\0';
1139 			mask = atoi(p + 1);
1140 		}
1141 
1142 		if (inet_pton(AF_INET, arg, paddr) == 1) {
1143 			if (p != NULL && mask > 32)
1144 				errx(EX_DATAERR, "bad IPv4 mask width: %s",
1145 				    p + 1);
1146 
1147 			masklen = p ? mask : 32;
1148 			af = AF_INET;
1149 		} else if (inet_pton(AF_INET6, arg, paddr) == 1) {
1150 			if (IN6_IS_ADDR_V4COMPAT(paddr))
1151 				errx(EX_DATAERR,
1152 				    "Use IPv4 instead of v4-compatible");
1153 			if (p != NULL && mask > 128)
1154 				errx(EX_DATAERR, "bad IPv6 mask width: %s",
1155 				    p + 1);
1156 
1157 			masklen = p ? mask : 128;
1158 			af = AF_INET6;
1159 		} else {
1160 			/* Assume FQDN */
1161 			if (lookup_host(arg, (struct in_addr *)paddr) != 0)
1162 				errx(EX_NOHOST, "hostname ``%s'' unknown", arg);
1163 
1164 			masklen = 32;
1165 			type = IPFW_TABLE_ADDR;
1166 			af = AF_INET;
1167 		}
1168 		break;
1169 	case IPFW_TABLE_INTERFACE:
1170 		/* Assume interface name. Copy significant data only */
1171 		mask = MIN(strlen(arg), IF_NAMESIZE - 1);
1172 		memcpy(paddr, arg, mask);
1173 		/* Set mask to exact match */
1174 		masklen = 8 * IF_NAMESIZE;
1175 		break;
1176 	case IPFW_TABLE_NUMBER:
1177 		/* Port or any other key */
1178 		key = strtol(arg, &p, 10);
1179 		if (*p != '\0')
1180 			errx(EX_DATAERR, "Invalid number: %s", arg);
1181 
1182 		pkey = (uint32_t *)paddr;
1183 		*pkey = key;
1184 		masklen = 32;
1185 		break;
1186 	case IPFW_TABLE_FLOW:
1187 		/* Assume [src-ip][,proto][,src-port][,dst-ip][,dst-port] */
1188 		tfe = &tentry->k.flow;
1189 		af = 0;
1190 
1191 		/* Handle <ipv4|ipv6> */
1192 		if ((tflags & IPFW_TFFLAG_SRCIP) != 0) {
1193 			if ((p = strchr(arg, ',')) != NULL)
1194 				*p++ = '\0';
1195 			/* Determine family using temporary storage */
1196 			if (inet_pton(AF_INET, arg, &tmp) == 1) {
1197 				if (af != 0 && af != AF_INET)
1198 					errx(EX_DATAERR,
1199 					    "Inconsistent address family\n");
1200 				af = AF_INET;
1201 				memcpy(&tfe->a.a4.sip, &tmp, 4);
1202 			} else if (inet_pton(AF_INET6, arg, &tmp) == 1) {
1203 				if (af != 0 && af != AF_INET6)
1204 					errx(EX_DATAERR,
1205 					    "Inconsistent address family\n");
1206 				af = AF_INET6;
1207 				memcpy(&tfe->a.a6.sip6, &tmp, 16);
1208 			}
1209 
1210 			arg = p;
1211 		}
1212 
1213 		/* Handle <proto-num|proto-name> */
1214 		if ((tflags & IPFW_TFFLAG_PROTO) != 0) {
1215 			if (arg == NULL)
1216 				errx(EX_DATAERR, "invalid key: proto missing");
1217 			if ((p = strchr(arg, ',')) != NULL)
1218 				*p++ = '\0';
1219 
1220 			key = strtol(arg, &pp, 10);
1221 			if (*pp != '\0') {
1222 				if ((pent = getprotobyname(arg)) == NULL)
1223 					errx(EX_DATAERR, "Unknown proto: %s",
1224 					    arg);
1225 				else
1226 					key = pent->p_proto;
1227 			}
1228 
1229 			if (key > 255)
1230 				errx(EX_DATAERR, "Bad protocol number: %u",key);
1231 
1232 			tfe->proto = key;
1233 
1234 			arg = p;
1235 		}
1236 
1237 		/* Handle <port-num|service-name> */
1238 		if ((tflags & IPFW_TFFLAG_SRCPORT) != 0) {
1239 			if (arg == NULL)
1240 				errx(EX_DATAERR, "invalid key: src port missing");
1241 			if ((p = strchr(arg, ',')) != NULL)
1242 				*p++ = '\0';
1243 
1244 			if ((port = htons(strtol(arg, NULL, 10))) == 0) {
1245 				if ((sent = getservbyname(arg, NULL)) == NULL)
1246 					errx(EX_DATAERR, "Unknown service: %s",
1247 					    arg);
1248 				else
1249 					key = sent->s_port;
1250 			}
1251 
1252 			tfe->sport = port;
1253 
1254 			arg = p;
1255 		}
1256 
1257 		/* Handle <ipv4|ipv6>*/
1258 		if ((tflags & IPFW_TFFLAG_DSTIP) != 0) {
1259 			if (arg == NULL)
1260 				errx(EX_DATAERR, "invalid key: dst ip missing");
1261 			if ((p = strchr(arg, ',')) != NULL)
1262 				*p++ = '\0';
1263 			/* Determine family using temporary storage */
1264 			if (inet_pton(AF_INET, arg, &tmp) == 1) {
1265 				if (af != 0 && af != AF_INET)
1266 					errx(EX_DATAERR,
1267 					    "Inconsistent address family");
1268 				af = AF_INET;
1269 				memcpy(&tfe->a.a4.dip, &tmp, 4);
1270 			} else if (inet_pton(AF_INET6, arg, &tmp) == 1) {
1271 				if (af != 0 && af != AF_INET6)
1272 					errx(EX_DATAERR,
1273 					    "Inconsistent address family");
1274 				af = AF_INET6;
1275 				memcpy(&tfe->a.a6.dip6, &tmp, 16);
1276 			}
1277 
1278 			arg = p;
1279 		}
1280 
1281 		/* Handle <port-num|service-name> */
1282 		if ((tflags & IPFW_TFFLAG_DSTPORT) != 0) {
1283 			if (arg == NULL)
1284 				errx(EX_DATAERR, "invalid key: dst port missing");
1285 			if ((p = strchr(arg, ',')) != NULL)
1286 				*p++ = '\0';
1287 
1288 			if ((port = htons(strtol(arg, NULL, 10))) == 0) {
1289 				if ((sent = getservbyname(arg, NULL)) == NULL)
1290 					errx(EX_DATAERR, "Unknown service: %s",
1291 					    arg);
1292 				else
1293 					key = sent->s_port;
1294 			}
1295 
1296 			tfe->dport = port;
1297 
1298 			arg = p;
1299 		}
1300 
1301 		tfe->af = af;
1302 
1303 		break;
1304 
1305 	default:
1306 		errx(EX_DATAERR, "Unsupported table type: %d", type);
1307 	}
1308 
1309 	tentry->subtype = af;
1310 	tentry->masklen = masklen;
1311 }
1312 
1313 static void
1314 tentry_fill_key(ipfw_obj_header *oh, ipfw_obj_tentry *tent, char *key,
1315     int add, uint8_t *ptype, uint32_t *pvmask, ipfw_xtable_info *xi)
1316 {
1317 	uint8_t type, tflags;
1318 	uint32_t vmask;
1319 	int error;
1320 	char *del;
1321 
1322 	type = 0;
1323 	tflags = 0;
1324 	vmask = 0;
1325 
1326 	if (xi->tablename[0] == '\0')
1327 		error = table_get_info(oh, xi);
1328 	else
1329 		error = 0;
1330 
1331 	if (error == 0) {
1332 		/* Table found. */
1333 		type = xi->type;
1334 		tflags = xi->tflags;
1335 		vmask = xi->vmask;
1336 	} else {
1337 		if (error != ESRCH)
1338 			errx(EX_OSERR, "Error requesting table %s info",
1339 			    oh->ntlv.name);
1340 		if (add == 0)
1341 			errx(EX_DATAERR, "Table %s does not exist",
1342 			    oh->ntlv.name);
1343 		/*
1344 		 * Table does not exist.
1345 		 * Compability layer: try to interpret data as ADDR
1346 		 * before failing.
1347 		 */
1348 		if ((del = strchr(key, '/')) != NULL)
1349 			*del = '\0';
1350 		if (inet_pton(AF_INET, key, &tent->k.addr6) == 1 ||
1351 		    inet_pton(AF_INET6, key, &tent->k.addr6) == 1) {
1352 			/* OK Prepare and send */
1353 			type = IPFW_TABLE_ADDR;
1354 			vmask = IPFW_VTYPE_LEGACY;
1355 		} else {
1356 			/* Inknown key */
1357 			errx(EX_USAGE, "Table %s does not exist, cannot guess "
1358 			    "key '%s' type", oh->ntlv.name, key);
1359 		}
1360 		if (del != NULL)
1361 			*del = '/';
1362 	}
1363 
1364 	tentry_fill_key_type(key, tent, type, tflags);
1365 
1366 	*ptype = type;
1367 	*pvmask = vmask;
1368 }
1369 
1370 static void
1371 set_legacy_value(uint32_t val, ipfw_table_value *v)
1372 {
1373 	v->tag = val;
1374 	v->pipe = val;
1375 	v->divert = val;
1376 	v->skipto = val;
1377 	v->netgraph = val;
1378 	v->fib = val;
1379 	v->nat = val;
1380 	v->nh4 = val;
1381 	v->dscp = (uint8_t)val;
1382 	v->limit = val;
1383 }
1384 
1385 static void
1386 tentry_fill_value(ipfw_obj_header *oh, ipfw_obj_tentry *tent, char *arg,
1387     uint8_t type, uint32_t vmask)
1388 {
1389 	struct addrinfo hints, *res;
1390 	uint32_t a4, flag, val, vm;
1391 	ipfw_table_value *v;
1392 	uint32_t i;
1393 	int dval;
1394 	char *comma, *e, *etype, *n, *p;
1395 
1396 	v = &tent->v.value;
1397 	vm = vmask;
1398 
1399 	/* Compat layer: keep old behavior for legacy value types */
1400 	if (vmask == IPFW_VTYPE_LEGACY) {
1401 		/* Try to interpret as number first */
1402 		val = strtoul(arg, &p, 0);
1403 		if (*p == '\0') {
1404 			set_legacy_value(val, v);
1405 			return;
1406 		}
1407 		if (inet_pton(AF_INET, arg, &val) == 1) {
1408 			set_legacy_value(ntohl(val), v);
1409 			return;
1410 		}
1411 		/* Try hostname */
1412 		if (lookup_host(arg, (struct in_addr *)&val) == 0) {
1413 			set_legacy_value(val, v);
1414 			return;
1415 		}
1416 		errx(EX_OSERR, "Unable to parse value %s", arg);
1417 	}
1418 
1419 	/*
1420 	 * Shorthands: handle single value if vmask consists
1421 	 * of numbers only. e.g.:
1422 	 * vmask = "fib,skipto" -> treat input "1" as "1,1"
1423 	 */
1424 
1425 	n = arg;
1426 	etype = NULL;
1427 	for (i = 1; i < (1 << 31); i *= 2) {
1428 		if ((flag = (vmask & i)) == 0)
1429 			continue;
1430 		vmask &= ~flag;
1431 
1432 		if ((comma = strchr(n, ',')) != NULL)
1433 			*comma = '\0';
1434 
1435 		switch (flag) {
1436 		case IPFW_VTYPE_TAG:
1437 			v->tag = strtol(n, &e, 10);
1438 			if (*e != '\0')
1439 				etype = "tag";
1440 			break;
1441 		case IPFW_VTYPE_PIPE:
1442 			v->pipe = strtol(n, &e, 10);
1443 			if (*e != '\0')
1444 				etype = "pipe";
1445 			break;
1446 		case IPFW_VTYPE_DIVERT:
1447 			v->divert = strtol(n, &e, 10);
1448 			if (*e != '\0')
1449 				etype = "divert";
1450 			break;
1451 		case IPFW_VTYPE_SKIPTO:
1452 			v->skipto = strtol(n, &e, 10);
1453 			if (*e != '\0')
1454 				etype = "skipto";
1455 			break;
1456 		case IPFW_VTYPE_NETGRAPH:
1457 			v->netgraph = strtol(n, &e, 10);
1458 			if (*e != '\0')
1459 				etype = "netgraph";
1460 			break;
1461 		case IPFW_VTYPE_FIB:
1462 			v->fib = strtol(n, &e, 10);
1463 			if (*e != '\0')
1464 				etype = "fib";
1465 			break;
1466 		case IPFW_VTYPE_NAT:
1467 			v->nat = strtol(n, &e, 10);
1468 			if (*e != '\0')
1469 				etype = "nat";
1470 			break;
1471 		case IPFW_VTYPE_LIMIT:
1472 			v->limit = strtol(n, &e, 10);
1473 			if (*e != '\0')
1474 				etype = "limit";
1475 			break;
1476 		case IPFW_VTYPE_NH4:
1477 			if (strchr(n, '.') != NULL &&
1478 			    inet_pton(AF_INET, n, &a4) == 1) {
1479 				v->nh4 = ntohl(a4);
1480 				break;
1481 			}
1482 			if (lookup_host(n, (struct in_addr *)&v->nh4) == 0)
1483 				break;
1484 			etype = "ipv4";
1485 			break;
1486 		case IPFW_VTYPE_DSCP:
1487 			if (isalpha(*n)) {
1488 				if ((dval = match_token(f_ipdscp, n)) != -1) {
1489 					v->dscp = dval;
1490 					break;
1491 				} else
1492 					etype = "DSCP code";
1493 			} else {
1494 				v->dscp = strtol(n, &e, 10);
1495 				if (v->dscp > 63 || *e != '\0')
1496 					etype = "DSCP value";
1497 			}
1498 			break;
1499 		case IPFW_VTYPE_NH6:
1500 			if (strchr(n, ':') != NULL) {
1501 				memset(&hints, 0, sizeof(hints));
1502 				hints.ai_family = AF_INET6;
1503 				hints.ai_flags = AI_NUMERICHOST;
1504 				if (getaddrinfo(n, NULL, &hints, &res) == 0) {
1505 					v->nh6 = ((struct sockaddr_in6 *)
1506 					    res->ai_addr)->sin6_addr;
1507 					v->zoneid = ((struct sockaddr_in6 *)
1508 					    res->ai_addr)->sin6_scope_id;
1509 					freeaddrinfo(res);
1510 					break;
1511 				}
1512 			}
1513 			etype = "ipv6";
1514 			break;
1515 		}
1516 
1517 		if (etype != NULL)
1518 			errx(EX_USAGE, "Unable to parse %s as %s", n, etype);
1519 
1520 		if (comma != NULL)
1521 			*comma++ = ',';
1522 
1523 		if ((n = comma) != NULL)
1524 			continue;
1525 
1526 		/* End of input. */
1527 		if (vmask != 0)
1528 			errx(EX_USAGE, "Not enough fields inside value");
1529 	}
1530 }
1531 
1532 /*
1533  * Compare table names.
1534  * Honor number comparison.
1535  */
1536 static int
1537 tablename_cmp(const void *a, const void *b)
1538 {
1539 	ipfw_xtable_info *ia, *ib;
1540 
1541 	ia = (ipfw_xtable_info *)a;
1542 	ib = (ipfw_xtable_info *)b;
1543 
1544 	return (stringnum_cmp(ia->tablename, ib->tablename));
1545 }
1546 
1547 /*
1548  * Retrieves table list from kernel,
1549  * optionally sorts it and calls requested function for each table.
1550  * Returns 0 on success.
1551  */
1552 static int
1553 tables_foreach(table_cb_t *f, void *arg, int sort)
1554 {
1555 	ipfw_obj_lheader *olh;
1556 	ipfw_xtable_info *info;
1557 	size_t sz;
1558 	int i, error;
1559 
1560 	/* Start with reasonable default */
1561 	sz = sizeof(*olh) + 16 * sizeof(ipfw_xtable_info);
1562 
1563 	for (;;) {
1564 		if ((olh = calloc(1, sz)) == NULL)
1565 			return (ENOMEM);
1566 
1567 		olh->size = sz;
1568 		if (do_get3(IP_FW_TABLES_XLIST, &olh->opheader, &sz) != 0) {
1569 			sz = olh->size;
1570 			free(olh);
1571 			if (errno != ENOMEM)
1572 				return (errno);
1573 			continue;
1574 		}
1575 
1576 		if (sort != 0)
1577 			qsort(olh + 1, olh->count, olh->objsize, tablename_cmp);
1578 
1579 		info = (ipfw_xtable_info *)(olh + 1);
1580 		for (i = 0; i < olh->count; i++) {
1581 			error = f(info, arg); /* Ignore errors for now */
1582 			info = (ipfw_xtable_info *)((caddr_t)info + olh->objsize);
1583 		}
1584 
1585 		free(olh);
1586 		break;
1587 	}
1588 
1589 	return (0);
1590 }
1591 
1592 
1593 /*
1594  * Retrieves all entries for given table @i in
1595  * eXtended format. Allocate buffer large enough
1596  * to store result. Called needs to free it later.
1597  *
1598  * Returns 0 on success.
1599  */
1600 static int
1601 table_do_get_list(ipfw_xtable_info *i, ipfw_obj_header **poh)
1602 {
1603 	ipfw_obj_header *oh;
1604 	size_t sz;
1605 	int c;
1606 
1607 	sz = 0;
1608 	oh = NULL;
1609 	for (c = 0; c < 8; c++) {
1610 		if (sz < i->size)
1611 			sz = i->size + 44;
1612 		if (oh != NULL)
1613 			free(oh);
1614 		if ((oh = calloc(1, sz)) == NULL)
1615 			continue;
1616 		table_fill_objheader(oh, i);
1617 		oh->opheader.version = 1; /* Current version */
1618 		if (do_get3(IP_FW_TABLE_XLIST, &oh->opheader, &sz) == 0) {
1619 			*poh = oh;
1620 			return (0);
1621 		}
1622 
1623 		if (errno != ENOMEM)
1624 			break;
1625 	}
1626 	free(oh);
1627 
1628 	return (errno);
1629 }
1630 
1631 /*
1632  * Shows all entries from @oh in human-readable format
1633  */
1634 static void
1635 table_show_list(ipfw_obj_header *oh, int need_header)
1636 {
1637 	ipfw_obj_tentry *tent;
1638 	uint32_t count;
1639 	ipfw_xtable_info *i;
1640 
1641 	i = (ipfw_xtable_info *)(oh + 1);
1642 	tent = (ipfw_obj_tentry *)(i + 1);
1643 
1644 	if (need_header)
1645 		printf("--- table(%s), set(%u) ---\n", i->tablename, i->set);
1646 
1647 	count = i->count;
1648 	while (count > 0) {
1649 		table_show_entry(i, tent);
1650 		tent = (ipfw_obj_tentry *)((caddr_t)tent + tent->head.length);
1651 		count--;
1652 	}
1653 }
1654 
1655 static void
1656 table_show_value(char *buf, size_t bufsize, ipfw_table_value *v,
1657     uint32_t vmask, int print_ip)
1658 {
1659 	char abuf[INET6_ADDRSTRLEN + IF_NAMESIZE + 2];
1660 	struct sockaddr_in6 sa6;
1661 	uint32_t flag, i, l;
1662 	size_t sz;
1663 	struct in_addr a4;
1664 
1665 	sz = bufsize;
1666 
1667 	/*
1668 	 * Some shorthands for printing values:
1669 	 * legacy assumes all values are equal, so keep the first one.
1670 	 */
1671 	if (vmask == IPFW_VTYPE_LEGACY) {
1672 		if (print_ip != 0) {
1673 			flag = htonl(v->tag);
1674 			inet_ntop(AF_INET, &flag, buf, sz);
1675 		} else
1676 			snprintf(buf, sz, "%u", v->tag);
1677 		return;
1678 	}
1679 
1680 	for (i = 1; i < (1 << 31); i *= 2) {
1681 		if ((flag = (vmask & i)) == 0)
1682 			continue;
1683 		l = 0;
1684 
1685 		switch (flag) {
1686 		case IPFW_VTYPE_TAG:
1687 			l = snprintf(buf, sz, "%u,", v->tag);
1688 			break;
1689 		case IPFW_VTYPE_PIPE:
1690 			l = snprintf(buf, sz, "%u,", v->pipe);
1691 			break;
1692 		case IPFW_VTYPE_DIVERT:
1693 			l = snprintf(buf, sz, "%d,", v->divert);
1694 			break;
1695 		case IPFW_VTYPE_SKIPTO:
1696 			l = snprintf(buf, sz, "%d,", v->skipto);
1697 			break;
1698 		case IPFW_VTYPE_NETGRAPH:
1699 			l = snprintf(buf, sz, "%u,", v->netgraph);
1700 			break;
1701 		case IPFW_VTYPE_FIB:
1702 			l = snprintf(buf, sz, "%u,", v->fib);
1703 			break;
1704 		case IPFW_VTYPE_NAT:
1705 			l = snprintf(buf, sz, "%u,", v->nat);
1706 			break;
1707 		case IPFW_VTYPE_LIMIT:
1708 			l = snprintf(buf, sz, "%u,", v->limit);
1709 			break;
1710 		case IPFW_VTYPE_NH4:
1711 			a4.s_addr = htonl(v->nh4);
1712 			inet_ntop(AF_INET, &a4, abuf, sizeof(abuf));
1713 			l = snprintf(buf, sz, "%s,", abuf);
1714 			break;
1715 		case IPFW_VTYPE_DSCP:
1716 			l = snprintf(buf, sz, "%d,", v->dscp);
1717 			break;
1718 		case IPFW_VTYPE_NH6:
1719 			sa6.sin6_family = AF_INET6;
1720 			sa6.sin6_len = sizeof(sa6);
1721 			sa6.sin6_addr = v->nh6;
1722 			sa6.sin6_port = 0;
1723 			sa6.sin6_scope_id = v->zoneid;
1724 			if (getnameinfo((const struct sockaddr *)&sa6,
1725 			    sa6.sin6_len, abuf, sizeof(abuf), NULL, 0,
1726 			    NI_NUMERICHOST) == 0)
1727 				l = snprintf(buf, sz, "%s,", abuf);
1728 			break;
1729 		}
1730 
1731 		buf += l;
1732 		sz -= l;
1733 	}
1734 
1735 	if (sz != bufsize)
1736 		*(buf - 1) = '\0';
1737 }
1738 
1739 static void
1740 table_show_entry(ipfw_xtable_info *i, ipfw_obj_tentry *tent)
1741 {
1742 	char *comma, tbuf[128], pval[128];
1743 	void *paddr;
1744 	struct tflow_entry *tfe;
1745 
1746 	table_show_value(pval, sizeof(pval), &tent->v.value, i->vmask,
1747 	    co.do_value_as_ip);
1748 
1749 	switch (i->type) {
1750 	case IPFW_TABLE_ADDR:
1751 		/* IPv4 or IPv6 prefixes */
1752 		inet_ntop(tent->subtype, &tent->k, tbuf, sizeof(tbuf));
1753 		printf("%s/%u %s\n", tbuf, tent->masklen, pval);
1754 		break;
1755 	case IPFW_TABLE_INTERFACE:
1756 		/* Interface names */
1757 		printf("%s %s\n", tent->k.iface, pval);
1758 		break;
1759 	case IPFW_TABLE_NUMBER:
1760 		/* numbers */
1761 		printf("%u %s\n", tent->k.key, pval);
1762 		break;
1763 	case IPFW_TABLE_FLOW:
1764 		/* flows */
1765 		tfe = &tent->k.flow;
1766 		comma = "";
1767 
1768 		if ((i->tflags & IPFW_TFFLAG_SRCIP) != 0) {
1769 			if (tfe->af == AF_INET)
1770 				paddr = &tfe->a.a4.sip;
1771 			else
1772 				paddr = &tfe->a.a6.sip6;
1773 
1774 			inet_ntop(tfe->af, paddr, tbuf, sizeof(tbuf));
1775 			printf("%s%s", comma, tbuf);
1776 			comma = ",";
1777 		}
1778 
1779 		if ((i->tflags & IPFW_TFFLAG_PROTO) != 0) {
1780 			printf("%s%d", comma, tfe->proto);
1781 			comma = ",";
1782 		}
1783 
1784 		if ((i->tflags & IPFW_TFFLAG_SRCPORT) != 0) {
1785 			printf("%s%d", comma, ntohs(tfe->sport));
1786 			comma = ",";
1787 		}
1788 		if ((i->tflags & IPFW_TFFLAG_DSTIP) != 0) {
1789 			if (tfe->af == AF_INET)
1790 				paddr = &tfe->a.a4.dip;
1791 			else
1792 				paddr = &tfe->a.a6.dip6;
1793 
1794 			inet_ntop(tfe->af, paddr, tbuf, sizeof(tbuf));
1795 			printf("%s%s", comma, tbuf);
1796 			comma = ",";
1797 		}
1798 
1799 		if ((i->tflags & IPFW_TFFLAG_DSTPORT) != 0) {
1800 			printf("%s%d", comma, ntohs(tfe->dport));
1801 			comma = ",";
1802 		}
1803 
1804 		printf(" %s\n", pval);
1805 	}
1806 }
1807 
1808 static int
1809 table_do_get_stdlist(uint16_t opcode, ipfw_obj_lheader **polh)
1810 {
1811 	ipfw_obj_lheader req, *olh;
1812 	size_t sz;
1813 
1814 	memset(&req, 0, sizeof(req));
1815 	sz = sizeof(req);
1816 
1817 	if (do_get3(opcode, &req.opheader, &sz) != 0)
1818 		if (errno != ENOMEM)
1819 			return (errno);
1820 
1821 	sz = req.size;
1822 	if ((olh = calloc(1, sz)) == NULL)
1823 		return (ENOMEM);
1824 
1825 	olh->size = sz;
1826 	if (do_get3(opcode, &olh->opheader, &sz) != 0) {
1827 		free(olh);
1828 		return (errno);
1829 	}
1830 
1831 	*polh = olh;
1832 	return (0);
1833 }
1834 
1835 static int
1836 table_do_get_algolist(ipfw_obj_lheader **polh)
1837 {
1838 
1839 	return (table_do_get_stdlist(IP_FW_TABLES_ALIST, polh));
1840 }
1841 
1842 static int
1843 table_do_get_vlist(ipfw_obj_lheader **polh)
1844 {
1845 
1846 	return (table_do_get_stdlist(IP_FW_TABLE_VLIST, polh));
1847 }
1848 
1849 void
1850 ipfw_list_ta(int ac, char *av[])
1851 {
1852 	ipfw_obj_lheader *olh;
1853 	ipfw_ta_info *info;
1854 	int error, i;
1855 	const char *atype;
1856 
1857 	error = table_do_get_algolist(&olh);
1858 	if (error != 0)
1859 		err(EX_OSERR, "Unable to request algorithm list");
1860 
1861 	info = (ipfw_ta_info *)(olh + 1);
1862 	for (i = 0; i < olh->count; i++) {
1863 		if ((atype = match_value(tabletypes, info->type)) == NULL)
1864 			atype = "unknown";
1865 		printf("--- %s ---\n", info->algoname);
1866 		printf(" type: %s\n refcount: %u\n", atype, info->refcnt);
1867 
1868 		info = (ipfw_ta_info *)((caddr_t)info + olh->objsize);
1869 	}
1870 
1871 	free(olh);
1872 }
1873 
1874 
1875 /* Copy of current kernel table_value structure */
1876 struct _table_value {
1877 	uint32_t	tag;		/* O_TAG/O_TAGGED */
1878 	uint32_t	pipe;		/* O_PIPE/O_QUEUE */
1879 	uint16_t	divert;		/* O_DIVERT/O_TEE */
1880 	uint16_t	skipto;		/* skipto, CALLRET */
1881 	uint32_t	netgraph;	/* O_NETGRAPH/O_NGTEE */
1882 	uint32_t	fib;		/* O_SETFIB */
1883 	uint32_t	nat;		/* O_NAT */
1884 	uint32_t	nh4;
1885 	uint8_t		dscp;
1886 	uint8_t		spare0;
1887 	uint16_t	spare1;
1888 	/* -- 32 bytes -- */
1889 	struct in6_addr	nh6;
1890 	uint32_t	limit;		/* O_LIMIT */
1891 	uint32_t	zoneid;
1892 	uint64_t	refcnt;		/* Number of references */
1893 };
1894 
1895 int
1896 compare_values(const void *_a, const void *_b)
1897 {
1898 	struct _table_value *a, *b;
1899 
1900 	a = (struct _table_value *)_a;
1901 	b = (struct _table_value *)_b;
1902 
1903 	if (a->spare1 < b->spare1)
1904 		return (-1);
1905 	else if (a->spare1 > b->spare1)
1906 		return (1);
1907 
1908 	return (0);
1909 }
1910 
1911 void
1912 ipfw_list_values(int ac, char *av[])
1913 {
1914 	ipfw_obj_lheader *olh;
1915 	struct _table_value *v;
1916 	int error, i;
1917 	uint32_t vmask;
1918 	char buf[128];
1919 
1920 	error = table_do_get_vlist(&olh);
1921 	if (error != 0)
1922 		err(EX_OSERR, "Unable to request value list");
1923 
1924 	vmask = 0x7FFFFFFF; /* Similar to IPFW_VTYPE_LEGACY */
1925 
1926 	table_print_valheader(buf, sizeof(buf), vmask);
1927 	printf("HEADER: %s\n", buf);
1928 	v = (struct _table_value *)(olh + 1);
1929 	qsort(v, olh->count, olh->objsize, compare_values);
1930 	for (i = 0; i < olh->count; i++) {
1931 		table_show_value(buf, sizeof(buf), (ipfw_table_value *)v,
1932 		    vmask, 0);
1933 		printf("[%u] refs=%lu %s\n", v->spare1, (u_long)v->refcnt, buf);
1934 		v = (struct _table_value *)((caddr_t)v + olh->objsize);
1935 	}
1936 
1937 	free(olh);
1938 }
1939 
1940 int
1941 table_check_name(char *tablename)
1942 {
1943 	int c, i, l;
1944 
1945 	/*
1946 	 * Check if tablename is null-terminated and contains
1947 	 * valid symbols only. Valid mask is:
1948 	 * [a-zA-Z0-9\-_\.]{1,63}
1949 	 */
1950 	l = strlen(tablename);
1951 	if (l == 0 || l >= 64)
1952 		return (EINVAL);
1953 	for (i = 0; i < l; i++) {
1954 		c = tablename[i];
1955 		if (isalpha(c) || isdigit(c) || c == '_' ||
1956 		    c == '-' || c == '.')
1957 			continue;
1958 		return (EINVAL);
1959 	}
1960 
1961 	/* Restrict some 'special' names */
1962 	if (strcmp(tablename, "all") == 0)
1963 		return (EINVAL);
1964 
1965 	return (0);
1966 }
1967 
1968