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