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