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