xref: /freebsd/sbin/ipfw/tables.c (revision f5846f16)
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 into "
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 /*
1314  * Tries to guess table key type.
1315  * This procedure is used in legacy table auto-create
1316  * code AND in `ipfw -n` ruleset checking.
1317  *
1318  * Imported from old table_fill_xentry() parse code.
1319  */
1320 static int
1321 guess_key_type(char *key, uint8_t *ptype)
1322 {
1323 	char *p;
1324 	struct in6_addr addr;
1325 	uint32_t kv;
1326 
1327 	if (ishexnumber(*key) != 0 || *key == ':') {
1328 		/* Remove / if exists */
1329 		if ((p = strchr(key, '/')) != NULL)
1330 			*p = '\0';
1331 
1332 		if ((inet_pton(AF_INET, key, &addr) == 1) ||
1333 		    (inet_pton(AF_INET6, key, &addr) == 1)) {
1334 			*ptype = IPFW_TABLE_CIDR;
1335 			if (p != NULL)
1336 				*p = '/';
1337 			return (0);
1338 		} else {
1339 			/* Port or any other key */
1340 			/* Skip non-base 10 entries like 'fa1' */
1341 			kv = strtol(key, &p, 10);
1342 			if (*p == '\0') {
1343 				*ptype = IPFW_TABLE_NUMBER;
1344 				return (0);
1345 			} else if ((p != key) && (*p == '.')) {
1346 				/*
1347 				 * Warn on IPv4 address strings
1348 				 * which are "valid" for inet_aton() but not
1349 				 * in inet_pton().
1350 				 *
1351 				 * Typical examples: '10.5' or '10.0.0.05'
1352 				 */
1353 				return (1);
1354 			}
1355 		}
1356 	}
1357 
1358 	if (strchr(key, '.') == NULL) {
1359 		*ptype = IPFW_TABLE_INTERFACE;
1360 		return (0);
1361 	}
1362 
1363 	if (lookup_host(key, (struct in_addr *)&addr) != 0)
1364 		return (1);
1365 
1366 	*ptype = IPFW_TABLE_CIDR;
1367 	return (0);
1368 }
1369 
1370 static void
1371 tentry_fill_key(ipfw_obj_header *oh, ipfw_obj_tentry *tent, char *key,
1372     int add, uint8_t *ptype, uint32_t *pvmask, ipfw_xtable_info *xi)
1373 {
1374 	uint8_t type, tflags;
1375 	uint32_t vmask;
1376 	int error;
1377 
1378 	type = 0;
1379 	tflags = 0;
1380 	vmask = 0;
1381 
1382 	if (xi->tablename[0] == '\0')
1383 		error = table_get_info(oh, xi);
1384 	else
1385 		error = 0;
1386 
1387 	if (error == 0) {
1388 		if (co.test_only == 0) {
1389 			/* Table found */
1390 			type = xi->type;
1391 			tflags = xi->tflags;
1392 			vmask = xi->vmask;
1393 		} else {
1394 			/*
1395 			 * we're running `ipfw -n`
1396 			 * Compability layer: try to guess key type
1397 			 * before failing.
1398 			 */
1399 			if (guess_key_type(key, &type) != 0) {
1400 				/* Inknown key */
1401 				errx(EX_USAGE, "Cannot guess "
1402 				    "key '%s' type", key);
1403 			}
1404 			vmask = IPFW_VTYPE_LEGACY;
1405 		}
1406 	} else {
1407 		if (error != ESRCH)
1408 			errx(EX_OSERR, "Error requesting table %s info",
1409 			    oh->ntlv.name);
1410 		if (add == 0)
1411 			errx(EX_DATAERR, "Table %s does not exist",
1412 			    oh->ntlv.name);
1413 		/*
1414 		 * Table does not exist
1415 		 * Compability layer: try to guess key type before failing.
1416 		 */
1417 		if (guess_key_type(key, &type) != 0) {
1418 			/* Inknown key */
1419 			errx(EX_USAGE, "Table %s does not exist, cannot guess "
1420 			    "key '%s' type", oh->ntlv.name, key);
1421 		}
1422 
1423 		vmask = IPFW_VTYPE_LEGACY;
1424 	}
1425 
1426 	tentry_fill_key_type(key, tent, type, tflags);
1427 
1428 	*ptype = type;
1429 	*pvmask = vmask;
1430 }
1431 
1432 static void
1433 set_legacy_value(uint32_t val, ipfw_table_value *v)
1434 {
1435 	v->tag = val;
1436 	v->pipe = val;
1437 	v->divert = val;
1438 	v->skipto = val;
1439 	v->netgraph = val;
1440 	v->fib = val;
1441 	v->nat = val;
1442 	v->nh4 = val;
1443 	v->dscp = (uint8_t)val;
1444 	v->limit = val;
1445 }
1446 
1447 static void
1448 tentry_fill_value(ipfw_obj_header *oh, ipfw_obj_tentry *tent, char *arg,
1449     uint8_t type, uint32_t vmask)
1450 {
1451 	struct addrinfo hints, *res;
1452 	uint32_t a4, flag, val, vm;
1453 	ipfw_table_value *v;
1454 	uint32_t i;
1455 	int dval;
1456 	char *comma, *e, *etype, *n, *p;
1457 
1458 	v = &tent->v.value;
1459 	vm = vmask;
1460 
1461 	/* Compat layer: keep old behavior for legacy value types */
1462 	if (vmask == IPFW_VTYPE_LEGACY) {
1463 		/* Try to interpret as number first */
1464 		val = strtoul(arg, &p, 0);
1465 		if (*p == '\0') {
1466 			set_legacy_value(val, v);
1467 			return;
1468 		}
1469 		if (inet_pton(AF_INET, arg, &val) == 1) {
1470 			set_legacy_value(ntohl(val), v);
1471 			return;
1472 		}
1473 		/* Try hostname */
1474 		if (lookup_host(arg, (struct in_addr *)&val) == 0) {
1475 			set_legacy_value(val, v);
1476 			return;
1477 		}
1478 		errx(EX_OSERR, "Unable to parse value %s", arg);
1479 	}
1480 
1481 	/*
1482 	 * Shorthands: handle single value if vmask consists
1483 	 * of numbers only. e.g.:
1484 	 * vmask = "fib,skipto" -> treat input "1" as "1,1"
1485 	 */
1486 
1487 	n = arg;
1488 	etype = NULL;
1489 	for (i = 1; i < (1 << 31); i *= 2) {
1490 		if ((flag = (vmask & i)) == 0)
1491 			continue;
1492 		vmask &= ~flag;
1493 
1494 		if ((comma = strchr(n, ',')) != NULL)
1495 			*comma = '\0';
1496 
1497 		switch (flag) {
1498 		case IPFW_VTYPE_TAG:
1499 			v->tag = strtol(n, &e, 10);
1500 			if (*e != '\0')
1501 				etype = "tag";
1502 			break;
1503 		case IPFW_VTYPE_PIPE:
1504 			v->pipe = strtol(n, &e, 10);
1505 			if (*e != '\0')
1506 				etype = "pipe";
1507 			break;
1508 		case IPFW_VTYPE_DIVERT:
1509 			v->divert = strtol(n, &e, 10);
1510 			if (*e != '\0')
1511 				etype = "divert";
1512 			break;
1513 		case IPFW_VTYPE_SKIPTO:
1514 			v->skipto = strtol(n, &e, 10);
1515 			if (*e != '\0')
1516 				etype = "skipto";
1517 			break;
1518 		case IPFW_VTYPE_NETGRAPH:
1519 			v->netgraph = strtol(n, &e, 10);
1520 			if (*e != '\0')
1521 				etype = "netgraph";
1522 			break;
1523 		case IPFW_VTYPE_FIB:
1524 			v->fib = strtol(n, &e, 10);
1525 			if (*e != '\0')
1526 				etype = "fib";
1527 			break;
1528 		case IPFW_VTYPE_NAT:
1529 			v->nat = strtol(n, &e, 10);
1530 			if (*e != '\0')
1531 				etype = "nat";
1532 			break;
1533 		case IPFW_VTYPE_LIMIT:
1534 			v->limit = strtol(n, &e, 10);
1535 			if (*e != '\0')
1536 				etype = "limit";
1537 			break;
1538 		case IPFW_VTYPE_NH4:
1539 			if (strchr(n, '.') != NULL &&
1540 			    inet_pton(AF_INET, n, &a4) == 1) {
1541 				v->nh4 = ntohl(a4);
1542 				break;
1543 			}
1544 			if (lookup_host(n, (struct in_addr *)&v->nh4) == 0)
1545 				break;
1546 			etype = "ipv4";
1547 			break;
1548 		case IPFW_VTYPE_DSCP:
1549 			if (isalpha(*n)) {
1550 				if ((dval = match_token(f_ipdscp, n)) != -1) {
1551 					v->dscp = dval;
1552 					break;
1553 				} else
1554 					etype = "DSCP code";
1555 			} else {
1556 				v->dscp = strtol(n, &e, 10);
1557 				if (v->dscp > 63 || *e != '\0')
1558 					etype = "DSCP value";
1559 			}
1560 			break;
1561 		case IPFW_VTYPE_NH6:
1562 			if (strchr(n, ':') != NULL) {
1563 				memset(&hints, 0, sizeof(hints));
1564 				hints.ai_family = AF_INET6;
1565 				hints.ai_flags = AI_NUMERICHOST;
1566 				if (getaddrinfo(n, NULL, &hints, &res) == 0) {
1567 					v->nh6 = ((struct sockaddr_in6 *)
1568 					    res->ai_addr)->sin6_addr;
1569 					v->zoneid = ((struct sockaddr_in6 *)
1570 					    res->ai_addr)->sin6_scope_id;
1571 					freeaddrinfo(res);
1572 					break;
1573 				}
1574 			}
1575 			etype = "ipv6";
1576 			break;
1577 		}
1578 
1579 		if (etype != NULL)
1580 			errx(EX_USAGE, "Unable to parse %s as %s", n, etype);
1581 
1582 		if (comma != NULL)
1583 			*comma++ = ',';
1584 
1585 		if ((n = comma) != NULL)
1586 			continue;
1587 
1588 		/* End of input. */
1589 		if (vmask != 0)
1590 			errx(EX_USAGE, "Not enough fields inside value");
1591 	}
1592 }
1593 
1594 /*
1595  * Compare table names.
1596  * Honor number comparison.
1597  */
1598 static int
1599 tablename_cmp(const void *a, const void *b)
1600 {
1601 	ipfw_xtable_info *ia, *ib;
1602 
1603 	ia = (ipfw_xtable_info *)a;
1604 	ib = (ipfw_xtable_info *)b;
1605 
1606 	return (stringnum_cmp(ia->tablename, ib->tablename));
1607 }
1608 
1609 /*
1610  * Retrieves table list from kernel,
1611  * optionally sorts it and calls requested function for each table.
1612  * Returns 0 on success.
1613  */
1614 static int
1615 tables_foreach(table_cb_t *f, void *arg, int sort)
1616 {
1617 	ipfw_obj_lheader *olh;
1618 	ipfw_xtable_info *info;
1619 	size_t sz;
1620 	int i, error;
1621 
1622 	/* Start with reasonable default */
1623 	sz = sizeof(*olh) + 16 * sizeof(ipfw_xtable_info);
1624 
1625 	for (;;) {
1626 		if ((olh = calloc(1, sz)) == NULL)
1627 			return (ENOMEM);
1628 
1629 		olh->size = sz;
1630 		if (do_get3(IP_FW_TABLES_XLIST, &olh->opheader, &sz) != 0) {
1631 			sz = olh->size;
1632 			free(olh);
1633 			if (errno != ENOMEM)
1634 				return (errno);
1635 			continue;
1636 		}
1637 
1638 		if (sort != 0)
1639 			qsort(olh + 1, olh->count, olh->objsize, tablename_cmp);
1640 
1641 		info = (ipfw_xtable_info *)(olh + 1);
1642 		for (i = 0; i < olh->count; i++) {
1643 			error = f(info, arg); /* Ignore errors for now */
1644 			info = (ipfw_xtable_info *)((caddr_t)info + olh->objsize);
1645 		}
1646 
1647 		free(olh);
1648 		break;
1649 	}
1650 
1651 	return (0);
1652 }
1653 
1654 
1655 /*
1656  * Retrieves all entries for given table @i in
1657  * eXtended format. Allocate buffer large enough
1658  * to store result. Called needs to free it later.
1659  *
1660  * Returns 0 on success.
1661  */
1662 static int
1663 table_do_get_list(ipfw_xtable_info *i, ipfw_obj_header **poh)
1664 {
1665 	ipfw_obj_header *oh;
1666 	size_t sz;
1667 	int c;
1668 
1669 	sz = 0;
1670 	oh = NULL;
1671 	for (c = 0; c < 8; c++) {
1672 		if (sz < i->size)
1673 			sz = i->size + 44;
1674 		if (oh != NULL)
1675 			free(oh);
1676 		if ((oh = calloc(1, sz)) == NULL)
1677 			continue;
1678 		table_fill_objheader(oh, i);
1679 		oh->opheader.version = 1; /* Current version */
1680 		if (do_get3(IP_FW_TABLE_XLIST, &oh->opheader, &sz) == 0) {
1681 			*poh = oh;
1682 			return (0);
1683 		}
1684 
1685 		if (errno != ENOMEM)
1686 			break;
1687 	}
1688 	free(oh);
1689 
1690 	return (errno);
1691 }
1692 
1693 /*
1694  * Shows all entries from @oh in human-readable format
1695  */
1696 static void
1697 table_show_list(ipfw_obj_header *oh, int need_header)
1698 {
1699 	ipfw_obj_tentry *tent;
1700 	uint32_t count;
1701 	ipfw_xtable_info *i;
1702 
1703 	i = (ipfw_xtable_info *)(oh + 1);
1704 	tent = (ipfw_obj_tentry *)(i + 1);
1705 
1706 	if (need_header)
1707 		printf("--- table(%s), set(%u) ---\n", i->tablename, i->set);
1708 
1709 	count = i->count;
1710 	while (count > 0) {
1711 		table_show_entry(i, tent);
1712 		tent = (ipfw_obj_tentry *)((caddr_t)tent + tent->head.length);
1713 		count--;
1714 	}
1715 }
1716 
1717 static void
1718 table_show_value(char *buf, size_t bufsize, ipfw_table_value *v,
1719     uint32_t vmask, int print_ip)
1720 {
1721 	char abuf[INET6_ADDRSTRLEN + IF_NAMESIZE + 2];
1722 	struct sockaddr_in6 sa6;
1723 	uint32_t flag, i, l;
1724 	size_t sz;
1725 	struct in_addr a4;
1726 
1727 	sz = bufsize;
1728 
1729 	/*
1730 	 * Some shorthands for printing values:
1731 	 * legacy assumes all values are equal, so keep the first one.
1732 	 */
1733 	if (vmask == IPFW_VTYPE_LEGACY) {
1734 		if (print_ip != 0) {
1735 			flag = htonl(v->tag);
1736 			inet_ntop(AF_INET, &flag, buf, sz);
1737 		} else
1738 			snprintf(buf, sz, "%u", v->tag);
1739 		return;
1740 	}
1741 
1742 	for (i = 1; i < (1 << 31); i *= 2) {
1743 		if ((flag = (vmask & i)) == 0)
1744 			continue;
1745 		l = 0;
1746 
1747 		switch (flag) {
1748 		case IPFW_VTYPE_TAG:
1749 			l = snprintf(buf, sz, "%u,", v->tag);
1750 			break;
1751 		case IPFW_VTYPE_PIPE:
1752 			l = snprintf(buf, sz, "%u,", v->pipe);
1753 			break;
1754 		case IPFW_VTYPE_DIVERT:
1755 			l = snprintf(buf, sz, "%d,", v->divert);
1756 			break;
1757 		case IPFW_VTYPE_SKIPTO:
1758 			l = snprintf(buf, sz, "%d,", v->skipto);
1759 			break;
1760 		case IPFW_VTYPE_NETGRAPH:
1761 			l = snprintf(buf, sz, "%u,", v->netgraph);
1762 			break;
1763 		case IPFW_VTYPE_FIB:
1764 			l = snprintf(buf, sz, "%u,", v->fib);
1765 			break;
1766 		case IPFW_VTYPE_NAT:
1767 			l = snprintf(buf, sz, "%u,", v->nat);
1768 			break;
1769 		case IPFW_VTYPE_LIMIT:
1770 			l = snprintf(buf, sz, "%u,", v->limit);
1771 			break;
1772 		case IPFW_VTYPE_NH4:
1773 			a4.s_addr = htonl(v->nh4);
1774 			inet_ntop(AF_INET, &a4, abuf, sizeof(abuf));
1775 			l = snprintf(buf, sz, "%s,", abuf);
1776 			break;
1777 		case IPFW_VTYPE_DSCP:
1778 			l = snprintf(buf, sz, "%d,", v->dscp);
1779 			break;
1780 		case IPFW_VTYPE_NH6:
1781 			sa6.sin6_family = AF_INET6;
1782 			sa6.sin6_len = sizeof(sa6);
1783 			sa6.sin6_addr = v->nh6;
1784 			sa6.sin6_port = 0;
1785 			sa6.sin6_scope_id = v->zoneid;
1786 			if (getnameinfo((const struct sockaddr *)&sa6,
1787 			    sa6.sin6_len, abuf, sizeof(abuf), NULL, 0,
1788 			    NI_NUMERICHOST) == 0)
1789 				l = snprintf(buf, sz, "%s,", abuf);
1790 			break;
1791 		}
1792 
1793 		buf += l;
1794 		sz -= l;
1795 	}
1796 
1797 	if (sz != bufsize)
1798 		*(buf - 1) = '\0';
1799 }
1800 
1801 static void
1802 table_show_entry(ipfw_xtable_info *i, ipfw_obj_tentry *tent)
1803 {
1804 	char *comma, tbuf[128], pval[128];
1805 	void *paddr;
1806 	struct tflow_entry *tfe;
1807 
1808 	table_show_value(pval, sizeof(pval), &tent->v.value, i->vmask,
1809 	    co.do_value_as_ip);
1810 
1811 	switch (i->type) {
1812 	case IPFW_TABLE_ADDR:
1813 		/* IPv4 or IPv6 prefixes */
1814 		inet_ntop(tent->subtype, &tent->k, tbuf, sizeof(tbuf));
1815 		printf("%s/%u %s\n", tbuf, tent->masklen, pval);
1816 		break;
1817 	case IPFW_TABLE_INTERFACE:
1818 		/* Interface names */
1819 		printf("%s %s\n", tent->k.iface, pval);
1820 		break;
1821 	case IPFW_TABLE_NUMBER:
1822 		/* numbers */
1823 		printf("%u %s\n", tent->k.key, pval);
1824 		break;
1825 	case IPFW_TABLE_FLOW:
1826 		/* flows */
1827 		tfe = &tent->k.flow;
1828 		comma = "";
1829 
1830 		if ((i->tflags & IPFW_TFFLAG_SRCIP) != 0) {
1831 			if (tfe->af == AF_INET)
1832 				paddr = &tfe->a.a4.sip;
1833 			else
1834 				paddr = &tfe->a.a6.sip6;
1835 
1836 			inet_ntop(tfe->af, paddr, tbuf, sizeof(tbuf));
1837 			printf("%s%s", comma, tbuf);
1838 			comma = ",";
1839 		}
1840 
1841 		if ((i->tflags & IPFW_TFFLAG_PROTO) != 0) {
1842 			printf("%s%d", comma, tfe->proto);
1843 			comma = ",";
1844 		}
1845 
1846 		if ((i->tflags & IPFW_TFFLAG_SRCPORT) != 0) {
1847 			printf("%s%d", comma, ntohs(tfe->sport));
1848 			comma = ",";
1849 		}
1850 		if ((i->tflags & IPFW_TFFLAG_DSTIP) != 0) {
1851 			if (tfe->af == AF_INET)
1852 				paddr = &tfe->a.a4.dip;
1853 			else
1854 				paddr = &tfe->a.a6.dip6;
1855 
1856 			inet_ntop(tfe->af, paddr, tbuf, sizeof(tbuf));
1857 			printf("%s%s", comma, tbuf);
1858 			comma = ",";
1859 		}
1860 
1861 		if ((i->tflags & IPFW_TFFLAG_DSTPORT) != 0) {
1862 			printf("%s%d", comma, ntohs(tfe->dport));
1863 			comma = ",";
1864 		}
1865 
1866 		printf(" %s\n", pval);
1867 	}
1868 }
1869 
1870 static int
1871 table_do_get_stdlist(uint16_t opcode, ipfw_obj_lheader **polh)
1872 {
1873 	ipfw_obj_lheader req, *olh;
1874 	size_t sz;
1875 
1876 	memset(&req, 0, sizeof(req));
1877 	sz = sizeof(req);
1878 
1879 	if (do_get3(opcode, &req.opheader, &sz) != 0)
1880 		if (errno != ENOMEM)
1881 			return (errno);
1882 
1883 	sz = req.size;
1884 	if ((olh = calloc(1, sz)) == NULL)
1885 		return (ENOMEM);
1886 
1887 	olh->size = sz;
1888 	if (do_get3(opcode, &olh->opheader, &sz) != 0) {
1889 		free(olh);
1890 		return (errno);
1891 	}
1892 
1893 	*polh = olh;
1894 	return (0);
1895 }
1896 
1897 static int
1898 table_do_get_algolist(ipfw_obj_lheader **polh)
1899 {
1900 
1901 	return (table_do_get_stdlist(IP_FW_TABLES_ALIST, polh));
1902 }
1903 
1904 static int
1905 table_do_get_vlist(ipfw_obj_lheader **polh)
1906 {
1907 
1908 	return (table_do_get_stdlist(IP_FW_TABLE_VLIST, polh));
1909 }
1910 
1911 void
1912 ipfw_list_ta(int ac, char *av[])
1913 {
1914 	ipfw_obj_lheader *olh;
1915 	ipfw_ta_info *info;
1916 	int error, i;
1917 	const char *atype;
1918 
1919 	error = table_do_get_algolist(&olh);
1920 	if (error != 0)
1921 		err(EX_OSERR, "Unable to request algorithm list");
1922 
1923 	info = (ipfw_ta_info *)(olh + 1);
1924 	for (i = 0; i < olh->count; i++) {
1925 		if ((atype = match_value(tabletypes, info->type)) == NULL)
1926 			atype = "unknown";
1927 		printf("--- %s ---\n", info->algoname);
1928 		printf(" type: %s\n refcount: %u\n", atype, info->refcnt);
1929 
1930 		info = (ipfw_ta_info *)((caddr_t)info + olh->objsize);
1931 	}
1932 
1933 	free(olh);
1934 }
1935 
1936 
1937 /* Copy of current kernel table_value structure */
1938 struct _table_value {
1939 	uint32_t	tag;		/* O_TAG/O_TAGGED */
1940 	uint32_t	pipe;		/* O_PIPE/O_QUEUE */
1941 	uint16_t	divert;		/* O_DIVERT/O_TEE */
1942 	uint16_t	skipto;		/* skipto, CALLRET */
1943 	uint32_t	netgraph;	/* O_NETGRAPH/O_NGTEE */
1944 	uint32_t	fib;		/* O_SETFIB */
1945 	uint32_t	nat;		/* O_NAT */
1946 	uint32_t	nh4;
1947 	uint8_t		dscp;
1948 	uint8_t		spare0;
1949 	uint16_t	spare1;
1950 	/* -- 32 bytes -- */
1951 	struct in6_addr	nh6;
1952 	uint32_t	limit;		/* O_LIMIT */
1953 	uint32_t	zoneid;
1954 	uint64_t	refcnt;		/* Number of references */
1955 };
1956 
1957 int
1958 compare_values(const void *_a, const void *_b)
1959 {
1960 	struct _table_value *a, *b;
1961 
1962 	a = (struct _table_value *)_a;
1963 	b = (struct _table_value *)_b;
1964 
1965 	if (a->spare1 < b->spare1)
1966 		return (-1);
1967 	else if (a->spare1 > b->spare1)
1968 		return (1);
1969 
1970 	return (0);
1971 }
1972 
1973 void
1974 ipfw_list_values(int ac, char *av[])
1975 {
1976 	ipfw_obj_lheader *olh;
1977 	struct _table_value *v;
1978 	int error, i;
1979 	uint32_t vmask;
1980 	char buf[128];
1981 
1982 	error = table_do_get_vlist(&olh);
1983 	if (error != 0)
1984 		err(EX_OSERR, "Unable to request value list");
1985 
1986 	vmask = 0x7FFFFFFF; /* Similar to IPFW_VTYPE_LEGACY */
1987 
1988 	table_print_valheader(buf, sizeof(buf), vmask);
1989 	printf("HEADER: %s\n", buf);
1990 	v = (struct _table_value *)(olh + 1);
1991 	qsort(v, olh->count, olh->objsize, compare_values);
1992 	for (i = 0; i < olh->count; i++) {
1993 		table_show_value(buf, sizeof(buf), (ipfw_table_value *)v,
1994 		    vmask, 0);
1995 		printf("[%u] refs=%lu %s\n", v->spare1, (u_long)v->refcnt, buf);
1996 		v = (struct _table_value *)((caddr_t)v + olh->objsize);
1997 	}
1998 
1999 	free(olh);
2000 }
2001 
2002 int
2003 table_check_name(char *tablename)
2004 {
2005 	int c, i, l;
2006 
2007 	/*
2008 	 * Check if tablename is null-terminated and contains
2009 	 * valid symbols only. Valid mask is:
2010 	 * [a-zA-Z0-9\-_\.]{1,63}
2011 	 */
2012 	l = strlen(tablename);
2013 	if (l == 0 || l >= 64)
2014 		return (EINVAL);
2015 	for (i = 0; i < l; i++) {
2016 		c = tablename[i];
2017 		if (isalpha(c) || isdigit(c) || c == '_' ||
2018 		    c == '-' || c == '.')
2019 			continue;
2020 		return (EINVAL);
2021 	}
2022 
2023 	/* Restrict some 'special' names */
2024 	if (strcmp(tablename, "all") == 0)
2025 		return (EINVAL);
2026 
2027 	return (0);
2028 }
2029 
2030