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