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