xref: /freebsd/sbin/pfctl/pfctl_parser.c (revision 8a7df6c58d549bd2eaa5cad30b2ef93c3eca3c18)
1 /*	$OpenBSD: pfctl_parser.c,v 1.240 2008/06/10 20:55:02 mcbride Exp $ */
2 
3 /*-
4  * SPDX-License-Identifier: BSD-2-Clause
5  *
6  * Copyright (c) 2001 Daniel Hartmeier
7  * Copyright (c) 2002,2003 Henning Brauer
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  *
14  *    - Redistributions of source code must retain the above copyright
15  *      notice, this list of conditions and the following disclaimer.
16  *    - Redistributions in binary form must reproduce the above
17  *      copyright notice, this list of conditions and the following
18  *      disclaimer in the documentation and/or other materials provided
19  *      with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
29  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGE.
33  *
34  */
35 
36 #include <sys/types.h>
37 #include <sys/ioctl.h>
38 #include <sys/socket.h>
39 #include <sys/param.h>
40 #include <sys/proc.h>
41 #include <net/if_dl.h>
42 #include <net/if.h>
43 #include <netinet/in.h>
44 #include <netinet/in_systm.h>
45 #include <netinet/ip.h>
46 #include <netinet/ip_icmp.h>
47 #include <netinet/icmp6.h>
48 #include <netinet/tcp.h>
49 #include <net/pfvar.h>
50 #include <arpa/inet.h>
51 
52 #include <assert.h>
53 #include <search.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <ctype.h>
58 #include <netdb.h>
59 #include <stdarg.h>
60 #include <errno.h>
61 #include <err.h>
62 #include <ifaddrs.h>
63 #include <inttypes.h>
64 #include <unistd.h>
65 
66 #include "pfctl_parser.h"
67 #include "pfctl.h"
68 
69 void		 print_op (u_int8_t, const char *, const char *);
70 void		 print_port (u_int8_t, u_int16_t, u_int16_t, const char *, int);
71 void		 print_ugid (u_int8_t, id_t, id_t, const char *);
72 void		 print_flags (uint16_t);
73 void		 print_fromto(struct pf_rule_addr *, pf_osfp_t,
74 		    struct pf_rule_addr *, sa_family_t, u_int8_t, int, int);
75 int		 ifa_skip_if(const char *filter, struct node_host *p);
76 
77 struct node_host	*host_if(const char *, int);
78 struct node_host	*host_ip(const char *, int);
79 struct node_host	*host_dns(const char *, int, int);
80 
81 const char * const tcpflags = "FSRPAUEWe";
82 
83 static const struct icmptypeent icmp_type[] = {
84 	{ "echoreq",	ICMP_ECHO },
85 	{ "echorep",	ICMP_ECHOREPLY },
86 	{ "unreach",	ICMP_UNREACH },
87 	{ "squench",	ICMP_SOURCEQUENCH },
88 	{ "redir",	ICMP_REDIRECT },
89 	{ "althost",	ICMP_ALTHOSTADDR },
90 	{ "routeradv",	ICMP_ROUTERADVERT },
91 	{ "routersol",	ICMP_ROUTERSOLICIT },
92 	{ "timex",	ICMP_TIMXCEED },
93 	{ "paramprob",	ICMP_PARAMPROB },
94 	{ "timereq",	ICMP_TSTAMP },
95 	{ "timerep",	ICMP_TSTAMPREPLY },
96 	{ "inforeq",	ICMP_IREQ },
97 	{ "inforep",	ICMP_IREQREPLY },
98 	{ "maskreq",	ICMP_MASKREQ },
99 	{ "maskrep",	ICMP_MASKREPLY },
100 	{ "trace",	ICMP_TRACEROUTE },
101 	{ "dataconv",	ICMP_DATACONVERR },
102 	{ "mobredir",	ICMP_MOBILE_REDIRECT },
103 	{ "ipv6-where",	ICMP_IPV6_WHEREAREYOU },
104 	{ "ipv6-here",	ICMP_IPV6_IAMHERE },
105 	{ "mobregreq",	ICMP_MOBILE_REGREQUEST },
106 	{ "mobregrep",	ICMP_MOBILE_REGREPLY },
107 	{ "skip",	ICMP_SKIP },
108 	{ "photuris",	ICMP_PHOTURIS }
109 };
110 
111 static const struct icmptypeent icmp6_type[] = {
112 	{ "unreach",	ICMP6_DST_UNREACH },
113 	{ "toobig",	ICMP6_PACKET_TOO_BIG },
114 	{ "timex",	ICMP6_TIME_EXCEEDED },
115 	{ "paramprob",	ICMP6_PARAM_PROB },
116 	{ "echoreq",	ICMP6_ECHO_REQUEST },
117 	{ "echorep",	ICMP6_ECHO_REPLY },
118 	{ "groupqry",	ICMP6_MEMBERSHIP_QUERY },
119 	{ "listqry",	MLD_LISTENER_QUERY },
120 	{ "grouprep",	ICMP6_MEMBERSHIP_REPORT },
121 	{ "listenrep",	MLD_LISTENER_REPORT },
122 	{ "groupterm",	ICMP6_MEMBERSHIP_REDUCTION },
123 	{ "listendone", MLD_LISTENER_DONE },
124 	{ "routersol",	ND_ROUTER_SOLICIT },
125 	{ "routeradv",	ND_ROUTER_ADVERT },
126 	{ "neighbrsol", ND_NEIGHBOR_SOLICIT },
127 	{ "neighbradv", ND_NEIGHBOR_ADVERT },
128 	{ "redir",	ND_REDIRECT },
129 	{ "routrrenum", ICMP6_ROUTER_RENUMBERING },
130 	{ "wrureq",	ICMP6_WRUREQUEST },
131 	{ "wrurep",	ICMP6_WRUREPLY },
132 	{ "fqdnreq",	ICMP6_FQDN_QUERY },
133 	{ "fqdnrep",	ICMP6_FQDN_REPLY },
134 	{ "niqry",	ICMP6_NI_QUERY },
135 	{ "nirep",	ICMP6_NI_REPLY },
136 	{ "mtraceresp",	MLD_MTRACE_RESP },
137 	{ "mtrace",	MLD_MTRACE },
138 	{ "listenrepv2", MLDV2_LISTENER_REPORT },
139 };
140 
141 static const struct icmpcodeent icmp_code[] = {
142 	{ "net-unr",		ICMP_UNREACH,	ICMP_UNREACH_NET },
143 	{ "host-unr",		ICMP_UNREACH,	ICMP_UNREACH_HOST },
144 	{ "proto-unr",		ICMP_UNREACH,	ICMP_UNREACH_PROTOCOL },
145 	{ "port-unr",		ICMP_UNREACH,	ICMP_UNREACH_PORT },
146 	{ "needfrag",		ICMP_UNREACH,	ICMP_UNREACH_NEEDFRAG },
147 	{ "srcfail",		ICMP_UNREACH,	ICMP_UNREACH_SRCFAIL },
148 	{ "net-unk",		ICMP_UNREACH,	ICMP_UNREACH_NET_UNKNOWN },
149 	{ "host-unk",		ICMP_UNREACH,	ICMP_UNREACH_HOST_UNKNOWN },
150 	{ "isolate",		ICMP_UNREACH,	ICMP_UNREACH_ISOLATED },
151 	{ "net-prohib",		ICMP_UNREACH,	ICMP_UNREACH_NET_PROHIB },
152 	{ "host-prohib",	ICMP_UNREACH,	ICMP_UNREACH_HOST_PROHIB },
153 	{ "net-tos",		ICMP_UNREACH,	ICMP_UNREACH_TOSNET },
154 	{ "host-tos",		ICMP_UNREACH,	ICMP_UNREACH_TOSHOST },
155 	{ "filter-prohib",	ICMP_UNREACH,	ICMP_UNREACH_FILTER_PROHIB },
156 	{ "host-preced",	ICMP_UNREACH,	ICMP_UNREACH_HOST_PRECEDENCE },
157 	{ "cutoff-preced",	ICMP_UNREACH,	ICMP_UNREACH_PRECEDENCE_CUTOFF },
158 	{ "redir-net",		ICMP_REDIRECT,	ICMP_REDIRECT_NET },
159 	{ "redir-host",		ICMP_REDIRECT,	ICMP_REDIRECT_HOST },
160 	{ "redir-tos-net",	ICMP_REDIRECT,	ICMP_REDIRECT_TOSNET },
161 	{ "redir-tos-host",	ICMP_REDIRECT,	ICMP_REDIRECT_TOSHOST },
162 	{ "normal-adv",		ICMP_ROUTERADVERT, ICMP_ROUTERADVERT_NORMAL },
163 	{ "common-adv",		ICMP_ROUTERADVERT, ICMP_ROUTERADVERT_NOROUTE_COMMON },
164 	{ "transit",		ICMP_TIMXCEED,	ICMP_TIMXCEED_INTRANS },
165 	{ "reassemb",		ICMP_TIMXCEED,	ICMP_TIMXCEED_REASS },
166 	{ "badhead",		ICMP_PARAMPROB,	ICMP_PARAMPROB_ERRATPTR },
167 	{ "optmiss",		ICMP_PARAMPROB,	ICMP_PARAMPROB_OPTABSENT },
168 	{ "badlen",		ICMP_PARAMPROB,	ICMP_PARAMPROB_LENGTH },
169 	{ "unknown-ind",	ICMP_PHOTURIS,	ICMP_PHOTURIS_UNKNOWN_INDEX },
170 	{ "auth-fail",		ICMP_PHOTURIS,	ICMP_PHOTURIS_AUTH_FAILED },
171 	{ "decrypt-fail",	ICMP_PHOTURIS,	ICMP_PHOTURIS_DECRYPT_FAILED }
172 };
173 
174 static const struct icmpcodeent icmp6_code[] = {
175 	{ "admin-unr", ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADMIN },
176 	{ "noroute-unr", ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_NOROUTE },
177 	{ "notnbr-unr",	ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_NOTNEIGHBOR },
178 	{ "beyond-unr", ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_BEYONDSCOPE },
179 	{ "addr-unr", ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR },
180 	{ "port-unr", ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_NOPORT },
181 	{ "transit", ICMP6_TIME_EXCEEDED, ICMP6_TIME_EXCEED_TRANSIT },
182 	{ "reassemb", ICMP6_TIME_EXCEEDED, ICMP6_TIME_EXCEED_REASSEMBLY },
183 	{ "badhead", ICMP6_PARAM_PROB, ICMP6_PARAMPROB_HEADER },
184 	{ "nxthdr", ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER },
185 	{ "redironlink", ND_REDIRECT, ND_REDIRECT_ONLINK },
186 	{ "redirrouter", ND_REDIRECT, ND_REDIRECT_ROUTER }
187 };
188 
189 const struct pf_timeout pf_timeouts[] = {
190 	{ "tcp.first",		PFTM_TCP_FIRST_PACKET },
191 	{ "tcp.opening",	PFTM_TCP_OPENING },
192 	{ "tcp.established",	PFTM_TCP_ESTABLISHED },
193 	{ "tcp.closing",	PFTM_TCP_CLOSING },
194 	{ "tcp.finwait",	PFTM_TCP_FIN_WAIT },
195 	{ "tcp.closed",		PFTM_TCP_CLOSED },
196 	{ "tcp.tsdiff",		PFTM_TS_DIFF },
197 	{ "sctp.first",		PFTM_SCTP_FIRST_PACKET },
198 	{ "sctp.opening",	PFTM_SCTP_OPENING },
199 	{ "sctp.established",	PFTM_SCTP_ESTABLISHED },
200 	{ "sctp.closing",	PFTM_SCTP_CLOSING },
201 	{ "sctp.closed",	PFTM_SCTP_CLOSED },
202 	{ "udp.first",		PFTM_UDP_FIRST_PACKET },
203 	{ "udp.single",		PFTM_UDP_SINGLE },
204 	{ "udp.multiple",	PFTM_UDP_MULTIPLE },
205 	{ "icmp.first",		PFTM_ICMP_FIRST_PACKET },
206 	{ "icmp.error",		PFTM_ICMP_ERROR_REPLY },
207 	{ "other.first",	PFTM_OTHER_FIRST_PACKET },
208 	{ "other.single",	PFTM_OTHER_SINGLE },
209 	{ "other.multiple",	PFTM_OTHER_MULTIPLE },
210 	{ "frag",		PFTM_FRAG },
211 	{ "interval",		PFTM_INTERVAL },
212 	{ "adaptive.start",	PFTM_ADAPTIVE_START },
213 	{ "adaptive.end",	PFTM_ADAPTIVE_END },
214 	{ "src.track",		PFTM_SRC_NODE },
215 	{ NULL,			0 }
216 };
217 
218 static struct hsearch_data isgroup_map;
219 
220 static __attribute__((constructor)) void
221 pfctl_parser_init(void)
222 {
223 	/*
224 	 * As hdestroy() will never be called on these tables, it will be
225 	 * safe to use references into the stored data as keys.
226 	 */
227 	if (hcreate_r(0, &isgroup_map) == 0)
228 		err(1, "Failed to create interface group query response map");
229 }
230 
231 void
232 copy_satopfaddr(struct pf_addr *pfa, struct sockaddr *sa)
233 {
234 	if (sa->sa_family == AF_INET6)
235 		pfa->v6 = ((struct sockaddr_in6 *)sa)->sin6_addr;
236 	else if (sa->sa_family == AF_INET)
237 		pfa->v4 = ((struct sockaddr_in *)sa)->sin_addr;
238 	else
239 		warnx("unhandled af %d", sa->sa_family);
240 }
241 
242 const struct icmptypeent *
243 geticmptypebynumber(u_int8_t type, sa_family_t af)
244 {
245 	size_t	i;
246 
247 	if (af != AF_INET6) {
248 		for (i=0; i < nitems(icmp_type); i++) {
249 			if (type == icmp_type[i].type)
250 				return (&icmp_type[i]);
251 		}
252 	} else {
253 		for (i=0; i < nitems(icmp6_type); i++) {
254 			if (type == icmp6_type[i].type)
255 				 return (&icmp6_type[i]);
256 		}
257 	}
258 	return (NULL);
259 }
260 
261 const struct icmptypeent *
262 geticmptypebyname(char *w, sa_family_t af)
263 {
264 	size_t	i;
265 
266 	if (af != AF_INET6) {
267 		for (i=0; i < nitems(icmp_type); i++) {
268 			if (!strcmp(w, icmp_type[i].name))
269 				return (&icmp_type[i]);
270 		}
271 	} else {
272 		for (i=0; i < nitems(icmp6_type); i++) {
273 			if (!strcmp(w, icmp6_type[i].name))
274 				return (&icmp6_type[i]);
275 		}
276 	}
277 	return (NULL);
278 }
279 
280 const struct icmpcodeent *
281 geticmpcodebynumber(u_int8_t type, u_int8_t code, sa_family_t af)
282 {
283 	size_t	i;
284 
285 	if (af != AF_INET6) {
286 		for (i=0; i < nitems(icmp_code); i++) {
287 			if (type == icmp_code[i].type &&
288 			    code == icmp_code[i].code)
289 				return (&icmp_code[i]);
290 		}
291 	} else {
292 		for (i=0; i < nitems(icmp6_code); i++) {
293 			if (type == icmp6_code[i].type &&
294 			    code == icmp6_code[i].code)
295 				return (&icmp6_code[i]);
296 		}
297 	}
298 	return (NULL);
299 }
300 
301 const struct icmpcodeent *
302 geticmpcodebyname(u_long type, char *w, sa_family_t af)
303 {
304 	size_t	i;
305 
306 	if (af != AF_INET6) {
307 		for (i=0; i < nitems(icmp_code); i++) {
308 			if (type == icmp_code[i].type &&
309 			    !strcmp(w, icmp_code[i].name))
310 				return (&icmp_code[i]);
311 		}
312 	} else {
313 		for (i=0; i < nitems(icmp6_code); i++) {
314 			if (type == icmp6_code[i].type &&
315 			    !strcmp(w, icmp6_code[i].name))
316 				return (&icmp6_code[i]);
317 		}
318 	}
319 	return (NULL);
320 }
321 
322 void
323 print_op(u_int8_t op, const char *a1, const char *a2)
324 {
325 	if (op == PF_OP_IRG)
326 		printf(" %s >< %s", a1, a2);
327 	else if (op == PF_OP_XRG)
328 		printf(" %s <> %s", a1, a2);
329 	else if (op == PF_OP_EQ)
330 		printf(" = %s", a1);
331 	else if (op == PF_OP_NE)
332 		printf(" != %s", a1);
333 	else if (op == PF_OP_LT)
334 		printf(" < %s", a1);
335 	else if (op == PF_OP_LE)
336 		printf(" <= %s", a1);
337 	else if (op == PF_OP_GT)
338 		printf(" > %s", a1);
339 	else if (op == PF_OP_GE)
340 		printf(" >= %s", a1);
341 	else if (op == PF_OP_RRG)
342 		printf(" %s:%s", a1, a2);
343 }
344 
345 void
346 print_port(u_int8_t op, u_int16_t p1, u_int16_t p2, const char *proto, int numeric)
347 {
348 	char		 a1[6], a2[6];
349 	struct servent	*s;
350 
351 	if (!numeric)
352 		s = getservbyport(p1, proto);
353 	else
354 		s = NULL;
355 	p1 = ntohs(p1);
356 	p2 = ntohs(p2);
357 	snprintf(a1, sizeof(a1), "%u", p1);
358 	snprintf(a2, sizeof(a2), "%u", p2);
359 	printf(" port");
360 	if (s != NULL && (op == PF_OP_EQ || op == PF_OP_NE))
361 		print_op(op, s->s_name, a2);
362 	else
363 		print_op(op, a1, a2);
364 }
365 
366 void
367 print_ugid(u_int8_t op, id_t i1, id_t i2, const char *t)
368 {
369 	char	a1[11], a2[11];
370 
371 	snprintf(a1, sizeof(a1), "%ju", (uintmax_t)i1);
372 	snprintf(a2, sizeof(a2), "%ju", (uintmax_t)i2);
373 	printf(" %s", t);
374 	if (i1 == -1 && (op == PF_OP_EQ || op == PF_OP_NE))
375 		print_op(op, "unknown", a2);
376 	else
377 		print_op(op, a1, a2);
378 }
379 
380 void
381 print_flags(uint16_t f)
382 {
383 	int	i;
384 
385 	for (i = 0; tcpflags[i]; ++i)
386 		if (f & (1 << i))
387 			printf("%c", tcpflags[i]);
388 }
389 
390 void
391 print_fromto(struct pf_rule_addr *src, pf_osfp_t osfp, struct pf_rule_addr *dst,
392     sa_family_t af, u_int8_t proto, int opts, int numeric)
393 {
394 	char buf[PF_OSFP_LEN*3];
395 	int verbose = opts & (PF_OPT_VERBOSE2 | PF_OPT_DEBUG);
396 
397 	if (src->addr.type == PF_ADDR_ADDRMASK &&
398 	    dst->addr.type == PF_ADDR_ADDRMASK &&
399 	    PF_AZERO(&src->addr.v.a.addr, AF_INET6) &&
400 	    PF_AZERO(&src->addr.v.a.mask, AF_INET6) &&
401 	    PF_AZERO(&dst->addr.v.a.addr, AF_INET6) &&
402 	    PF_AZERO(&dst->addr.v.a.mask, AF_INET6) &&
403 	    !src->neg && !dst->neg &&
404 	    !src->port_op && !dst->port_op &&
405 	    osfp == PF_OSFP_ANY)
406 		printf(" all");
407 	else {
408 		printf(" from ");
409 		if (src->neg)
410 			printf("! ");
411 		print_addr(&src->addr, af, verbose);
412 		if (src->port_op)
413 			print_port(src->port_op, src->port[0],
414 			    src->port[1],
415 			    proto == IPPROTO_TCP ? "tcp" : "udp",
416 			    numeric);
417 		if (osfp != PF_OSFP_ANY)
418 			printf(" os \"%s\"", pfctl_lookup_fingerprint(osfp, buf,
419 			    sizeof(buf)));
420 
421 		printf(" to ");
422 		if (dst->neg)
423 			printf("! ");
424 		print_addr(&dst->addr, af, verbose);
425 		if (dst->port_op)
426 			print_port(dst->port_op, dst->port[0],
427 			    dst->port[1],
428 			    proto == IPPROTO_TCP ? "tcp" : "udp",
429 			    numeric);
430 	}
431 }
432 
433 void
434 print_pool(struct pfctl_pool *pool, u_int16_t p1, u_int16_t p2, int id)
435 {
436 	struct pfctl_pooladdr	*pooladdr;
437 
438 	if ((TAILQ_FIRST(&pool->list) != NULL) &&
439 	    TAILQ_NEXT(TAILQ_FIRST(&pool->list), entries) != NULL)
440 		printf("{ ");
441 	TAILQ_FOREACH(pooladdr, &pool->list, entries){
442 		switch (id) {
443 		case PF_NAT:
444 		case PF_RDR:
445 		case PF_BINAT:
446 			print_addr(&pooladdr->addr, pooladdr->af, 0);
447 			break;
448 		case PF_PASS:
449 		case PF_MATCH:
450 			if (PF_AZERO(&pooladdr->addr.v.a.addr, pooladdr->af))
451 				printf("%s", pooladdr->ifname);
452 			else {
453 				printf("(%s ", pooladdr->ifname);
454 				print_addr(&pooladdr->addr, pooladdr->af, 0);
455 				printf(")");
456 			}
457 			break;
458 		default:
459 			break;
460 		}
461 		if (TAILQ_NEXT(pooladdr, entries) != NULL)
462 			printf(", ");
463 		else if (TAILQ_NEXT(TAILQ_FIRST(&pool->list), entries) != NULL)
464 			printf(" }");
465 	}
466 	switch (id) {
467 	case PF_NAT:
468 		if ((p1 != PF_NAT_PROXY_PORT_LOW ||
469 		    p2 != PF_NAT_PROXY_PORT_HIGH) && (p1 != 0 || p2 != 0)) {
470 			if (p1 == p2)
471 				printf(" port %u", p1);
472 			else
473 				printf(" port %u:%u", p1, p2);
474 		}
475 		break;
476 	case PF_RDR:
477 		if (p1) {
478 			printf(" port %u", p1);
479 			if (p2 && (p2 != p1))
480 				printf(":%u", p2);
481 		}
482 		break;
483 	default:
484 		break;
485 	}
486 	switch (pool->opts & PF_POOL_TYPEMASK) {
487 	case PF_POOL_NONE:
488 		break;
489 	case PF_POOL_BITMASK:
490 		printf(" bitmask");
491 		break;
492 	case PF_POOL_RANDOM:
493 		printf(" random");
494 		break;
495 	case PF_POOL_SRCHASH:
496 		printf(" source-hash 0x%08x%08x%08x%08x",
497 		    pool->key.key32[0], pool->key.key32[1],
498 		    pool->key.key32[2], pool->key.key32[3]);
499 		break;
500 	case PF_POOL_ROUNDROBIN:
501 		printf(" round-robin");
502 		break;
503 	}
504 	if (pool->opts & PF_POOL_STICKYADDR)
505 		printf(" sticky-address");
506 	if (pool->opts & PF_POOL_ENDPI)
507 		printf(" endpoint-independent");
508 	if (id == PF_NAT && p1 == 0 && p2 == 0)
509 		printf(" static-port");
510 	if (pool->mape.offset > 0)
511 		printf(" map-e-portset %u/%u/%u",
512 		    pool->mape.offset, pool->mape.psidlen, pool->mape.psid);
513 	if (pool->opts & PF_POOL_IPV6NH)
514 		printf(" prefer-ipv6-nexthop");
515 }
516 
517 void
518 print_status(struct pfctl_status *s, struct pfctl_syncookies *cookies, int opts)
519 {
520 	struct pfctl_status_counter	*c;
521 	char			statline[80], *running;
522 	time_t			runtime;
523 	int			i;
524 	char			buf[PF_MD5_DIGEST_LENGTH * 2 + 1];
525 	static const char	hex[] = "0123456789abcdef";
526 
527 	runtime = time(NULL) - s->since;
528 	running = s->running ? "Enabled" : "Disabled";
529 
530 	if (s->since) {
531 		unsigned int	sec, min, hrs;
532 		time_t		day = runtime;
533 
534 		sec = day % 60;
535 		day /= 60;
536 		min = day % 60;
537 		day /= 60;
538 		hrs = day % 24;
539 		day /= 24;
540 		snprintf(statline, sizeof(statline),
541 		    "Status: %s for %lld days %.2u:%.2u:%.2u",
542 		    running, (long long)day, hrs, min, sec);
543 	} else
544 		snprintf(statline, sizeof(statline), "Status: %s", running);
545 	printf("%-44s", statline);
546 	switch (s->debug) {
547 	case PF_DEBUG_NONE:
548 		printf("%15s\n\n", "Debug: None");
549 		break;
550 	case PF_DEBUG_URGENT:
551 		printf("%15s\n\n", "Debug: Urgent");
552 		break;
553 	case PF_DEBUG_MISC:
554 		printf("%15s\n\n", "Debug: Misc");
555 		break;
556 	case PF_DEBUG_NOISY:
557 		printf("%15s\n\n", "Debug: Loud");
558 		break;
559 	}
560 
561 	if (opts & PF_OPT_VERBOSE) {
562 		printf("Hostid:   0x%08x\n", s->hostid);
563 
564 		for (i = 0; i < PF_MD5_DIGEST_LENGTH; i++) {
565 			buf[i + i] = hex[s->pf_chksum[i] >> 4];
566 			buf[i + i + 1] = hex[s->pf_chksum[i] & 0x0f];
567 		}
568 		buf[i + i] = '\0';
569 		printf("Checksum: 0x%s\n\n", buf);
570 	}
571 
572 	if (s->ifname[0] != 0) {
573 		printf("Interface Stats for %-16s %5s %16s\n",
574 		    s->ifname, "IPv4", "IPv6");
575 		printf("  %-25s %14llu %16llu\n", "Bytes In",
576 		    (unsigned long long)s->bcounters[0][0],
577 		    (unsigned long long)s->bcounters[1][0]);
578 		printf("  %-25s %14llu %16llu\n", "Bytes Out",
579 		    (unsigned long long)s->bcounters[0][1],
580 		    (unsigned long long)s->bcounters[1][1]);
581 		printf("  Packets In\n");
582 		printf("    %-23s %14llu %16llu\n", "Passed",
583 		    (unsigned long long)s->pcounters[0][0][PF_PASS],
584 		    (unsigned long long)s->pcounters[1][0][PF_PASS]);
585 		printf("    %-23s %14llu %16llu\n", "Blocked",
586 		    (unsigned long long)s->pcounters[0][0][PF_DROP],
587 		    (unsigned long long)s->pcounters[1][0][PF_DROP]);
588 		printf("  Packets Out\n");
589 		printf("    %-23s %14llu %16llu\n", "Passed",
590 		    (unsigned long long)s->pcounters[0][1][PF_PASS],
591 		    (unsigned long long)s->pcounters[1][1][PF_PASS]);
592 		printf("    %-23s %14llu %16llu\n\n", "Blocked",
593 		    (unsigned long long)s->pcounters[0][1][PF_DROP],
594 		    (unsigned long long)s->pcounters[1][1][PF_DROP]);
595 	}
596 	printf("%-27s %14s %16s\n", "State Table", "Total", "Rate");
597 	printf("  %-25s %14ju %14s\n", "current entries", s->states, "");
598 	TAILQ_FOREACH(c, &s->fcounters, entry) {
599 		printf("  %-25s %14ju ", c->name, c->counter);
600 		if (runtime > 0)
601 			printf("%14.1f/s\n",
602 			    (double)c->counter / (double)runtime);
603 		else
604 			printf("%14s\n", "");
605 	}
606 	if (opts & PF_OPT_VERBOSE) {
607 		printf("Source Tracking Table\n");
608 		printf("  %-25s %14ju %14s\n", "current entries",
609 		    s->src_nodes, "");
610 		TAILQ_FOREACH(c, &s->scounters, entry) {
611 			printf("  %-25s %14ju ", c->name, c->counter);
612 			if (runtime > 0)
613 				printf("%14.1f/s\n",
614 				    (double)c->counter / (double)runtime);
615 			else
616 				printf("%14s\n", "");
617 		}
618 	}
619 	if (opts & PF_OPT_VERBOSE) {
620 		printf("Fragments\n");
621 		printf("  %-25s %14ju %14s\n", "current entries",
622 		    s->fragments, "");
623 		TAILQ_FOREACH(c, &s->ncounters, entry) {
624 			printf("  %-25s %14ju ", c->name,
625 			    c->counter);
626 			if (runtime > 0)
627 				printf("%14.1f/s\n",
628 				    (double)c->counter / (double)runtime);
629 			else
630 				printf("%14s\n", "");
631 		}
632 	}
633 	printf("Counters\n");
634 	TAILQ_FOREACH(c, &s->counters, entry) {
635 		printf("  %-25s %14ju ", c->name, c->counter);
636 		if (runtime > 0)
637 			printf("%14.1f/s\n",
638 			    (double)c->counter / (double)runtime);
639 		else
640 			printf("%14s\n", "");
641 	}
642 	if (opts & PF_OPT_VERBOSE) {
643 		printf("Limit Counters\n");
644 		TAILQ_FOREACH(c, &s->lcounters, entry) {
645 			printf("  %-25s %14ju ", c->name, c->counter);
646 			if (runtime > 0)
647 				printf("%14.1f/s\n",
648 				    (double)c->counter / (double)runtime);
649 			else
650 				printf("%14s\n", "");
651 		}
652 
653 		printf("Syncookies\n");
654 		assert(cookies->mode <= PFCTL_SYNCOOKIES_ADAPTIVE);
655 		printf("  %-25s %s\n", "mode",
656 		    PFCTL_SYNCOOKIES_MODE_NAMES[cookies->mode]);
657 		printf("  %-25s %s\n", "active",
658 		    s->syncookies_active ? "active" : "inactive");
659 		if (opts & PF_OPT_VERBOSE2) {
660 			printf("  %-25s %d %%\n", "highwater", cookies->highwater);
661 			printf("  %-25s %d %%\n", "lowwater", cookies->lowwater);
662 			printf("  %-25s %d\n", "halfopen states", cookies->halfopen_states);
663 		}
664 		printf("Reassemble %24s %s\n",
665 		    s->reass & PF_REASS_ENABLED ? "yes" : "no",
666 		    s->reass & PF_REASS_NODF ? "no-df" : ""
667 		);
668 	}
669 }
670 
671 void
672 print_running(struct pfctl_status *status)
673 {
674 	printf("%s\n", status->running ? "Enabled" : "Disabled");
675 }
676 
677 void
678 print_src_node(struct pfctl_src_node *sn, int opts)
679 {
680 	struct pf_addr_wrap aw;
681 	uint64_t min, sec;
682 	const char *sn_type_names[] = PF_SN_TYPE_NAMES;
683 
684 	memset(&aw, 0, sizeof(aw));
685 	if (sn->af == AF_INET)
686 		aw.v.a.mask.addr32[0] = 0xffffffff;
687 	else
688 		memset(&aw.v.a.mask, 0xff, sizeof(aw.v.a.mask));
689 
690 	aw.v.a.addr = sn->addr;
691 	print_addr(&aw, sn->af, opts & PF_OPT_VERBOSE2);
692 	printf(" -> ");
693 	aw.v.a.addr = sn->raddr;
694 	print_addr(&aw, sn->raf, opts & PF_OPT_VERBOSE2);
695 	printf(" ( states %u, connections %u, rate %u.%u/%us )\n", sn->states,
696 	    sn->conn, sn->conn_rate.count / 1000,
697 	    (sn->conn_rate.count % 1000) / 100, sn->conn_rate.seconds);
698 	if (opts & PF_OPT_VERBOSE) {
699 		sec = sn->creation % 60;
700 		sn->creation /= 60;
701 		min = sn->creation % 60;
702 		sn->creation /= 60;
703 		printf("   age %.2" PRIu64 ":%.2" PRIu64 ":%.2" PRIu64,
704 		    sn->creation, min, sec);
705 		if (sn->states == 0) {
706 			sec = sn->expire % 60;
707 			sn->expire /= 60;
708 			min = sn->expire % 60;
709 			sn->expire /= 60;
710 			printf(", expires in %.2" PRIu64 ":%.2" PRIu64 ":%.2" PRIu64,
711 			    sn->expire, min, sec);
712 		}
713 		printf(", %" PRIu64 " pkts, %" PRIu64 " bytes",
714 		    sn->packets[0] + sn->packets[1],
715 		    sn->bytes[0] + sn->bytes[1]);
716 		switch (sn->ruletype) {
717 		case PF_NAT:
718 			if (sn->rule != -1)
719 				printf(", nat rule %u", sn->rule);
720 			break;
721 		case PF_RDR:
722 			if (sn->rule != -1)
723 				printf(", rdr rule %u", sn->rule);
724 			break;
725 		case PF_PASS:
726 		case PF_MATCH:
727 			if (sn->rule != -1)
728 				printf(", filter rule %u", sn->rule);
729 			break;
730 		}
731 		printf(", %s", sn_type_names[sn->type]);
732 		printf("\n");
733 	}
734 }
735 
736 static void
737 print_eth_addr(const struct pfctl_eth_addr *a)
738 {
739 	int i, masklen = ETHER_ADDR_LEN * 8;
740 	bool seen_unset = false;
741 
742 	for (i = 0; i < ETHER_ADDR_LEN; i++) {
743 		if (a->addr[i] != 0)
744 			break;
745 	}
746 
747 	/* Unset, so don't print anything. */
748 	if (i == ETHER_ADDR_LEN)
749 		return;
750 
751 	printf("%s%02x:%02x:%02x:%02x:%02x:%02x", a->neg ? "! " : "",
752 	    a->addr[0], a->addr[1], a->addr[2], a->addr[3], a->addr[4],
753 	    a->addr[5]);
754 
755 	for (i = 0; i < (ETHER_ADDR_LEN * 8); i++) {
756 		bool isset = a->mask[i / 8] & (1 << i % 8);
757 
758 		if (! seen_unset) {
759 			if (isset)
760 				continue;
761 			seen_unset = true;
762 			masklen = i;
763 		} else {
764 			/* Not actually a continuous mask, so print the whole
765 			 * thing. */
766 			if (isset)
767 				break;
768 			continue;
769 		}
770 	}
771 
772 	if (masklen == (ETHER_ADDR_LEN * 8))
773 		return;
774 
775 	if (i == (ETHER_ADDR_LEN * 8)) {
776 		printf("/%d", masklen);
777 		return;
778 	}
779 
780 	printf("&%02x:%02x:%02x:%02x:%02x:%02x",
781 	    a->mask[0], a->mask[1], a->mask[2], a->mask[3], a->mask[4],
782 	    a->mask[5]);
783 }
784 
785 void
786 print_eth_rule(struct pfctl_eth_rule *r, const char *anchor_call,
787     int rule_numbers)
788 {
789 	static const char *actiontypes[] = { "pass", "block", "", "", "", "",
790 	    "", "", "", "", "", "", "match" };
791 
792 	int i;
793 
794 	if (rule_numbers)
795 		printf("@%u ", r->nr);
796 
797 	printf("ether ");
798 	if (anchor_call[0]) {
799 		if (anchor_call[0] == '_') {
800 			printf("anchor");
801 		} else
802 			printf("anchor \"%s\"", anchor_call);
803 	} else {
804 		printf("%s", actiontypes[r->action]);
805 	}
806 	if (r->direction == PF_IN)
807 		printf(" in");
808 	else if (r->direction == PF_OUT)
809 		printf(" out");
810 
811 	if (r->quick)
812 		printf(" quick");
813 	if (r->ifname[0]) {
814 		if (r->ifnot)
815 			printf(" on ! %s", r->ifname);
816 		else
817 			printf(" on %s", r->ifname);
818 	}
819 	if (r->bridge_to[0])
820 		printf(" bridge-to %s", r->bridge_to);
821 	if (r->proto)
822 		printf(" proto 0x%04x", r->proto);
823 
824 	if (r->src.isset) {
825 		printf(" from ");
826 		print_eth_addr(&r->src);
827 	}
828 	if (r->dst.isset) {
829 		printf(" to ");
830 		print_eth_addr(&r->dst);
831 	}
832 	printf(" l3");
833 	print_fromto(&r->ipsrc, PF_OSFP_ANY, &r->ipdst,
834 	    r->proto == ETHERTYPE_IP ? AF_INET : AF_INET6, 0,
835 	    0, 0);
836 
837 	i = 0;
838 	while (r->label[i][0])
839 		printf(" label \"%s\"", r->label[i++]);
840 	if (r->ridentifier)
841 		printf(" ridentifier %u", r->ridentifier);
842 
843 	if (r->qname[0])
844 		printf(" queue %s", r->qname);
845 	if (r->tagname[0])
846 		printf(" tag %s", r->tagname);
847 	if (r->match_tagname[0]) {
848 		if (r->match_tag_not)
849 			printf(" !");
850 		printf(" tagged %s", r->match_tagname);
851 	}
852 	if (r->dnpipe)
853 		printf(" %s %d",
854 		    r->dnflags & PFRULE_DN_IS_PIPE ? "dnpipe" : "dnqueue",
855 		    r->dnpipe);
856 }
857 
858 void
859 print_statelim(const struct pfctl_state_lim *ioc)
860 {
861 	printf("state limiter %s id %u limit %u", ioc->name, ioc->id,
862 	    ioc->limit);
863 	if (ioc->rate.limit != 0)
864 		printf(" rate %u/%u", ioc->rate.limit, ioc->rate.seconds);
865 
866 	printf("\n");
867 }
868 
869 void
870 print_sourcelim(const struct pfctl_source_lim *ioc)
871 {
872 	printf("source limiter %s id %u entries %u limit %u", ioc->name,
873 	    ioc->id, ioc->entries, ioc->limit);
874 	if (ioc->rate.limit != 0)
875 		printf(" rate %u/%u", ioc->rate.limit, ioc->rate.seconds);
876 	if (ioc->overload_tblname[0] != '\0') {
877 		printf(" table <%s> above %u", ioc->overload_tblname,
878 		    ioc->overload_hwm);
879 		if (ioc->overload_lwm)
880 			printf(" below %u", ioc->overload_lwm);
881 	}
882 	if (ioc->inet_prefix < 32)
883 		printf(" inet mask %u", ioc->inet_prefix);
884 	if (ioc->inet6_prefix < 128)
885 		printf(" inet6 mask %u", ioc->inet6_prefix);
886 
887 	printf("\n");
888 }
889 
890 void
891 print_rule(struct pfctl_rule *r, const char *anchor_call, int opts, int numeric)
892 {
893 	static const char *actiontypes[] = { "pass", "block", "scrub",
894 	    "no scrub", "nat", "no nat", "binat", "no binat", "rdr", "no rdr",
895 	    "synproxy drop", "defer", "match", "af-rt", "route-to" };
896 	static const char *anchortypes[] = { "anchor", "anchor", "anchor",
897 	    "anchor", "nat-anchor", "nat-anchor", "binat-anchor",
898 	    "binat-anchor", "rdr-anchor", "rdr-anchor" };
899 	int	 i, ropts;
900 	int	 verbose = opts & (PF_OPT_VERBOSE2 | PF_OPT_DEBUG);
901 	char	*p;
902 
903 	if ((r->rule_flag & PFRULE_EXPIRED) && (!verbose))
904 		return;
905 
906 	if (verbose)
907 		printf("@%d ", r->nr);
908 	if (anchor_call[0]) {
909 		if (r->action >= nitems(anchortypes)) {
910 			printf("anchor(%d)", r->action);
911 		} else {
912 			p = strrchr(anchor_call, '/');
913 			if (p ? p[1] == '_' : anchor_call[0] == '_')
914 				printf("%s", anchortypes[r->action]);
915 			else
916 				printf("%s \"%s\"", anchortypes[r->action],
917 				    anchor_call);
918 		}
919 	} else {
920 		if (r->action >= nitems(actiontypes))
921 			printf("action(%d)", r->action);
922 		else {
923 			printf("%s", actiontypes[r->action]);
924 			if (r->natpass)
925 				printf(" pass");
926 		}
927 	}
928 	if (r->action == PF_DROP) {
929 		if (r->rule_flag & PFRULE_RETURN)
930 			printf(" return");
931 		else if (r->rule_flag & PFRULE_RETURNRST) {
932 			if (!r->return_ttl)
933 				printf(" return-rst");
934 			else
935 				printf(" return-rst(ttl %d)", r->return_ttl);
936 		} else if (r->rule_flag & PFRULE_RETURNICMP) {
937 			const struct icmpcodeent	*ic, *ic6;
938 
939 			ic = geticmpcodebynumber(r->return_icmp >> 8,
940 			    r->return_icmp & 255, AF_INET);
941 			ic6 = geticmpcodebynumber(r->return_icmp6 >> 8,
942 			    r->return_icmp6 & 255, AF_INET6);
943 
944 			switch (r->af) {
945 			case AF_INET:
946 				printf(" return-icmp");
947 				if (ic == NULL)
948 					printf("(%u)", r->return_icmp & 255);
949 				else
950 					printf("(%s)", ic->name);
951 				break;
952 			case AF_INET6:
953 				printf(" return-icmp6");
954 				if (ic6 == NULL)
955 					printf("(%u)", r->return_icmp6 & 255);
956 				else
957 					printf("(%s)", ic6->name);
958 				break;
959 			default:
960 				printf(" return-icmp");
961 				if (ic == NULL)
962 					printf("(%u, ", r->return_icmp & 255);
963 				else
964 					printf("(%s, ", ic->name);
965 				if (ic6 == NULL)
966 					printf("%u)", r->return_icmp6 & 255);
967 				else
968 					printf("%s)", ic6->name);
969 				break;
970 			}
971 		} else
972 			printf(" drop");
973 	}
974 	if (r->direction == PF_IN)
975 		printf(" in");
976 	else if (r->direction == PF_OUT)
977 		printf(" out");
978 	if (r->log) {
979 		printf(" log");
980 		if (r->log & ~PF_LOG || r->logif) {
981 			int count = 0;
982 
983 			printf(" (");
984 			if (r->log & PF_LOG_ALL)
985 				printf("%sall", count++ ? ", " : "");
986 			if (r->log & PF_LOG_MATCHES)
987 				printf("%smatches", count++ ? ", " : "");
988 			if (r->log & PF_LOG_USER)
989 				printf("%suser", count++ ? ", " : "");
990 			if (r->logif)
991 				printf("%sto pflog%u", count++ ? ", " : "",
992 				    r->logif);
993 			printf(")");
994 		}
995 	}
996 	if (r->quick)
997 		printf(" quick");
998 	if (r->ifname[0]) {
999 		if (r->ifnot)
1000 			printf(" on ! %s", r->ifname);
1001 		else
1002 			printf(" on %s", r->ifname);
1003 	}
1004 	if (r->rt) {
1005 		if (r->rt == PF_ROUTETO)
1006 			printf(" route-to");
1007 		else if (r->rt == PF_REPLYTO)
1008 			printf(" reply-to");
1009 		else if (r->rt == PF_DUPTO)
1010 			printf(" dup-to");
1011 		printf(" ");
1012 		print_pool(&r->route, 0, 0, PF_PASS);
1013 	}
1014 	if (r->af) {
1015 		if (r->af == AF_INET)
1016 			printf(" inet");
1017 		else
1018 			printf(" inet6");
1019 	}
1020 	if (r->proto) {
1021 		const char *protoname;
1022 
1023 		if ((protoname = pfctl_proto2name(r->proto)) != NULL)
1024 			printf(" proto %s", protoname);
1025 		else
1026 			printf(" proto %u", r->proto);
1027 	}
1028 	print_fromto(&r->src, r->os_fingerprint, &r->dst, r->af, r->proto,
1029 	    opts, numeric);
1030 	if (r->rcv_ifname[0])
1031 		printf(" %sreceived-on %s", r->rcvifnot ? "!" : "",
1032 		    r->rcv_ifname);
1033 	if (r->uid.op)
1034 		print_ugid(r->uid.op, r->uid.uid[0], r->uid.uid[1], "user");
1035 	if (r->gid.op)
1036 		print_ugid(r->gid.op, r->gid.gid[0], r->gid.gid[1], "group");
1037 	if (r->flags || r->flagset) {
1038 		printf(" flags ");
1039 		print_flags(r->flags);
1040 		printf("/");
1041 		print_flags(r->flagset);
1042 	} else if ((r->action == PF_PASS || r->action == PF_MATCH) &&
1043 	    (!r->proto || r->proto == IPPROTO_TCP) &&
1044 	    !(r->rule_flag & PFRULE_FRAGMENT) &&
1045 	    !anchor_call[0] && r->keep_state)
1046 		printf(" flags any");
1047 	if (r->type) {
1048 		const struct icmptypeent	*it;
1049 
1050 		it = geticmptypebynumber(r->type-1, r->af);
1051 		if (r->af != AF_INET6)
1052 			printf(" icmp-type");
1053 		else
1054 			printf(" icmp6-type");
1055 		if (it != NULL)
1056 			printf(" %s", it->name);
1057 		else
1058 			printf(" %u", r->type-1);
1059 		if (r->code) {
1060 			const struct icmpcodeent	*ic;
1061 
1062 			ic = geticmpcodebynumber(r->type-1, r->code-1, r->af);
1063 			if (ic != NULL)
1064 				printf(" code %s", ic->name);
1065 			else
1066 				printf(" code %u", r->code-1);
1067 		}
1068 	}
1069 	if (r->tos)
1070 		printf(" tos 0x%2.2x", r->tos);
1071 	if (r->prio)
1072 		printf(" prio %u", r->prio == PF_PRIO_ZERO ? 0 : r->prio);
1073 	if (r->pktrate.limit)
1074 		printf(" max-pkt-rate %u/%u", r->pktrate.limit,
1075 		    r->pktrate.seconds);
1076 	if (r->max_pkt_size)
1077 		printf( " max-pkt-size %u", r->max_pkt_size);
1078 	if (r->scrub_flags & PFSTATE_SETMASK) {
1079 		char *comma = "";
1080 		printf(" set (");
1081 		if (r->scrub_flags & PFSTATE_SETPRIO) {
1082 			if (r->set_prio[0] == r->set_prio[1])
1083 				printf("%s prio %u", comma, r->set_prio[0]);
1084 			else
1085 				printf("%s prio(%u, %u)", comma, r->set_prio[0],
1086 				    r->set_prio[1]);
1087 			comma = ",";
1088 		}
1089 		if (r->scrub_flags & PFSTATE_SETTOS) {
1090 			printf("%s tos 0x%2.2x", comma, r->set_tos);
1091 			comma = ",";
1092 		}
1093 		printf(" )");
1094 	}
1095 	if (!r->keep_state && r->action == PF_PASS && !anchor_call[0])
1096 		printf(" no state");
1097 	else if (r->keep_state == PF_STATE_NORMAL)
1098 		printf(" keep state");
1099 	else if (r->keep_state == PF_STATE_MODULATE)
1100 		printf(" modulate state");
1101 	else if (r->keep_state == PF_STATE_SYNPROXY)
1102 		printf(" synproxy state");
1103 	if (r->prob) {
1104 		char	buf[20];
1105 
1106 		snprintf(buf, sizeof(buf), "%f", r->prob*100.0/(UINT_MAX+1.0));
1107 		for (i = strlen(buf)-1; i > 0; i--) {
1108 			if (buf[i] == '0')
1109 				buf[i] = '\0';
1110 			else {
1111 				if (buf[i] == '.')
1112 					buf[i] = '\0';
1113 				break;
1114 			}
1115 		}
1116 		printf(" probability %s%%", buf);
1117 	}
1118 	if (r->statelim.id != PF_STATELIM_ID_NONE) {
1119 #if 0 /* XXX need pf to find statelims */
1120 		struct pfctl_statelim *stlim =
1121 		    pfctl_get_statelim_id(pf, r->statelim);
1122 
1123 		if (stlim != NULL)
1124 			printf(" state limiter %s", stlim->ioc.name);
1125 		else
1126 #endif
1127 		printf(" state limiter id %u (%s)", r->statelim.id,
1128 		    (r->statelim.limiter_action == PF_LIMITER_BLOCK) ?
1129 		    "block" : "no-match");
1130 	}
1131 	if (r->sourcelim.id != PF_SOURCELIM_ID_NONE) {
1132 #if 0 /* XXX need pf to find sourcelims */
1133 		struct pfctl_sourcelim *srlim =
1134 		    pfctl_get_sourcelim_id(pf, r->sourcelim);
1135 
1136 		if (srlim != NULL)
1137 			printf(" source limiter %s", srlim->ioc.name);
1138 		else
1139 #endif
1140 		printf(" source limiter id %u (%s)", r->sourcelim.id,
1141 		    (r->sourcelim.limiter_action == PF_LIMITER_BLOCK) ?
1142 		    "block" : "no-match");
1143 	}
1144 
1145 	ropts = 0;
1146 	if (r->max_states || r->max_src_nodes || r->max_src_states)
1147 		ropts = 1;
1148 	if (r->rule_flag & PFRULE_NOSYNC)
1149 		ropts = 1;
1150 	if (r->rule_flag & PFRULE_SRCTRACK)
1151 		ropts = 1;
1152 	if (r->rule_flag & PFRULE_IFBOUND)
1153 		ropts = 1;
1154 	if (r->rule_flag & PFRULE_STATESLOPPY)
1155 		ropts = 1;
1156 	if (r->rule_flag & PFRULE_PFLOW)
1157 		ropts = 1;
1158 	for (i = 0; !ropts && i < PFTM_MAX; ++i)
1159 		if (r->timeout[i])
1160 			ropts = 1;
1161 	if (ropts) {
1162 		printf(" (");
1163 		if (r->max_states) {
1164 			printf("max %u", r->max_states);
1165 			ropts = 0;
1166 		}
1167 		if (r->rule_flag & PFRULE_NOSYNC) {
1168 			if (!ropts)
1169 				printf(", ");
1170 			printf("no-sync");
1171 			ropts = 0;
1172 		}
1173 		if (r->rule_flag & PFRULE_SRCTRACK) {
1174 			if (!ropts)
1175 				printf(", ");
1176 			printf("source-track");
1177 			if (r->rule_flag & PFRULE_RULESRCTRACK)
1178 				printf(" rule");
1179 			else
1180 				printf(" global");
1181 			ropts = 0;
1182 		}
1183 		if (r->max_src_states) {
1184 			if (!ropts)
1185 				printf(", ");
1186 			printf("max-src-states %u", r->max_src_states);
1187 			ropts = 0;
1188 		}
1189 		if (r->max_src_conn) {
1190 			if (!ropts)
1191 				printf(", ");
1192 			printf("max-src-conn %u", r->max_src_conn);
1193 			ropts = 0;
1194 		}
1195 		if (r->max_src_conn_rate.limit) {
1196 			if (!ropts)
1197 				printf(", ");
1198 			printf("max-src-conn-rate %u/%u",
1199 			    r->max_src_conn_rate.limit,
1200 			    r->max_src_conn_rate.seconds);
1201 			ropts = 0;
1202 		}
1203 		if (r->max_src_nodes) {
1204 			if (!ropts)
1205 				printf(", ");
1206 			printf("max-src-nodes %u", r->max_src_nodes);
1207 			ropts = 0;
1208 		}
1209 		if (r->overload_tblname[0]) {
1210 			if (!ropts)
1211 				printf(", ");
1212 			printf("overload <%s>", r->overload_tblname);
1213 			if (r->flush)
1214 				printf(" flush");
1215 			if (r->flush & PF_FLUSH_GLOBAL)
1216 				printf(" global");
1217 		}
1218 		if (r->rule_flag & PFRULE_IFBOUND) {
1219 			if (!ropts)
1220 				printf(", ");
1221 			printf("if-bound");
1222 			ropts = 0;
1223 		}
1224 		if (r->rule_flag & PFRULE_STATESLOPPY) {
1225 			if (!ropts)
1226 				printf(", ");
1227 			printf("sloppy");
1228 			ropts = 0;
1229 		}
1230 		if (r->rule_flag & PFRULE_PFLOW) {
1231 			if (!ropts)
1232 				printf(", ");
1233 			printf("pflow");
1234 			ropts = 0;
1235 		}
1236 		for (i = 0; i < PFTM_MAX; ++i)
1237 			if (r->timeout[i]) {
1238 				int j;
1239 
1240 				if (!ropts)
1241 					printf(", ");
1242 				ropts = 0;
1243 				for (j = 0; pf_timeouts[j].name != NULL;
1244 				    ++j)
1245 					if (pf_timeouts[j].timeout == i)
1246 						break;
1247 				printf("%s %u", pf_timeouts[j].name == NULL ?
1248 				    "inv.timeout" : pf_timeouts[j].name,
1249 				    r->timeout[i]);
1250 			}
1251 		printf(")");
1252 	}
1253 	if (r->allow_opts)
1254 		printf(" allow-opts");
1255 	if (r->rule_flag & PFRULE_FRAGMENT)
1256 		printf(" fragment");
1257 	if (r->action == PF_SCRUB) {
1258 		/* Scrub flags for old-style scrub. */
1259 		if (r->rule_flag & PFRULE_NODF)
1260 			printf(" no-df");
1261 		if (r->rule_flag & PFRULE_RANDOMID)
1262 			printf(" random-id");
1263 		if (r->min_ttl)
1264 			printf(" min-ttl %d", r->min_ttl);
1265 		if (r->max_mss)
1266 			printf(" max-mss %d", r->max_mss);
1267 		if (r->rule_flag & PFRULE_SET_TOS)
1268 			printf(" set-tos 0x%2.2x", r->set_tos);
1269 		if (r->rule_flag & PFRULE_REASSEMBLE_TCP)
1270 			printf(" reassemble tcp");
1271 		/* The PFRULE_FRAGMENT_NOREASS is set on all rules by default! */
1272 		printf(" fragment %sreassemble",
1273 		    r->rule_flag & PFRULE_FRAGMENT_NOREASS ? "no " : "");
1274 	} else if (r->scrub_flags & PFSTATE_SCRUBMASK || r->min_ttl || r->max_mss) {
1275 		/* Scrub actions on normal rules. */
1276 		printf(" scrub(");
1277 		if (r->scrub_flags & PFSTATE_NODF)
1278 			printf(" no-df");
1279 		if (r->scrub_flags & PFSTATE_RANDOMID)
1280 			printf(" random-id");
1281 		if (r->min_ttl)
1282 			printf(" min-ttl %d", r->min_ttl);
1283 		if (r->scrub_flags & PFSTATE_SETTOS)
1284 			printf(" set-tos 0x%2.2x", r->set_tos);
1285 		if (r->scrub_flags & PFSTATE_SCRUB_TCP)
1286 			printf(" reassemble tcp");
1287 		if (r->max_mss)
1288 			printf(" max-mss %d", r->max_mss);
1289 		printf(")");
1290 	}
1291 	i = 0;
1292 	while (r->label[i][0])
1293 		printf(" label \"%s\"", r->label[i++]);
1294 	if (r->ridentifier)
1295 		printf(" ridentifier %u", r->ridentifier);
1296 	/* Only dnrpipe as we might do (0, 42) to only queue return traffic. */
1297 	if (r->dnrpipe)
1298 		printf(" %s(%d, %d)",
1299 		    r->free_flags & PFRULE_DN_IS_PIPE ? "dnpipe" : "dnqueue",
1300 		    r->dnpipe, r->dnrpipe);
1301 	else if (r->dnpipe)
1302 		printf(" %s %d",
1303 		    r->free_flags & PFRULE_DN_IS_PIPE ? "dnpipe" : "dnqueue",
1304 		    r->dnpipe);
1305 	if (r->rule_flag & PFRULE_ONCE)
1306 		printf(" once");
1307 	if (r->qname[0] && r->pqname[0])
1308 		printf(" queue(%s, %s)", r->qname, r->pqname);
1309 	else if (r->qname[0])
1310 		printf(" queue %s", r->qname);
1311 	if (r->tagname[0])
1312 		printf(" tag %s", r->tagname);
1313 	if (r->match_tagname[0]) {
1314 		if (r->match_tag_not)
1315 			printf(" !");
1316 		printf(" tagged %s", r->match_tagname);
1317 	}
1318 	if (r->rtableid != -1)
1319 		printf(" rtable %u", r->rtableid);
1320 	if (r->divert.port) {
1321 #ifdef __FreeBSD__
1322 		printf(" divert-to %u", ntohs(r->divert.port));
1323 #else
1324 		if (PF_AZERO(&r->divert.addr, r->af)) {
1325 			printf(" divert-reply");
1326 		} else {
1327 			printf(" divert-to ");
1328 			print_addr_str(r->af, &r->divert.addr);
1329 			printf(" port %u", ntohs(r->divert.port));
1330 		}
1331 #endif
1332 	}
1333 	if (anchor_call[0])
1334 		return;
1335 	if (r->action == PF_NAT || r->action == PF_BINAT || r->action == PF_RDR) {
1336 		printf(" -> ");
1337 		print_pool(&r->rdr, r->rdr.proxy_port[0],
1338 		    r->rdr.proxy_port[1], r->action);
1339 	} else {
1340 		if (!TAILQ_EMPTY(&r->nat.list)) {
1341 			if (r->rule_flag & PFRULE_AFTO) {
1342 				printf(" af-to %s from ", r->naf == AF_INET ? "inet" : (r->naf == AF_INET6 ? "inet6" : "? "));
1343 			} else {
1344 				printf(" nat-to ");
1345 			}
1346 			print_pool(&r->nat, r->nat.proxy_port[0],
1347 			    r->nat.proxy_port[1], PF_NAT);
1348 		}
1349 		if (!TAILQ_EMPTY(&r->rdr.list)) {
1350 			if (r->rule_flag & PFRULE_AFTO) {
1351 				printf(" to ");
1352 			} else {
1353 				printf(" rdr-to ");
1354 			}
1355 			print_pool(&r->rdr, r->rdr.proxy_port[0],
1356 			    r->rdr.proxy_port[1], PF_RDR);
1357 		}
1358 	}
1359 
1360 	if (r->rule_flag & PFRULE_EXPIRED) {
1361 		printf(" # expired");
1362 
1363 		if (r->exptime != 0)
1364 			printf(" %s", ctime(&r->exptime));
1365 	}
1366 }
1367 
1368 void
1369 print_tabledef(const char *name, int flags, int addrs,
1370     struct node_tinithead *nodes)
1371 {
1372 	struct node_tinit	*ti, *nti;
1373 	struct node_host	*h;
1374 
1375 	printf("table <%s>", name);
1376 	if (flags & PFR_TFLAG_CONST)
1377 		printf(" const");
1378 	if (flags & PFR_TFLAG_PERSIST)
1379 		printf(" persist");
1380 	if (flags & PFR_TFLAG_COUNTERS)
1381 		printf(" counters");
1382 	SIMPLEQ_FOREACH(ti, nodes, entries) {
1383 		if (ti->file) {
1384 			printf(" file \"%s\"", ti->file);
1385 			continue;
1386 		}
1387 		printf(" {");
1388 		for (;;) {
1389 			for (h = ti->host; h != NULL; h = h->next) {
1390 				printf(h->not ? " !" : " ");
1391 				print_addr(&h->addr, h->af, 0);
1392 			}
1393 			nti = SIMPLEQ_NEXT(ti, entries);
1394 			if (nti != NULL && nti->file == NULL)
1395 				ti = nti;	/* merge lists */
1396 			else
1397 				break;
1398 		}
1399 		printf(" }");
1400 	}
1401 	if (addrs && SIMPLEQ_EMPTY(nodes))
1402 		printf(" { }");
1403 	printf("\n");
1404 }
1405 
1406 int
1407 parse_flags(char *s)
1408 {
1409 	char		*p, *q;
1410 	uint16_t	 f = 0;
1411 
1412 	for (p = s; *p; p++) {
1413 		if ((q = strchr(tcpflags, *p)) == NULL)
1414 			return -1;
1415 		else
1416 			f |= 1 << (q - tcpflags);
1417 	}
1418 	return (f ? f : TH_FLAGS);
1419 }
1420 
1421 void
1422 set_ipmask(struct node_host *h, int bb)
1423 {
1424 	struct pf_addr	*m, *n;
1425 	int		 i, j = 0;
1426 	uint8_t		 b;
1427 
1428 	m = &h->addr.v.a.mask;
1429 	memset(m, 0, sizeof(*m));
1430 
1431 	if (bb == -1)
1432 		b = h->af == AF_INET ? 32 : 128;
1433 	else
1434 		b = bb;
1435 
1436 	while (b >= 32) {
1437 		m->addr32[j++] = 0xffffffff;
1438 		b -= 32;
1439 	}
1440 	for (i = 31; i > 31-b; --i)
1441 		m->addr32[j] |= (1 << i);
1442 	if (b)
1443 		m->addr32[j] = htonl(m->addr32[j]);
1444 
1445 	/* Mask off bits of the address that will never be used. */
1446 	n = &h->addr.v.a.addr;
1447 	if (h->addr.type == PF_ADDR_ADDRMASK)
1448 		for (i = 0; i < 4; i++)
1449 			n->addr32[i] = n->addr32[i] & m->addr32[i];
1450 }
1451 
1452 int
1453 check_netmask(struct node_host *h, sa_family_t af)
1454 {
1455 	struct node_host	*n = NULL;
1456 	struct pf_addr		*m;
1457 
1458 	for (n = h; n != NULL; n = n->next) {
1459 		if (h->addr.type == PF_ADDR_TABLE)
1460 			continue;
1461 		m = &h->addr.v.a.mask;
1462 		/* netmasks > 32 bit are invalid on v4 */
1463 		if (af == AF_INET &&
1464 		    (m->addr32[1] || m->addr32[2] || m->addr32[3])) {
1465 			fprintf(stderr, "netmask %u invalid for IPv4 address\n",
1466 			    unmask(m));
1467 			return (1);
1468 		}
1469 	}
1470 	return (0);
1471 }
1472 
1473 struct node_host *
1474 gen_dynnode(struct node_host *h, sa_family_t af)
1475 {
1476 	struct node_host	*n;
1477 
1478 	if (h->addr.type != PF_ADDR_DYNIFTL)
1479 		return (NULL);
1480 
1481 	if ((n = calloc(1, sizeof(*n))) == NULL)
1482 		return (NULL);
1483 	bcopy(h, n, sizeof(*n));
1484 	n->ifname = NULL;
1485 	n->next = NULL;
1486 	n->tail = NULL;
1487 
1488 	/* fix up netmask */
1489 	if (af == AF_INET && unmask(&n->addr.v.a.mask) > 32)
1490 		set_ipmask(n, 32);
1491 
1492 	return (n);
1493 }
1494 
1495 /* interface lookup routines */
1496 
1497 static struct node_host	*iftab;
1498 
1499 /*
1500  * Retrieve the list of groups this interface is a member of and make sure
1501  * each group is in the group map.
1502  */
1503 static void
1504 ifa_add_groups_to_map(char *ifa_name)
1505 {
1506 	int			 s, len;
1507 	struct ifgroupreq	 ifgr;
1508 	struct ifg_req		*ifg;
1509 
1510 	s = get_query_socket();
1511 
1512 	/* Get size of group list for this interface */
1513 	memset(&ifgr, 0, sizeof(ifgr));
1514 	strlcpy(ifgr.ifgr_name, ifa_name, IFNAMSIZ);
1515 	if (ioctl(s, SIOCGIFGROUP, (caddr_t)&ifgr) == -1)
1516 		err(1, "SIOCGIFGROUP");
1517 
1518 	/* Retrieve group list for this interface */
1519 	len = ifgr.ifgr_len;
1520 	ifgr.ifgr_groups =
1521 	    (struct ifg_req *)calloc(len / sizeof(struct ifg_req),
1522 		sizeof(struct ifg_req));
1523 	if (ifgr.ifgr_groups == NULL)
1524 		err(1, "calloc");
1525 	if (ioctl(s, SIOCGIFGROUP, (caddr_t)&ifgr) == -1)
1526 		err(1, "SIOCGIFGROUP");
1527 
1528 	ifg = ifgr.ifgr_groups;
1529 	for (; ifg && len >= sizeof(struct ifg_req); ifg++) {
1530 		len -= sizeof(struct ifg_req);
1531 		if (strcmp(ifg->ifgrq_group, "all")) {
1532 			ENTRY	 		 item;
1533 			ENTRY			*ret_item;
1534 			int			*answer;
1535 
1536 			item.key = ifg->ifgrq_group;
1537 			if (hsearch_r(item, FIND, &ret_item, &isgroup_map) == 0) {
1538 				struct ifgroupreq	 ifgr2;
1539 
1540 				/* Don't know the answer yet */
1541 				if ((answer = malloc(sizeof(int))) == NULL)
1542 					err(1, "malloc");
1543 
1544 				bzero(&ifgr2, sizeof(ifgr2));
1545 				strlcpy(ifgr2.ifgr_name, ifg->ifgrq_group,
1546 				    sizeof(ifgr2.ifgr_name));
1547 				if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr2) == 0)
1548 					*answer = ifgr2.ifgr_len;
1549 				else
1550 					*answer = 0;
1551 
1552 				item.key = strdup(ifg->ifgrq_group);
1553 				item.data = answer;
1554 				if (hsearch_r(item, ENTER, &ret_item,
1555 					&isgroup_map) == 0)
1556 					err(1, "interface group query response"
1557 					    " map insert");
1558 			}
1559 		}
1560 	}
1561 	free(ifgr.ifgr_groups);
1562 }
1563 
1564 void
1565 ifa_load(void)
1566 {
1567 	struct ifaddrs		*ifap, *ifa;
1568 	struct node_host	*n = NULL, *h = NULL;
1569 
1570 	if (getifaddrs(&ifap) < 0)
1571 		err(1, "getifaddrs");
1572 
1573 	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
1574 		if (ifa->ifa_addr == NULL ||
1575 		    !(ifa->ifa_addr->sa_family == AF_INET ||
1576 		    ifa->ifa_addr->sa_family == AF_INET6 ||
1577 		    ifa->ifa_addr->sa_family == AF_LINK))
1578 				continue;
1579 		n = calloc(1, sizeof(struct node_host));
1580 		if (n == NULL)
1581 			err(1, "%s: calloc", __func__);
1582 		n->af = ifa->ifa_addr->sa_family;
1583 		n->ifa_flags = ifa->ifa_flags;
1584 #ifdef __KAME__
1585 		if (n->af == AF_INET6 &&
1586 		    IN6_IS_ADDR_LINKLOCAL(&((struct sockaddr_in6 *)
1587 		    ifa->ifa_addr)->sin6_addr) &&
1588 		    ((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_scope_id ==
1589 		    0) {
1590 			struct sockaddr_in6	*sin6;
1591 
1592 			sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
1593 			sin6->sin6_scope_id = sin6->sin6_addr.s6_addr[2] << 8 |
1594 			    sin6->sin6_addr.s6_addr[3];
1595 			sin6->sin6_addr.s6_addr[2] = 0;
1596 			sin6->sin6_addr.s6_addr[3] = 0;
1597 		}
1598 #endif
1599 		n->ifindex = 0;
1600 		if (n->af == AF_LINK) {
1601 			n->ifindex = ((struct sockaddr_dl *)
1602 			    ifa->ifa_addr)->sdl_index;
1603 			ifa_add_groups_to_map(ifa->ifa_name);
1604 		} else {
1605 			copy_satopfaddr(&n->addr.v.a.addr, ifa->ifa_addr);
1606 			ifa->ifa_netmask->sa_family = ifa->ifa_addr->sa_family;
1607 			copy_satopfaddr(&n->addr.v.a.mask, ifa->ifa_netmask);
1608 			if (ifa->ifa_flags & IFF_BROADCAST &&
1609 			    ifa->ifa_broadaddr != NULL &&
1610 			    ifa->ifa_broadaddr->sa_len != 0) {
1611 				ifa->ifa_broadaddr->sa_family =
1612 				    ifa->ifa_addr->sa_family;
1613 				ifa->ifa_broadaddr->sa_family = ifa->ifa_addr->sa_family;
1614 				copy_satopfaddr(&n->bcast, ifa->ifa_broadaddr);
1615 			} else if (ifa->ifa_flags & IFF_POINTOPOINT &&
1616 			    ifa->ifa_dstaddr != NULL &&
1617 			    ifa->ifa_dstaddr->sa_len != 0) {
1618 				ifa->ifa_dstaddr->sa_family =
1619 				    ifa->ifa_addr->sa_family;
1620 				ifa->ifa_dstaddr->sa_family = ifa->ifa_addr->sa_family;
1621 				copy_satopfaddr(&n->peer, ifa->ifa_dstaddr);
1622 			}
1623 			if (n->af == AF_INET6)
1624 				n->ifindex = ((struct sockaddr_in6 *)
1625 				    ifa->ifa_addr) ->sin6_scope_id;
1626 		}
1627 		if ((n->ifname = strdup(ifa->ifa_name)) == NULL)
1628 			err(1, "%s: strdup", __func__);
1629 		n->next = NULL;
1630 		n->tail = n;
1631 		if (h == NULL)
1632 			h = n;
1633 		else {
1634 			h->tail->next = n;
1635 			h->tail = n;
1636 		}
1637 	}
1638 
1639 	iftab = h;
1640 	freeifaddrs(ifap);
1641 }
1642 
1643 static int
1644 get_socket_domain(void)
1645 {
1646 	int sdom;
1647 
1648 	sdom = AF_UNSPEC;
1649 #ifdef WITH_INET6
1650 	if (sdom == AF_UNSPEC && feature_present("inet6"))
1651 		sdom = AF_INET6;
1652 #endif
1653 #ifdef WITH_INET
1654 	if (sdom == AF_UNSPEC && feature_present("inet"))
1655 		sdom = AF_INET;
1656 #endif
1657 	if (sdom == AF_UNSPEC)
1658 		sdom = AF_LINK;
1659 
1660 	return (sdom);
1661 }
1662 
1663 int
1664 get_query_socket(void)
1665 {
1666 	static int s = -1;
1667 
1668 	if (s == -1) {
1669 		if ((s = socket(get_socket_domain(), SOCK_DGRAM, 0)) == -1)
1670 			err(1, "socket");
1671 	}
1672 
1673 	return (s);
1674 }
1675 
1676 /*
1677  * Returns the response len if the name is a group, otherwise returns 0.
1678  */
1679 static int
1680 is_a_group(char *name)
1681 {
1682 	ENTRY	 		 item;
1683 	ENTRY			*ret_item;
1684 
1685 	item.key = name;
1686 	if (hsearch_r(item, FIND, &ret_item, &isgroup_map) == 0)
1687 		return (0);
1688 
1689 	return (*(int *)ret_item->data);
1690 }
1691 
1692 unsigned int
1693 ifa_nametoindex(const char *ifa_name)
1694 {
1695 	struct node_host	*p;
1696 
1697 	for (p = iftab; p; p = p->next) {
1698 		if (p->af == AF_LINK && strcmp(p->ifname, ifa_name) == 0)
1699 			return (p->ifindex);
1700 	}
1701 	errno = ENXIO;
1702 	return (0);
1703 }
1704 
1705 char *
1706 ifa_indextoname(unsigned int ifindex, char *ifa_name)
1707 {
1708 	struct node_host	*p;
1709 
1710 	for (p = iftab; p; p = p->next) {
1711 		if (p->af == AF_LINK && ifindex == p->ifindex) {
1712 			strlcpy(ifa_name, p->ifname, IFNAMSIZ);
1713 			return (ifa_name);
1714 		}
1715 	}
1716 	errno = ENXIO;
1717 	return (NULL);
1718 }
1719 
1720 struct node_host *
1721 ifa_exists(char *ifa_name)
1722 {
1723 	struct node_host	*n;
1724 
1725 	if (iftab == NULL)
1726 		ifa_load();
1727 
1728 	/* check whether this is a group */
1729 	if (is_a_group(ifa_name)) {
1730 		/* fake a node_host */
1731 		if ((n = calloc(1, sizeof(*n))) == NULL)
1732 			err(1, "calloc");
1733 		if ((n->ifname = strdup(ifa_name)) == NULL)
1734 			err(1, "strdup");
1735 		return (n);
1736 	}
1737 
1738 	for (n = iftab; n; n = n->next) {
1739 		if (n->af == AF_LINK && !strncmp(n->ifname, ifa_name, IFNAMSIZ))
1740 			return (n);
1741 	}
1742 
1743 	return (NULL);
1744 }
1745 
1746 struct node_host *
1747 ifa_grouplookup(char *ifa_name, int flags)
1748 {
1749 	struct ifg_req		*ifg;
1750 	struct ifgroupreq	 ifgr;
1751 	int			 s, len;
1752 	struct node_host	*n, *h = NULL;
1753 
1754 	s = get_query_socket();
1755 	len = is_a_group(ifa_name);
1756 	if (len == 0)
1757 		return (NULL);
1758 	bzero(&ifgr, sizeof(ifgr));
1759 	strlcpy(ifgr.ifgr_name, ifa_name, sizeof(ifgr.ifgr_name));
1760 	ifgr.ifgr_len = len;
1761 	if ((ifgr.ifgr_groups = calloc(1, len)) == NULL)
1762 		err(1, "calloc");
1763 	if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == -1)
1764 		err(1, "SIOCGIFGMEMB");
1765 
1766 	for (ifg = ifgr.ifgr_groups; ifg && len >= sizeof(struct ifg_req);
1767 	    ifg++) {
1768 		len -= sizeof(struct ifg_req);
1769 		if ((n = ifa_lookup(ifg->ifgrq_member, flags)) == NULL)
1770 			continue;
1771 		if (h == NULL)
1772 			h = n;
1773 		else {
1774 			h->tail->next = n;
1775 			h->tail = n->tail;
1776 		}
1777 	}
1778 	free(ifgr.ifgr_groups);
1779 
1780 	return (h);
1781 }
1782 
1783 struct node_host *
1784 ifa_lookup(char *ifa_name, int flags)
1785 {
1786 	struct node_host	*p = NULL, *h = NULL, *n = NULL;
1787 	int			 got4 = 0, got6 = 0;
1788 	const char		 *last_if = NULL;
1789 
1790 	/* first load iftab and isgroup_map */
1791 	if (iftab == NULL)
1792 		ifa_load();
1793 
1794 	if ((h = ifa_grouplookup(ifa_name, flags)) != NULL)
1795 		return (h);
1796 
1797 	if (!strncmp(ifa_name, "self", IFNAMSIZ))
1798 		ifa_name = NULL;
1799 
1800 	for (p = iftab; p; p = p->next) {
1801 		if (ifa_skip_if(ifa_name, p))
1802 			continue;
1803 		if ((flags & PFI_AFLAG_BROADCAST) && p->af != AF_INET)
1804 			continue;
1805 		if ((flags & PFI_AFLAG_BROADCAST) &&
1806 		    !(p->ifa_flags & IFF_BROADCAST))
1807 			continue;
1808 		if ((flags & PFI_AFLAG_BROADCAST) && p->bcast.v4.s_addr == 0)
1809 			continue;
1810 		if ((flags & PFI_AFLAG_PEER) &&
1811 		    !(p->ifa_flags & IFF_POINTOPOINT))
1812 			continue;
1813 		if ((flags & PFI_AFLAG_NETWORK) && p->ifindex > 0)
1814 			continue;
1815 		if (last_if == NULL || strcmp(last_if, p->ifname))
1816 			got4 = got6 = 0;
1817 		last_if = p->ifname;
1818 		if ((flags & PFI_AFLAG_NOALIAS) && p->af == AF_INET && got4)
1819 			continue;
1820 		if ((flags & PFI_AFLAG_NOALIAS) && p->af == AF_INET6 &&
1821 		    IN6_IS_ADDR_LINKLOCAL(&p->addr.v.a.addr.v6))
1822 			continue;
1823 		if ((flags & PFI_AFLAG_NOALIAS) && p->af == AF_INET6 && got6)
1824 			continue;
1825 		if (p->af == AF_INET)
1826 			got4 = 1;
1827 		else
1828 			got6 = 1;
1829 		n = calloc(1, sizeof(struct node_host));
1830 		if (n == NULL)
1831 			err(1, "%s: calloc", __func__);
1832 		n->af = p->af;
1833 		if (flags & PFI_AFLAG_BROADCAST)
1834 			memcpy(&n->addr.v.a.addr, &p->bcast,
1835 			    sizeof(struct pf_addr));
1836 		else if (flags & PFI_AFLAG_PEER)
1837 			memcpy(&n->addr.v.a.addr, &p->peer,
1838 			    sizeof(struct pf_addr));
1839 		else
1840 			memcpy(&n->addr.v.a.addr, &p->addr.v.a.addr,
1841 			    sizeof(struct pf_addr));
1842 		if (flags & PFI_AFLAG_NETWORK)
1843 			set_ipmask(n, unmask(&p->addr.v.a.mask));
1844 		else
1845 			set_ipmask(n, -1);
1846 		n->ifindex = p->ifindex;
1847 		n->ifname = strdup(p->ifname);
1848 
1849 		n->next = NULL;
1850 		n->tail = n;
1851 		if (h == NULL)
1852 			h = n;
1853 		else {
1854 			h->tail->next = n;
1855 			h->tail = n;
1856 		}
1857 	}
1858 	return (h);
1859 }
1860 
1861 int
1862 ifa_skip_if(const char *filter, struct node_host *p)
1863 {
1864 	int	n;
1865 
1866 	if (p->af != AF_INET && p->af != AF_INET6)
1867 		return (1);
1868 	if (filter == NULL || !*filter)
1869 		return (0);
1870 	if (!strcmp(p->ifname, filter))
1871 		return (0);	/* exact match */
1872 	n = strlen(filter);
1873 	if (n < 1 || n >= IFNAMSIZ)
1874 		return (1);	/* sanity check */
1875 	if (filter[n-1] >= '0' && filter[n-1] <= '9')
1876 		return (1);	/* only do exact match in that case */
1877 	if (strncmp(p->ifname, filter, n))
1878 		return (1);	/* prefix doesn't match */
1879 	return (p->ifname[n] < '0' || p->ifname[n] > '9');
1880 }
1881 
1882 
1883 struct node_host *
1884 host(const char *s, int opts)
1885 {
1886 	struct node_host	*h = NULL;
1887 	int			 mask = -1;
1888 	char			*p, *ps;
1889 	const char		*errstr;
1890 
1891 	if ((p = strchr(s, '/')) != NULL) {
1892 		mask = strtonum(p+1, 0, 128, &errstr);
1893 		if (errstr) {
1894 			fprintf(stderr, "netmask is %s: %s\n", errstr, p);
1895 			goto error;
1896 		}
1897 		if ((ps = malloc(strlen(s) - strlen(p) + 1)) == NULL)
1898 			err(1, "%s: malloc", __func__);
1899 		strlcpy(ps, s, strlen(s) - strlen(p) + 1);
1900 	} else {
1901 		if ((ps = strdup(s)) == NULL)
1902 			err(1, "%s: strdup", __func__);
1903 	}
1904 
1905 	if ((h = host_ip(ps, mask)) == NULL &&
1906 	    (h = host_if(ps, mask)) == NULL &&
1907 	    (h = host_dns(ps, mask, (opts & PF_OPT_NODNS))) == NULL) {
1908 		fprintf(stderr, "no IP address found for %s\n", s);
1909 		goto error;
1910 	}
1911 
1912 error:
1913 	free(ps);
1914 	return (h);
1915 }
1916 
1917 struct node_host *
1918 host_if(const char *s, int mask)
1919 {
1920 	struct node_host	*n, *h = NULL;
1921 	char			*p, *ps;
1922 	int			 flags = 0;
1923 
1924 	if ((ps = strdup(s)) == NULL)
1925 		err(1, "host_if: strdup");
1926 	while ((p = strrchr(ps, ':')) != NULL) {
1927 		if (!strcmp(p+1, "network"))
1928 			flags |= PFI_AFLAG_NETWORK;
1929 		else if (!strcmp(p+1, "broadcast"))
1930 			flags |= PFI_AFLAG_BROADCAST;
1931 		else if (!strcmp(p+1, "peer"))
1932 			flags |= PFI_AFLAG_PEER;
1933 		else if (!strcmp(p+1, "0"))
1934 			flags |= PFI_AFLAG_NOALIAS;
1935 		else
1936 			goto error;
1937 		*p = '\0';
1938 	}
1939 	if (flags & (flags - 1) & PFI_AFLAG_MODEMASK) { /* Yep! */
1940 		fprintf(stderr, "illegal combination of interface modifiers\n");
1941 		goto error;
1942 	}
1943 	if ((flags & (PFI_AFLAG_NETWORK|PFI_AFLAG_BROADCAST)) && mask > -1) {
1944 		fprintf(stderr, "network or broadcast lookup, but "
1945 		    "extra netmask given\n");
1946 		goto error;
1947 	}
1948 	if (ifa_exists(ps) || !strncmp(ps, "self", IFNAMSIZ)) {
1949 		/* interface with this name exists */
1950 		h = ifa_lookup(ps, flags);
1951 		if (mask > -1)
1952 			for (n = h; n != NULL; n = n->next)
1953 				set_ipmask(n, mask);
1954 	}
1955 
1956 error:
1957 	free(ps);
1958 	return (h);
1959 }
1960 
1961 struct node_host *
1962 host_ip(const char *s, int mask)
1963 {
1964 	struct addrinfo		 hints, *res;
1965 	struct node_host	*h = NULL;
1966 
1967 	h = calloc(1, sizeof(*h));
1968 	if (h == NULL)
1969 		err(1, "%s: calloc", __func__);
1970 	if (mask != -1) {
1971 		/* Try to parse 10/8 */
1972 		h->af = AF_INET;
1973 		if (inet_net_pton(AF_INET, s, &h->addr.v.a.addr.v4,
1974 		    sizeof(h->addr.v.a.addr.v4)) != -1)
1975 			goto out;
1976 	}
1977 
1978 	memset(&hints, 0, sizeof(hints));
1979 	hints.ai_family = AF_UNSPEC;
1980 	hints.ai_socktype = SOCK_DGRAM; /*dummy*/
1981 	hints.ai_flags = AI_NUMERICHOST;
1982 	if (getaddrinfo(s, NULL, &hints, &res) == 0) {
1983 		h->af = res->ai_family;
1984 		copy_satopfaddr(&h->addr.v.a.addr, res->ai_addr);
1985 		if (h->af == AF_INET6)
1986 			h->ifindex =
1987 			    ((struct sockaddr_in6 *)res->ai_addr)->sin6_scope_id;
1988 		freeaddrinfo(res);
1989 	} else {
1990 		free(h);
1991 		return (NULL);
1992 	}
1993 out:
1994 	set_ipmask(h, mask);
1995 	h->ifname = NULL;
1996 	h->next = NULL;
1997 	h->tail = h;
1998 
1999 	return (h);
2000 }
2001 
2002 struct node_host *
2003 host_dns(const char *s, int mask, int numeric)
2004 {
2005 	struct addrinfo		 hints, *res0, *res;
2006 	struct node_host	*n, *h = NULL;
2007 	int			 noalias = 0, got4 = 0, got6 = 0;
2008 	char			*p, *ps;
2009 
2010 	if ((ps = strdup(s)) == NULL)
2011 		err(1, "host_dns: strdup");
2012 	if ((p = strrchr(ps, ':')) != NULL && !strcmp(p, ":0")) {
2013 		noalias = 1;
2014 		*p = '\0';
2015 	}
2016 	memset(&hints, 0, sizeof(hints));
2017 	hints.ai_family = PF_UNSPEC;
2018 	hints.ai_socktype = SOCK_STREAM; /* DUMMY */
2019 	if (numeric)
2020 		hints.ai_flags = AI_NUMERICHOST;
2021 	if (getaddrinfo(ps, NULL, &hints, &res0) != 0)
2022 		goto error;
2023 
2024 	for (res = res0; res; res = res->ai_next) {
2025 		if (res->ai_family != AF_INET &&
2026 		    res->ai_family != AF_INET6)
2027 			continue;
2028 		if (noalias) {
2029 			if (res->ai_family == AF_INET) {
2030 				if (got4)
2031 					continue;
2032 				got4 = 1;
2033 			} else {
2034 				if (got6)
2035 					continue;
2036 				got6 = 1;
2037 			}
2038 		}
2039 		n = calloc(1, sizeof(struct node_host));
2040 		if (n == NULL)
2041 			err(1, "host_dns: calloc");
2042 		n->ifname = NULL;
2043 		n->af = res->ai_family;
2044 		copy_satopfaddr(&n->addr.v.a.addr, res->ai_addr);
2045 		if (res->ai_family == AF_INET6)
2046 			n->ifindex =
2047 			    ((struct sockaddr_in6 *)res->ai_addr)->sin6_scope_id;
2048 		set_ipmask(n, mask);
2049 		n->next = NULL;
2050 		n->tail = n;
2051 		if (h == NULL)
2052 			h = n;
2053 		else {
2054 			h->tail->next = n;
2055 			h->tail = n;
2056 		}
2057 	}
2058 	freeaddrinfo(res0);
2059 error:
2060 	free(ps);
2061 
2062 	return (h);
2063 }
2064 
2065 /*
2066  * convert a hostname to a list of addresses and put them in the given buffer.
2067  * test:
2068  *	if set to 1, only simple addresses are accepted (no netblock, no "!").
2069  */
2070 int
2071 append_addr(struct pfr_buffer *b, char *s, int test, int opts)
2072 {
2073 	char			 *r;
2074 	struct node_host	*h, *n;
2075 	int			 rv, not = 0;
2076 
2077 	for (r = s; *r == '!'; r++)
2078 		not = !not;
2079 	if ((n = host(r, opts)) == NULL) {
2080 		errno = 0;
2081 		return (-1);
2082 	}
2083 	rv = append_addr_host(b, n, test, not);
2084 	do {
2085 		h = n;
2086 		n = n->next;
2087 		free(h);
2088 	} while (n != NULL);
2089 	return (rv);
2090 }
2091 
2092 /*
2093  * same as previous function, but with a pre-parsed input and the ability
2094  * to "negate" the result. Does not free the node_host list.
2095  * not:
2096  *      setting it to 1 is equivalent to adding "!" in front of parameter s.
2097  */
2098 int
2099 append_addr_host(struct pfr_buffer *b, struct node_host *n, int test, int not)
2100 {
2101 	int			 bits;
2102 	struct pfr_addr		 addr;
2103 
2104 	do {
2105 		bzero(&addr, sizeof(addr));
2106 		addr.pfra_not = n->not ^ not;
2107 		addr.pfra_af = n->af;
2108 		addr.pfra_net = unmask(&n->addr.v.a.mask);
2109 		switch (n->af) {
2110 		case AF_INET:
2111 			addr.pfra_ip4addr.s_addr = n->addr.v.a.addr.addr32[0];
2112 			bits = 32;
2113 			break;
2114 		case AF_INET6:
2115 			memcpy(&addr.pfra_ip6addr, &n->addr.v.a.addr.v6,
2116 			    sizeof(struct in6_addr));
2117 			bits = 128;
2118 			break;
2119 		default:
2120 			errno = EINVAL;
2121 			return (-1);
2122 		}
2123 		if ((test && (not || addr.pfra_net != bits)) ||
2124 		    addr.pfra_net > bits) {
2125 			errno = EINVAL;
2126 			return (-1);
2127 		}
2128 		if (pfr_buf_add(b, &addr))
2129 			return (-1);
2130 	} while ((n = n->next) != NULL);
2131 
2132 	return (0);
2133 }
2134 
2135 int
2136 pfctl_add_trans(struct pfr_buffer *buf, int rs_num, const char *anchor)
2137 {
2138 	struct pfioc_trans_e trans;
2139 
2140 	bzero(&trans, sizeof(trans));
2141 	trans.rs_num = rs_num;
2142 	if (strlcpy(trans.anchor, anchor,
2143 	    sizeof(trans.anchor)) >= sizeof(trans.anchor))
2144 		errx(1, "pfctl_add_trans: strlcpy");
2145 
2146 	return pfr_buf_add(buf, &trans);
2147 }
2148 
2149 u_int32_t
2150 pfctl_get_ticket(struct pfr_buffer *buf, int rs_num, const char *anchor)
2151 {
2152 	struct pfioc_trans_e *p;
2153 
2154 	PFRB_FOREACH(p, buf)
2155 		if (rs_num == p->rs_num && !strcmp(anchor, p->anchor))
2156 			return (p->ticket);
2157 	errx(1, "pfctl_get_ticket: assertion failed");
2158 }
2159 
2160 int
2161 pfctl_trans(int dev, struct pfr_buffer *buf, u_long cmd, int from)
2162 {
2163 	struct pfioc_trans trans;
2164 
2165 	bzero(&trans, sizeof(trans));
2166 	trans.size = buf->pfrb_size - from;
2167 	trans.esize = sizeof(struct pfioc_trans_e);
2168 	trans.array = ((struct pfioc_trans_e *)buf->pfrb_caddr) + from;
2169 	return ioctl(dev, cmd, &trans);
2170 }
2171