xref: /freebsd/sbin/pfctl/pfctl_parser.c (revision 2008043f386721d58158e37e0d7e50df8095942d)
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/cdefs.h>
37 #include <sys/types.h>
38 #include <sys/ioctl.h>
39 #include <sys/socket.h>
40 #include <sys/param.h>
41 #include <sys/proc.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 <net/pfvar.h>
49 #include <arpa/inet.h>
50 
51 #include <assert.h>
52 #include <search.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <ctype.h>
57 #include <netdb.h>
58 #include <stdarg.h>
59 #include <errno.h>
60 #include <err.h>
61 #include <ifaddrs.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 (id == PF_NAT && p1 == 0 && p2 == 0)
493 		printf(" static-port");
494 	if (pool->mape.offset > 0)
495 		printf(" map-e-portset %u/%u/%u",
496 		    pool->mape.offset, pool->mape.psidlen, pool->mape.psid);
497 }
498 
499 const char	* const pf_reasons[PFRES_MAX+1] = PFRES_NAMES;
500 const char	* const pf_lcounters[LCNT_MAX+1] = LCNT_NAMES;
501 const char	* const pf_fcounters[FCNT_MAX+1] = FCNT_NAMES;
502 const char	* const pf_scounters[FCNT_MAX+1] = FCNT_NAMES;
503 
504 void
505 print_status(struct pfctl_status *s, struct pfctl_syncookies *cookies, int opts)
506 {
507 	struct pfctl_status_counter	*c;
508 	char			statline[80], *running;
509 	time_t			runtime;
510 	int			i;
511 	char			buf[PF_MD5_DIGEST_LENGTH * 2 + 1];
512 	static const char	hex[] = "0123456789abcdef";
513 
514 	runtime = time(NULL) - s->since;
515 	running = s->running ? "Enabled" : "Disabled";
516 
517 	if (s->since) {
518 		unsigned int	sec, min, hrs, day = runtime;
519 
520 		sec = day % 60;
521 		day /= 60;
522 		min = day % 60;
523 		day /= 60;
524 		hrs = day % 24;
525 		day /= 24;
526 		snprintf(statline, sizeof(statline),
527 		    "Status: %s for %u days %.2u:%.2u:%.2u",
528 		    running, day, hrs, min, sec);
529 	} else
530 		snprintf(statline, sizeof(statline), "Status: %s", running);
531 	printf("%-44s", statline);
532 	switch (s->debug) {
533 	case PF_DEBUG_NONE:
534 		printf("%15s\n\n", "Debug: None");
535 		break;
536 	case PF_DEBUG_URGENT:
537 		printf("%15s\n\n", "Debug: Urgent");
538 		break;
539 	case PF_DEBUG_MISC:
540 		printf("%15s\n\n", "Debug: Misc");
541 		break;
542 	case PF_DEBUG_NOISY:
543 		printf("%15s\n\n", "Debug: Loud");
544 		break;
545 	}
546 
547 	if (opts & PF_OPT_VERBOSE) {
548 		printf("Hostid:   0x%08x\n", s->hostid);
549 
550 		for (i = 0; i < PF_MD5_DIGEST_LENGTH; i++) {
551 			buf[i + i] = hex[s->pf_chksum[i] >> 4];
552 			buf[i + i + 1] = hex[s->pf_chksum[i] & 0x0f];
553 		}
554 		buf[i + i] = '\0';
555 		printf("Checksum: 0x%s\n\n", buf);
556 	}
557 
558 	if (s->ifname[0] != 0) {
559 		printf("Interface Stats for %-16s %5s %16s\n",
560 		    s->ifname, "IPv4", "IPv6");
561 		printf("  %-25s %14llu %16llu\n", "Bytes In",
562 		    (unsigned long long)s->bcounters[0][0],
563 		    (unsigned long long)s->bcounters[1][0]);
564 		printf("  %-25s %14llu %16llu\n", "Bytes Out",
565 		    (unsigned long long)s->bcounters[0][1],
566 		    (unsigned long long)s->bcounters[1][1]);
567 		printf("  Packets In\n");
568 		printf("    %-23s %14llu %16llu\n", "Passed",
569 		    (unsigned long long)s->pcounters[0][0][PF_PASS],
570 		    (unsigned long long)s->pcounters[1][0][PF_PASS]);
571 		printf("    %-23s %14llu %16llu\n", "Blocked",
572 		    (unsigned long long)s->pcounters[0][0][PF_DROP],
573 		    (unsigned long long)s->pcounters[1][0][PF_DROP]);
574 		printf("  Packets Out\n");
575 		printf("    %-23s %14llu %16llu\n", "Passed",
576 		    (unsigned long long)s->pcounters[0][1][PF_PASS],
577 		    (unsigned long long)s->pcounters[1][1][PF_PASS]);
578 		printf("    %-23s %14llu %16llu\n\n", "Blocked",
579 		    (unsigned long long)s->pcounters[0][1][PF_DROP],
580 		    (unsigned long long)s->pcounters[1][1][PF_DROP]);
581 	}
582 	printf("%-27s %14s %16s\n", "State Table", "Total", "Rate");
583 	printf("  %-25s %14ju %14s\n", "current entries", s->states, "");
584 	TAILQ_FOREACH(c, &s->fcounters, entry) {
585 		printf("  %-25s %14ju ", c->name, c->counter);
586 		if (runtime > 0)
587 			printf("%14.1f/s\n",
588 			    (double)c->counter / (double)runtime);
589 		else
590 			printf("%14s\n", "");
591 	}
592 	if (opts & PF_OPT_VERBOSE) {
593 		printf("Source Tracking Table\n");
594 		printf("  %-25s %14ju %14s\n", "current entries",
595 		    s->src_nodes, "");
596 		TAILQ_FOREACH(c, &s->scounters, entry) {
597 			printf("  %-25s %14ju ", c->name, c->counter);
598 			if (runtime > 0)
599 				printf("%14.1f/s\n",
600 				    (double)c->counter / (double)runtime);
601 			else
602 				printf("%14s\n", "");
603 		}
604 	}
605 	printf("Counters\n");
606 	TAILQ_FOREACH(c, &s->counters, entry) {
607 		printf("  %-25s %14ju ", c->name, c->counter);
608 		if (runtime > 0)
609 			printf("%14.1f/s\n",
610 			    (double)c->counter / (double)runtime);
611 		else
612 			printf("%14s\n", "");
613 	}
614 	if (opts & PF_OPT_VERBOSE) {
615 		printf("Limit Counters\n");
616 		TAILQ_FOREACH(c, &s->lcounters, entry) {
617 			printf("  %-25s %14ju ", c->name, c->counter);
618 			if (runtime > 0)
619 				printf("%14.1f/s\n",
620 				    (double)c->counter / (double)runtime);
621 			else
622 				printf("%14s\n", "");
623 		}
624 
625 		printf("Syncookies\n");
626 		assert(cookies->mode <= PFCTL_SYNCOOKIES_ADAPTIVE);
627 		printf("  %-25s %s\n", "mode",
628 		    PFCTL_SYNCOOKIES_MODE_NAMES[cookies->mode]);
629 		printf("  %-25s %s\n", "active",
630 		    s->syncookies_active ? "active" : "inactive");
631 		printf("Reassemble %24s %s\n",
632 		    s->reass & PF_REASS_ENABLED ? "yes" : "no",
633 		    s->reass & PF_REASS_NODF ? "no-df" : ""
634 		);
635 	}
636 }
637 
638 void
639 print_running(struct pfctl_status *status)
640 {
641 	printf("%s\n", status->running ? "Enabled" : "Disabled");
642 }
643 
644 void
645 print_src_node(struct pf_src_node *sn, int opts)
646 {
647 	struct pf_addr_wrap aw;
648 	int min, sec;
649 
650 	memset(&aw, 0, sizeof(aw));
651 	if (sn->af == AF_INET)
652 		aw.v.a.mask.addr32[0] = 0xffffffff;
653 	else
654 		memset(&aw.v.a.mask, 0xff, sizeof(aw.v.a.mask));
655 
656 	aw.v.a.addr = sn->addr;
657 	print_addr(&aw, sn->af, opts & PF_OPT_VERBOSE2);
658 	printf(" -> ");
659 	aw.v.a.addr = sn->raddr;
660 	print_addr(&aw, sn->af, opts & PF_OPT_VERBOSE2);
661 	printf(" ( states %u, connections %u, rate %u.%u/%us )\n", sn->states,
662 	    sn->conn, sn->conn_rate.count / 1000,
663 	    (sn->conn_rate.count % 1000) / 100, sn->conn_rate.seconds);
664 	if (opts & PF_OPT_VERBOSE) {
665 		sec = sn->creation % 60;
666 		sn->creation /= 60;
667 		min = sn->creation % 60;
668 		sn->creation /= 60;
669 		printf("   age %.2u:%.2u:%.2u", sn->creation, min, sec);
670 		if (sn->states == 0) {
671 			sec = sn->expire % 60;
672 			sn->expire /= 60;
673 			min = sn->expire % 60;
674 			sn->expire /= 60;
675 			printf(", expires in %.2u:%.2u:%.2u",
676 			    sn->expire, min, sec);
677 		}
678 		printf(", %llu pkts, %llu bytes",
679 #ifdef __FreeBSD__
680 		    (unsigned long long)(sn->packets[0] + sn->packets[1]),
681 		    (unsigned long long)(sn->bytes[0] + sn->bytes[1]));
682 #else
683 		    sn->packets[0] + sn->packets[1],
684 		    sn->bytes[0] + sn->bytes[1]);
685 #endif
686 		switch (sn->ruletype) {
687 		case PF_NAT:
688 			if (sn->rule.nr != -1)
689 				printf(", nat rule %u", sn->rule.nr);
690 			break;
691 		case PF_RDR:
692 			if (sn->rule.nr != -1)
693 				printf(", rdr rule %u", sn->rule.nr);
694 			break;
695 		case PF_PASS:
696 		case PF_MATCH:
697 			if (sn->rule.nr != -1)
698 				printf(", filter rule %u", sn->rule.nr);
699 			break;
700 		}
701 		printf("\n");
702 	}
703 }
704 
705 static void
706 print_eth_addr(const struct pfctl_eth_addr *a)
707 {
708 	int i, masklen = ETHER_ADDR_LEN * 8;
709 	bool seen_unset = false;
710 
711 	for (i = 0; i < ETHER_ADDR_LEN; i++) {
712 		if (a->addr[i] != 0)
713 			break;
714 	}
715 
716 	/* Unset, so don't print anything. */
717 	if (i == ETHER_ADDR_LEN)
718 		return;
719 
720 	printf("%s%02x:%02x:%02x:%02x:%02x:%02x", a->neg ? "! " : "",
721 	    a->addr[0], a->addr[1], a->addr[2], a->addr[3], a->addr[4],
722 	    a->addr[5]);
723 
724 	for (i = 0; i < (ETHER_ADDR_LEN * 8); i++) {
725 		bool isset = a->mask[i / 8] & (1 << i % 8);
726 
727 		if (! seen_unset) {
728 			if (isset)
729 				continue;
730 			seen_unset = true;
731 			masklen = i;
732 		} else {
733 			/* Not actually a continuous mask, so print the whole
734 			 * thing. */
735 			if (isset)
736 				break;
737 			continue;
738 		}
739 	}
740 
741 	if (masklen == (ETHER_ADDR_LEN * 8))
742 		return;
743 
744 	if (i == (ETHER_ADDR_LEN * 8)) {
745 		printf("/%d", masklen);
746 		return;
747 	}
748 
749 	printf("&%02x:%02x:%02x:%02x:%02x:%02x",
750 	    a->mask[0], a->mask[1], a->mask[2], a->mask[3], a->mask[4],
751 	    a->mask[5]);
752 }
753 
754 void
755 print_eth_rule(struct pfctl_eth_rule *r, const char *anchor_call,
756     int rule_numbers)
757 {
758 	static const char *actiontypes[] = { "pass", "block", "", "", "", "",
759 	    "", "", "", "", "", "", "match" };
760 
761 	int i;
762 
763 	if (rule_numbers)
764 		printf("@%u ", r->nr);
765 
766 	printf("ether ");
767 	if (anchor_call[0]) {
768 		if (anchor_call[0] == '_') {
769 			printf("anchor");
770 		} else
771 			printf("anchor \"%s\"", anchor_call);
772 	} else {
773 		printf("%s", actiontypes[r->action]);
774 	}
775 	if (r->direction == PF_IN)
776 		printf(" in");
777 	else if (r->direction == PF_OUT)
778 		printf(" out");
779 
780 	if (r->quick)
781 		printf(" quick");
782 	if (r->ifname[0]) {
783 		if (r->ifnot)
784 			printf(" on ! %s", r->ifname);
785 		else
786 			printf(" on %s", r->ifname);
787 	}
788 	if (r->bridge_to[0])
789 		printf(" bridge-to %s", r->bridge_to);
790 	if (r->proto)
791 		printf(" proto 0x%04x", r->proto);
792 
793 	if (r->src.isset) {
794 		printf(" from ");
795 		print_eth_addr(&r->src);
796 	}
797 	if (r->dst.isset) {
798 		printf(" to ");
799 		print_eth_addr(&r->dst);
800 	}
801 	printf(" l3");
802 	print_fromto(&r->ipsrc, PF_OSFP_ANY, &r->ipdst,
803 	    r->proto == ETHERTYPE_IP ? AF_INET : AF_INET6, 0,
804 	    0, 0);
805 
806 	i = 0;
807 	while (r->label[i][0])
808 		printf(" label \"%s\"", r->label[i++]);
809 	if (r->ridentifier)
810 		printf(" ridentifier %u", r->ridentifier);
811 
812 	if (r->qname[0])
813 		printf(" queue %s", r->qname);
814 	if (r->tagname[0])
815 		printf(" tag %s", r->tagname);
816 	if (r->match_tagname[0]) {
817 		if (r->match_tag_not)
818 			printf(" !");
819 		printf(" tagged %s", r->match_tagname);
820 	}
821 	if (r->dnpipe)
822 		printf(" %s %d",
823 		    r->dnflags & PFRULE_DN_IS_PIPE ? "dnpipe" : "dnqueue",
824 		    r->dnpipe);
825 }
826 
827 void
828 print_rule(struct pfctl_rule *r, const char *anchor_call, int verbose, int numeric)
829 {
830 	static const char *actiontypes[] = { "pass", "block", "scrub",
831 	    "no scrub", "nat", "no nat", "binat", "no binat", "rdr", "no rdr",
832 	    "", "", "match"};
833 	static const char *anchortypes[] = { "anchor", "anchor", "anchor",
834 	    "anchor", "nat-anchor", "nat-anchor", "binat-anchor",
835 	    "binat-anchor", "rdr-anchor", "rdr-anchor" };
836 	int	i, opts;
837 	char	*p;
838 
839 	if (verbose)
840 		printf("@%d ", r->nr);
841 	if (r->action == PF_MATCH)
842 		printf("match");
843 	else if (r->action > PF_NORDR)
844 		printf("action(%d)", r->action);
845 	else if (anchor_call[0]) {
846 		p = strrchr(anchor_call, '/');
847 		if (p ? p[1] == '_' : anchor_call[0] == '_')
848 			printf("%s", anchortypes[r->action]);
849 		else
850 			printf("%s \"%s\"", anchortypes[r->action],
851 			    anchor_call);
852 	} else {
853 		printf("%s", actiontypes[r->action]);
854 		if (r->natpass)
855 			printf(" pass");
856 	}
857 	if (r->action == PF_DROP) {
858 		if (r->rule_flag & PFRULE_RETURN)
859 			printf(" return");
860 		else if (r->rule_flag & PFRULE_RETURNRST) {
861 			if (!r->return_ttl)
862 				printf(" return-rst");
863 			else
864 				printf(" return-rst(ttl %d)", r->return_ttl);
865 		} else if (r->rule_flag & PFRULE_RETURNICMP) {
866 			const struct icmpcodeent	*ic, *ic6;
867 
868 			ic = geticmpcodebynumber(r->return_icmp >> 8,
869 			    r->return_icmp & 255, AF_INET);
870 			ic6 = geticmpcodebynumber(r->return_icmp6 >> 8,
871 			    r->return_icmp6 & 255, AF_INET6);
872 
873 			switch (r->af) {
874 			case AF_INET:
875 				printf(" return-icmp");
876 				if (ic == NULL)
877 					printf("(%u)", r->return_icmp & 255);
878 				else
879 					printf("(%s)", ic->name);
880 				break;
881 			case AF_INET6:
882 				printf(" return-icmp6");
883 				if (ic6 == NULL)
884 					printf("(%u)", r->return_icmp6 & 255);
885 				else
886 					printf("(%s)", ic6->name);
887 				break;
888 			default:
889 				printf(" return-icmp");
890 				if (ic == NULL)
891 					printf("(%u, ", r->return_icmp & 255);
892 				else
893 					printf("(%s, ", ic->name);
894 				if (ic6 == NULL)
895 					printf("%u)", r->return_icmp6 & 255);
896 				else
897 					printf("%s)", ic6->name);
898 				break;
899 			}
900 		} else
901 			printf(" drop");
902 	}
903 	if (r->direction == PF_IN)
904 		printf(" in");
905 	else if (r->direction == PF_OUT)
906 		printf(" out");
907 	if (r->log) {
908 		printf(" log");
909 		if (r->log & ~PF_LOG || r->logif) {
910 			int count = 0;
911 
912 			printf(" (");
913 			if (r->log & PF_LOG_ALL)
914 				printf("%sall", count++ ? ", " : "");
915 			if (r->log & PF_LOG_SOCKET_LOOKUP)
916 				printf("%suser", count++ ? ", " : "");
917 			if (r->logif)
918 				printf("%sto pflog%u", count++ ? ", " : "",
919 				    r->logif);
920 			printf(")");
921 		}
922 	}
923 	if (r->quick)
924 		printf(" quick");
925 	if (r->ifname[0]) {
926 		if (r->ifnot)
927 			printf(" on ! %s", r->ifname);
928 		else
929 			printf(" on %s", r->ifname);
930 	}
931 	if (r->rt) {
932 		if (r->rt == PF_ROUTETO)
933 			printf(" route-to");
934 		else if (r->rt == PF_REPLYTO)
935 			printf(" reply-to");
936 		else if (r->rt == PF_DUPTO)
937 			printf(" dup-to");
938 		printf(" ");
939 		print_pool(&r->rpool, 0, 0, r->af, PF_PASS);
940 	}
941 	if (r->af) {
942 		if (r->af == AF_INET)
943 			printf(" inet");
944 		else
945 			printf(" inet6");
946 	}
947 	if (r->proto) {
948 		const char *protoname;
949 
950 		if ((protoname = pfctl_proto2name(r->proto)) != NULL)
951 			printf(" proto %s", protoname);
952 		else
953 			printf(" proto %u", r->proto);
954 	}
955 	print_fromto(&r->src, r->os_fingerprint, &r->dst, r->af, r->proto,
956 	    verbose, numeric);
957 	if (r->uid.op)
958 		print_ugid(r->uid.op, r->uid.uid[0], r->uid.uid[1], "user",
959 		    UID_MAX);
960 	if (r->gid.op)
961 		print_ugid(r->gid.op, r->gid.gid[0], r->gid.gid[1], "group",
962 		    GID_MAX);
963 	if (r->flags || r->flagset) {
964 		printf(" flags ");
965 		print_flags(r->flags);
966 		printf("/");
967 		print_flags(r->flagset);
968 	} else if ((r->action == PF_PASS || r->action == PF_MATCH) &&
969 	    (!r->proto || r->proto == IPPROTO_TCP) &&
970 	    !(r->rule_flag & PFRULE_FRAGMENT) &&
971 	    !anchor_call[0] && r->keep_state)
972 		printf(" flags any");
973 	if (r->type) {
974 		const struct icmptypeent	*it;
975 
976 		it = geticmptypebynumber(r->type-1, r->af);
977 		if (r->af != AF_INET6)
978 			printf(" icmp-type");
979 		else
980 			printf(" icmp6-type");
981 		if (it != NULL)
982 			printf(" %s", it->name);
983 		else
984 			printf(" %u", r->type-1);
985 		if (r->code) {
986 			const struct icmpcodeent	*ic;
987 
988 			ic = geticmpcodebynumber(r->type-1, r->code-1, r->af);
989 			if (ic != NULL)
990 				printf(" code %s", ic->name);
991 			else
992 				printf(" code %u", r->code-1);
993 		}
994 	}
995 	if (r->tos)
996 		printf(" tos 0x%2.2x", r->tos);
997 	if (r->prio)
998 		printf(" prio %u", r->prio == PF_PRIO_ZERO ? 0 : r->prio);
999 	if (r->scrub_flags & PFSTATE_SETMASK) {
1000 		char *comma = "";
1001 		printf(" set (");
1002 		if (r->scrub_flags & PFSTATE_SETPRIO) {
1003 			if (r->set_prio[0] == r->set_prio[1])
1004 				printf("%s prio %u", comma, r->set_prio[0]);
1005 			else
1006 				printf("%s prio(%u, %u)", comma, r->set_prio[0],
1007 				    r->set_prio[1]);
1008 			comma = ",";
1009 		}
1010 		if (r->scrub_flags & PFSTATE_SETTOS) {
1011 			printf("%s tos 0x%2.2x", comma, r->set_tos);
1012 			comma = ",";
1013 		}
1014 		printf(" )");
1015 	}
1016 	if (!r->keep_state && r->action == PF_PASS && !anchor_call[0])
1017 		printf(" no state");
1018 	else if (r->keep_state == PF_STATE_NORMAL)
1019 		printf(" keep state");
1020 	else if (r->keep_state == PF_STATE_MODULATE)
1021 		printf(" modulate state");
1022 	else if (r->keep_state == PF_STATE_SYNPROXY)
1023 		printf(" synproxy state");
1024 	if (r->prob) {
1025 		char	buf[20];
1026 
1027 		snprintf(buf, sizeof(buf), "%f", r->prob*100.0/(UINT_MAX+1.0));
1028 		for (i = strlen(buf)-1; i > 0; i--) {
1029 			if (buf[i] == '0')
1030 				buf[i] = '\0';
1031 			else {
1032 				if (buf[i] == '.')
1033 					buf[i] = '\0';
1034 				break;
1035 			}
1036 		}
1037 		printf(" probability %s%%", buf);
1038 	}
1039 	opts = 0;
1040 	if (r->max_states || r->max_src_nodes || r->max_src_states)
1041 		opts = 1;
1042 	if (r->rule_flag & PFRULE_NOSYNC)
1043 		opts = 1;
1044 	if (r->rule_flag & PFRULE_SRCTRACK)
1045 		opts = 1;
1046 	if (r->rule_flag & PFRULE_IFBOUND)
1047 		opts = 1;
1048 	if (r->rule_flag & PFRULE_STATESLOPPY)
1049 		opts = 1;
1050 	for (i = 0; !opts && i < PFTM_MAX; ++i)
1051 		if (r->timeout[i])
1052 			opts = 1;
1053 	if (opts) {
1054 		printf(" (");
1055 		if (r->max_states) {
1056 			printf("max %u", r->max_states);
1057 			opts = 0;
1058 		}
1059 		if (r->rule_flag & PFRULE_NOSYNC) {
1060 			if (!opts)
1061 				printf(", ");
1062 			printf("no-sync");
1063 			opts = 0;
1064 		}
1065 		if (r->rule_flag & PFRULE_SRCTRACK) {
1066 			if (!opts)
1067 				printf(", ");
1068 			printf("source-track");
1069 			if (r->rule_flag & PFRULE_RULESRCTRACK)
1070 				printf(" rule");
1071 			else
1072 				printf(" global");
1073 			opts = 0;
1074 		}
1075 		if (r->max_src_states) {
1076 			if (!opts)
1077 				printf(", ");
1078 			printf("max-src-states %u", r->max_src_states);
1079 			opts = 0;
1080 		}
1081 		if (r->max_src_conn) {
1082 			if (!opts)
1083 				printf(", ");
1084 			printf("max-src-conn %u", r->max_src_conn);
1085 			opts = 0;
1086 		}
1087 		if (r->max_src_conn_rate.limit) {
1088 			if (!opts)
1089 				printf(", ");
1090 			printf("max-src-conn-rate %u/%u",
1091 			    r->max_src_conn_rate.limit,
1092 			    r->max_src_conn_rate.seconds);
1093 			opts = 0;
1094 		}
1095 		if (r->max_src_nodes) {
1096 			if (!opts)
1097 				printf(", ");
1098 			printf("max-src-nodes %u", r->max_src_nodes);
1099 			opts = 0;
1100 		}
1101 		if (r->overload_tblname[0]) {
1102 			if (!opts)
1103 				printf(", ");
1104 			printf("overload <%s>", r->overload_tblname);
1105 			if (r->flush)
1106 				printf(" flush");
1107 			if (r->flush & PF_FLUSH_GLOBAL)
1108 				printf(" global");
1109 		}
1110 		if (r->rule_flag & PFRULE_IFBOUND) {
1111 			if (!opts)
1112 				printf(", ");
1113 			printf("if-bound");
1114 			opts = 0;
1115 		}
1116 		if (r->rule_flag & PFRULE_STATESLOPPY) {
1117 			if (!opts)
1118 				printf(", ");
1119 			printf("sloppy");
1120 			opts = 0;
1121 		}
1122 		for (i = 0; i < PFTM_MAX; ++i)
1123 			if (r->timeout[i]) {
1124 				int j;
1125 
1126 				if (!opts)
1127 					printf(", ");
1128 				opts = 0;
1129 				for (j = 0; pf_timeouts[j].name != NULL;
1130 				    ++j)
1131 					if (pf_timeouts[j].timeout == i)
1132 						break;
1133 				printf("%s %u", pf_timeouts[j].name == NULL ?
1134 				    "inv.timeout" : pf_timeouts[j].name,
1135 				    r->timeout[i]);
1136 			}
1137 		printf(")");
1138 	}
1139 	if (r->allow_opts)
1140 		printf(" allow-opts");
1141 	if (r->rule_flag & PFRULE_FRAGMENT)
1142 		printf(" fragment");
1143 	if (r->action == PF_SCRUB) {
1144 		/* Scrub flags for old-style scrub. */
1145 		if (r->rule_flag & PFRULE_NODF)
1146 			printf(" no-df");
1147 		if (r->rule_flag & PFRULE_RANDOMID)
1148 			printf(" random-id");
1149 		if (r->min_ttl)
1150 			printf(" min-ttl %d", r->min_ttl);
1151 		if (r->max_mss)
1152 			printf(" max-mss %d", r->max_mss);
1153 		if (r->rule_flag & PFRULE_SET_TOS)
1154 			printf(" set-tos 0x%2.2x", r->set_tos);
1155 		if (r->rule_flag & PFRULE_REASSEMBLE_TCP)
1156 			printf(" reassemble tcp");
1157 		/* The PFRULE_FRAGMENT_NOREASS is set on all rules by default! */
1158 		printf(" fragment %sreassemble",
1159 		    r->rule_flag & PFRULE_FRAGMENT_NOREASS ? "no " : "");
1160 	} else if (r->scrub_flags & PFSTATE_SCRUBMASK || r->min_ttl || r->max_mss) {
1161 		/* Scrub actions on normal rules. */
1162 		printf(" scrub(");
1163 		if (r->scrub_flags & PFSTATE_NODF)
1164 			printf(" no-df");
1165 		if (r->scrub_flags & PFSTATE_RANDOMID)
1166 			printf(" random-id");
1167 		if (r->min_ttl)
1168 			printf(" min-ttl %d", r->min_ttl);
1169 		if (r->scrub_flags & PFSTATE_SETTOS)
1170 			printf(" set-tos 0x%2.2x", r->set_tos);
1171 		if (r->scrub_flags & PFSTATE_SCRUB_TCP)
1172 			printf(" reassemble tcp");
1173 		if (r->max_mss)
1174 			printf(" max-mss %d", r->max_mss);
1175 		printf(")");
1176 	}
1177 	i = 0;
1178 	while (r->label[i][0])
1179 		printf(" label \"%s\"", r->label[i++]);
1180 	if (r->ridentifier)
1181 		printf(" ridentifier %u", r->ridentifier);
1182 	/* Only dnrpipe as we might do (0, 42) to only queue return traffic. */
1183 	if (r->dnrpipe)
1184 		printf(" %s(%d, %d)",
1185 		    r->free_flags & PFRULE_DN_IS_PIPE ? "dnpipe" : "dnqueue",
1186 		    r->dnpipe, r->dnrpipe);
1187 	else if (r->dnpipe)
1188 		printf(" %s %d",
1189 		    r->free_flags & PFRULE_DN_IS_PIPE ? "dnpipe" : "dnqueue",
1190 		    r->dnpipe);
1191 	if (r->qname[0] && r->pqname[0])
1192 		printf(" queue(%s, %s)", r->qname, r->pqname);
1193 	else if (r->qname[0])
1194 		printf(" queue %s", r->qname);
1195 	if (r->tagname[0])
1196 		printf(" tag %s", r->tagname);
1197 	if (r->match_tagname[0]) {
1198 		if (r->match_tag_not)
1199 			printf(" !");
1200 		printf(" tagged %s", r->match_tagname);
1201 	}
1202 	if (r->rtableid != -1)
1203 		printf(" rtable %u", r->rtableid);
1204 	if (r->divert.port) {
1205 #ifdef __FreeBSD__
1206 		printf(" divert-to %u", ntohs(r->divert.port));
1207 #else
1208 		if (PF_AZERO(&r->divert.addr, r->af)) {
1209 			printf(" divert-reply");
1210 		} else {
1211 			/* XXX cut&paste from print_addr */
1212 			char buf[48];
1213 
1214 			printf(" divert-to ");
1215 			if (inet_ntop(r->af, &r->divert.addr, buf,
1216 			    sizeof(buf)) == NULL)
1217 				printf("?");
1218 			else
1219 				printf("%s", buf);
1220 			printf(" port %u", ntohs(r->divert.port));
1221 		}
1222 #endif
1223 	}
1224 	if (!anchor_call[0] && (r->action == PF_NAT ||
1225 	    r->action == PF_BINAT || r->action == PF_RDR)) {
1226 		printf(" -> ");
1227 		print_pool(&r->rpool, r->rpool.proxy_port[0],
1228 		    r->rpool.proxy_port[1], r->af, r->action);
1229 	}
1230 }
1231 
1232 void
1233 print_tabledef(const char *name, int flags, int addrs,
1234     struct node_tinithead *nodes)
1235 {
1236 	struct node_tinit	*ti, *nti;
1237 	struct node_host	*h;
1238 
1239 	printf("table <%s>", name);
1240 	if (flags & PFR_TFLAG_CONST)
1241 		printf(" const");
1242 	if (flags & PFR_TFLAG_PERSIST)
1243 		printf(" persist");
1244 	if (flags & PFR_TFLAG_COUNTERS)
1245 		printf(" counters");
1246 	SIMPLEQ_FOREACH(ti, nodes, entries) {
1247 		if (ti->file) {
1248 			printf(" file \"%s\"", ti->file);
1249 			continue;
1250 		}
1251 		printf(" {");
1252 		for (;;) {
1253 			for (h = ti->host; h != NULL; h = h->next) {
1254 				printf(h->not ? " !" : " ");
1255 				print_addr(&h->addr, h->af, 0);
1256 			}
1257 			nti = SIMPLEQ_NEXT(ti, entries);
1258 			if (nti != NULL && nti->file == NULL)
1259 				ti = nti;	/* merge lists */
1260 			else
1261 				break;
1262 		}
1263 		printf(" }");
1264 	}
1265 	if (addrs && SIMPLEQ_EMPTY(nodes))
1266 		printf(" { }");
1267 	printf("\n");
1268 }
1269 
1270 int
1271 parse_flags(char *s)
1272 {
1273 	char		*p, *q;
1274 	u_int8_t	 f = 0;
1275 
1276 	for (p = s; *p; p++) {
1277 		if ((q = strchr(tcpflags, *p)) == NULL)
1278 			return -1;
1279 		else
1280 			f |= 1 << (q - tcpflags);
1281 	}
1282 	return (f ? f : PF_TH_ALL);
1283 }
1284 
1285 void
1286 set_ipmask(struct node_host *h, u_int8_t b)
1287 {
1288 	struct pf_addr	*m, *n;
1289 	int		 i, j = 0;
1290 
1291 	m = &h->addr.v.a.mask;
1292 	memset(m, 0, sizeof(*m));
1293 
1294 	while (b >= 32) {
1295 		m->addr32[j++] = 0xffffffff;
1296 		b -= 32;
1297 	}
1298 	for (i = 31; i > 31-b; --i)
1299 		m->addr32[j] |= (1 << i);
1300 	if (b)
1301 		m->addr32[j] = htonl(m->addr32[j]);
1302 
1303 	/* Mask off bits of the address that will never be used. */
1304 	n = &h->addr.v.a.addr;
1305 	if (h->addr.type == PF_ADDR_ADDRMASK)
1306 		for (i = 0; i < 4; i++)
1307 			n->addr32[i] = n->addr32[i] & m->addr32[i];
1308 }
1309 
1310 int
1311 check_netmask(struct node_host *h, sa_family_t af)
1312 {
1313 	struct node_host	*n = NULL;
1314 	struct pf_addr		*m;
1315 
1316 	for (n = h; n != NULL; n = n->next) {
1317 		if (h->addr.type == PF_ADDR_TABLE)
1318 			continue;
1319 		m = &h->addr.v.a.mask;
1320 		/* netmasks > 32 bit are invalid on v4 */
1321 		if (af == AF_INET &&
1322 		    (m->addr32[1] || m->addr32[2] || m->addr32[3])) {
1323 			fprintf(stderr, "netmask %u invalid for IPv4 address\n",
1324 			    unmask(m, AF_INET6));
1325 			return (1);
1326 		}
1327 	}
1328 	return (0);
1329 }
1330 
1331 struct node_host *
1332 gen_dynnode(struct node_host *h, sa_family_t af)
1333 {
1334 	struct node_host	*n;
1335 	struct pf_addr		*m;
1336 
1337 	if (h->addr.type != PF_ADDR_DYNIFTL)
1338 		return (NULL);
1339 
1340 	if ((n = calloc(1, sizeof(*n))) == NULL)
1341 		return (NULL);
1342 	bcopy(h, n, sizeof(*n));
1343 	n->ifname = NULL;
1344 	n->next = NULL;
1345 	n->tail = NULL;
1346 
1347 	/* fix up netmask */
1348 	m = &n->addr.v.a.mask;
1349 	if (af == AF_INET && unmask(m, AF_INET6) > 32)
1350 		set_ipmask(n, 32);
1351 
1352 	return (n);
1353 }
1354 
1355 /* interface lookup routines */
1356 
1357 static struct node_host	*iftab;
1358 
1359 /*
1360  * Retrieve the list of groups this interface is a member of and make sure
1361  * each group is in the group map.
1362  */
1363 static void
1364 ifa_add_groups_to_map(char *ifa_name)
1365 {
1366 	int			 s, len;
1367 	struct ifgroupreq	 ifgr;
1368 	struct ifg_req		*ifg;
1369 
1370 	s = get_query_socket();
1371 
1372 	/* Get size of group list for this interface */
1373 	memset(&ifgr, 0, sizeof(ifgr));
1374 	strlcpy(ifgr.ifgr_name, ifa_name, IFNAMSIZ);
1375 	if (ioctl(s, SIOCGIFGROUP, (caddr_t)&ifgr) == -1)
1376 		err(1, "SIOCGIFGROUP");
1377 
1378 	/* Retrieve group list for this interface */
1379 	len = ifgr.ifgr_len;
1380 	ifgr.ifgr_groups =
1381 	    (struct ifg_req *)calloc(len / sizeof(struct ifg_req),
1382 		sizeof(struct ifg_req));
1383 	if (ifgr.ifgr_groups == NULL)
1384 		err(1, "calloc");
1385 	if (ioctl(s, SIOCGIFGROUP, (caddr_t)&ifgr) == -1)
1386 		err(1, "SIOCGIFGROUP");
1387 
1388 	ifg = ifgr.ifgr_groups;
1389 	for (; ifg && len >= sizeof(struct ifg_req); ifg++) {
1390 		len -= sizeof(struct ifg_req);
1391 		if (strcmp(ifg->ifgrq_group, "all")) {
1392 			ENTRY	 		 item;
1393 			ENTRY			*ret_item;
1394 			int			*answer;
1395 
1396 			item.key = ifg->ifgrq_group;
1397 			if (hsearch_r(item, FIND, &ret_item, &isgroup_map) == 0) {
1398 				struct ifgroupreq	 ifgr2;
1399 
1400 				/* Don't know the answer yet */
1401 				if ((answer = malloc(sizeof(int))) == NULL)
1402 					err(1, "malloc");
1403 
1404 				bzero(&ifgr2, sizeof(ifgr2));
1405 				strlcpy(ifgr2.ifgr_name, ifg->ifgrq_group,
1406 				    sizeof(ifgr2.ifgr_name));
1407 				if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr2) == 0)
1408 					*answer = ifgr2.ifgr_len;
1409 				else
1410 					*answer = 0;
1411 
1412 				item.key = strdup(ifg->ifgrq_group);
1413 				item.data = answer;
1414 				if (hsearch_r(item, ENTER, &ret_item,
1415 					&isgroup_map) == 0)
1416 					err(1, "interface group query response"
1417 					    " map insert");
1418 			}
1419 		}
1420 	}
1421 	free(ifgr.ifgr_groups);
1422 }
1423 
1424 void
1425 ifa_load(void)
1426 {
1427 	struct ifaddrs		*ifap, *ifa;
1428 	struct node_host	*n = NULL, *h = NULL;
1429 
1430 	if (getifaddrs(&ifap) < 0)
1431 		err(1, "getifaddrs");
1432 
1433 	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
1434 		if (!(ifa->ifa_addr->sa_family == AF_INET ||
1435 		    ifa->ifa_addr->sa_family == AF_INET6 ||
1436 		    ifa->ifa_addr->sa_family == AF_LINK))
1437 				continue;
1438 		n = calloc(1, sizeof(struct node_host));
1439 		if (n == NULL)
1440 			err(1, "address: calloc");
1441 		n->af = ifa->ifa_addr->sa_family;
1442 		n->ifa_flags = ifa->ifa_flags;
1443 #ifdef __KAME__
1444 		if (n->af == AF_INET6 &&
1445 		    IN6_IS_ADDR_LINKLOCAL(&((struct sockaddr_in6 *)
1446 		    ifa->ifa_addr)->sin6_addr) &&
1447 		    ((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_scope_id ==
1448 		    0) {
1449 			struct sockaddr_in6	*sin6;
1450 
1451 			sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
1452 			sin6->sin6_scope_id = sin6->sin6_addr.s6_addr[2] << 8 |
1453 			    sin6->sin6_addr.s6_addr[3];
1454 			sin6->sin6_addr.s6_addr[2] = 0;
1455 			sin6->sin6_addr.s6_addr[3] = 0;
1456 		}
1457 #endif
1458 		n->ifindex = 0;
1459 		if (n->af == AF_INET) {
1460 			memcpy(&n->addr.v.a.addr, &((struct sockaddr_in *)
1461 			    ifa->ifa_addr)->sin_addr.s_addr,
1462 			    sizeof(struct in_addr));
1463 			memcpy(&n->addr.v.a.mask, &((struct sockaddr_in *)
1464 			    ifa->ifa_netmask)->sin_addr.s_addr,
1465 			    sizeof(struct in_addr));
1466 			if (ifa->ifa_broadaddr != NULL)
1467 				memcpy(&n->bcast, &((struct sockaddr_in *)
1468 				    ifa->ifa_broadaddr)->sin_addr.s_addr,
1469 				    sizeof(struct in_addr));
1470 			if (ifa->ifa_dstaddr != NULL)
1471 				memcpy(&n->peer, &((struct sockaddr_in *)
1472 				    ifa->ifa_dstaddr)->sin_addr.s_addr,
1473 				    sizeof(struct in_addr));
1474 		} else if (n->af == AF_INET6) {
1475 			memcpy(&n->addr.v.a.addr, &((struct sockaddr_in6 *)
1476 			    ifa->ifa_addr)->sin6_addr.s6_addr,
1477 			    sizeof(struct in6_addr));
1478 			memcpy(&n->addr.v.a.mask, &((struct sockaddr_in6 *)
1479 			    ifa->ifa_netmask)->sin6_addr.s6_addr,
1480 			    sizeof(struct in6_addr));
1481 			if (ifa->ifa_broadaddr != NULL)
1482 				memcpy(&n->bcast, &((struct sockaddr_in6 *)
1483 				    ifa->ifa_broadaddr)->sin6_addr.s6_addr,
1484 				    sizeof(struct in6_addr));
1485 			if (ifa->ifa_dstaddr != NULL)
1486 				 memcpy(&n->peer, &((struct sockaddr_in6 *)
1487 				    ifa->ifa_dstaddr)->sin6_addr.s6_addr,
1488 				    sizeof(struct in6_addr));
1489 			n->ifindex = ((struct sockaddr_in6 *)
1490 			    ifa->ifa_addr)->sin6_scope_id;
1491 		} else if (n->af == AF_LINK) {
1492 			ifa_add_groups_to_map(ifa->ifa_name);
1493 		}
1494 		if ((n->ifname = strdup(ifa->ifa_name)) == NULL)
1495 			err(1, "ifa_load: strdup");
1496 		n->next = NULL;
1497 		n->tail = n;
1498 		if (h == NULL)
1499 			h = n;
1500 		else {
1501 			h->tail->next = n;
1502 			h->tail = n;
1503 		}
1504 	}
1505 
1506 	iftab = h;
1507 	freeifaddrs(ifap);
1508 }
1509 
1510 static int
1511 get_socket_domain(void)
1512 {
1513 	int sdom;
1514 
1515 	sdom = AF_UNSPEC;
1516 #ifdef WITH_INET6
1517 	if (sdom == AF_UNSPEC && feature_present("inet6"))
1518 		sdom = AF_INET6;
1519 #endif
1520 #ifdef WITH_INET
1521 	if (sdom == AF_UNSPEC && feature_present("inet"))
1522 		sdom = AF_INET;
1523 #endif
1524 	if (sdom == AF_UNSPEC)
1525 		sdom = AF_LINK;
1526 
1527 	return (sdom);
1528 }
1529 
1530 int
1531 get_query_socket(void)
1532 {
1533 	static int s = -1;
1534 
1535 	if (s == -1) {
1536 		if ((s = socket(get_socket_domain(), SOCK_DGRAM, 0)) == -1)
1537 			err(1, "socket");
1538 	}
1539 
1540 	return (s);
1541 }
1542 
1543 /*
1544  * Returns the response len if the name is a group, otherwise returns 0.
1545  */
1546 static int
1547 is_a_group(char *name)
1548 {
1549 	ENTRY	 		 item;
1550 	ENTRY			*ret_item;
1551 
1552 	item.key = name;
1553 	if (hsearch_r(item, FIND, &ret_item, &isgroup_map) == 0)
1554 		return (0);
1555 
1556 	return (*(int *)ret_item->data);
1557 }
1558 
1559 struct node_host *
1560 ifa_exists(char *ifa_name)
1561 {
1562 	struct node_host	*n;
1563 
1564 	if (iftab == NULL)
1565 		ifa_load();
1566 
1567 	/* check whether this is a group */
1568 	if (is_a_group(ifa_name)) {
1569 		/* fake a node_host */
1570 		if ((n = calloc(1, sizeof(*n))) == NULL)
1571 			err(1, "calloc");
1572 		if ((n->ifname = strdup(ifa_name)) == NULL)
1573 			err(1, "strdup");
1574 		return (n);
1575 	}
1576 
1577 	for (n = iftab; n; n = n->next) {
1578 		if (n->af == AF_LINK && !strncmp(n->ifname, ifa_name, IFNAMSIZ))
1579 			return (n);
1580 	}
1581 
1582 	return (NULL);
1583 }
1584 
1585 struct node_host *
1586 ifa_grouplookup(char *ifa_name, int flags)
1587 {
1588 	struct ifg_req		*ifg;
1589 	struct ifgroupreq	 ifgr;
1590 	int			 s, len;
1591 	struct node_host	*n, *h = NULL;
1592 
1593 	s = get_query_socket();
1594 	len = is_a_group(ifa_name);
1595 	if (len == 0)
1596 		return (NULL);
1597 	bzero(&ifgr, sizeof(ifgr));
1598 	strlcpy(ifgr.ifgr_name, ifa_name, sizeof(ifgr.ifgr_name));
1599 	ifgr.ifgr_len = len;
1600 	if ((ifgr.ifgr_groups = calloc(1, len)) == NULL)
1601 		err(1, "calloc");
1602 	if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == -1)
1603 		err(1, "SIOCGIFGMEMB");
1604 
1605 	for (ifg = ifgr.ifgr_groups; ifg && len >= sizeof(struct ifg_req);
1606 	    ifg++) {
1607 		len -= sizeof(struct ifg_req);
1608 		if ((n = ifa_lookup(ifg->ifgrq_member, flags)) == NULL)
1609 			continue;
1610 		if (h == NULL)
1611 			h = n;
1612 		else {
1613 			h->tail->next = n;
1614 			h->tail = n->tail;
1615 		}
1616 	}
1617 	free(ifgr.ifgr_groups);
1618 
1619 	return (h);
1620 }
1621 
1622 struct node_host *
1623 ifa_lookup(char *ifa_name, int flags)
1624 {
1625 	struct node_host	*p = NULL, *h = NULL, *n = NULL;
1626 	int			 got4 = 0, got6 = 0;
1627 	const char		 *last_if = NULL;
1628 
1629 	/* first load iftab and isgroup_map */
1630 	if (iftab == NULL)
1631 		ifa_load();
1632 
1633 	if ((h = ifa_grouplookup(ifa_name, flags)) != NULL)
1634 		return (h);
1635 
1636 	if (!strncmp(ifa_name, "self", IFNAMSIZ))
1637 		ifa_name = NULL;
1638 
1639 	for (p = iftab; p; p = p->next) {
1640 		if (ifa_skip_if(ifa_name, p))
1641 			continue;
1642 		if ((flags & PFI_AFLAG_BROADCAST) && p->af != AF_INET)
1643 			continue;
1644 		if ((flags & PFI_AFLAG_BROADCAST) &&
1645 		    !(p->ifa_flags & IFF_BROADCAST))
1646 			continue;
1647 		if ((flags & PFI_AFLAG_PEER) &&
1648 		    !(p->ifa_flags & IFF_POINTOPOINT))
1649 			continue;
1650 		if ((flags & PFI_AFLAG_NETWORK) && p->ifindex > 0)
1651 			continue;
1652 		if (last_if == NULL || strcmp(last_if, p->ifname))
1653 			got4 = got6 = 0;
1654 		last_if = p->ifname;
1655 		if ((flags & PFI_AFLAG_NOALIAS) && p->af == AF_INET && got4)
1656 			continue;
1657 		if ((flags & PFI_AFLAG_NOALIAS) && p->af == AF_INET6 &&
1658 		    IN6_IS_ADDR_LINKLOCAL(&p->addr.v.a.addr.v6))
1659 			continue;
1660 		if ((flags & PFI_AFLAG_NOALIAS) && p->af == AF_INET6 && got6)
1661 			continue;
1662 		if (p->af == AF_INET)
1663 			got4 = 1;
1664 		else
1665 			got6 = 1;
1666 		n = calloc(1, sizeof(struct node_host));
1667 		if (n == NULL)
1668 			err(1, "address: calloc");
1669 		n->af = p->af;
1670 		if (flags & PFI_AFLAG_BROADCAST)
1671 			memcpy(&n->addr.v.a.addr, &p->bcast,
1672 			    sizeof(struct pf_addr));
1673 		else if (flags & PFI_AFLAG_PEER)
1674 			memcpy(&n->addr.v.a.addr, &p->peer,
1675 			    sizeof(struct pf_addr));
1676 		else
1677 			memcpy(&n->addr.v.a.addr, &p->addr.v.a.addr,
1678 			    sizeof(struct pf_addr));
1679 		if (flags & PFI_AFLAG_NETWORK)
1680 			set_ipmask(n, unmask(&p->addr.v.a.mask, n->af));
1681 		else {
1682 			if (n->af == AF_INET) {
1683 				if (p->ifa_flags & IFF_LOOPBACK &&
1684 				    p->ifa_flags & IFF_LINK1)
1685 					memcpy(&n->addr.v.a.mask,
1686 					    &p->addr.v.a.mask,
1687 					    sizeof(struct pf_addr));
1688 				else
1689 					set_ipmask(n, 32);
1690 			} else
1691 				set_ipmask(n, 128);
1692 		}
1693 		n->ifindex = p->ifindex;
1694 		n->ifname = strdup(p->ifname);
1695 
1696 		n->next = NULL;
1697 		n->tail = n;
1698 		if (h == NULL)
1699 			h = n;
1700 		else {
1701 			h->tail->next = n;
1702 			h->tail = n;
1703 		}
1704 	}
1705 	return (h);
1706 }
1707 
1708 int
1709 ifa_skip_if(const char *filter, struct node_host *p)
1710 {
1711 	int	n;
1712 
1713 	if (p->af != AF_INET && p->af != AF_INET6)
1714 		return (1);
1715 	if (filter == NULL || !*filter)
1716 		return (0);
1717 	if (!strcmp(p->ifname, filter))
1718 		return (0);	/* exact match */
1719 	n = strlen(filter);
1720 	if (n < 1 || n >= IFNAMSIZ)
1721 		return (1);	/* sanity check */
1722 	if (filter[n-1] >= '0' && filter[n-1] <= '9')
1723 		return (1);	/* only do exact match in that case */
1724 	if (strncmp(p->ifname, filter, n))
1725 		return (1);	/* prefix doesn't match */
1726 	return (p->ifname[n] < '0' || p->ifname[n] > '9');
1727 }
1728 
1729 
1730 struct node_host *
1731 host(const char *s)
1732 {
1733 	struct node_host	*h = NULL;
1734 	int			 mask, v4mask, v6mask, cont = 1;
1735 	char			*p, *q, *ps;
1736 
1737 	if ((p = strrchr(s, '/')) != NULL) {
1738 		mask = strtol(p+1, &q, 0);
1739 		if (!q || *q || mask > 128 || q == (p+1)) {
1740 			fprintf(stderr, "invalid netmask '%s'\n", p);
1741 			return (NULL);
1742 		}
1743 		if ((ps = malloc(strlen(s) - strlen(p) + 1)) == NULL)
1744 			err(1, "host: malloc");
1745 		strlcpy(ps, s, strlen(s) - strlen(p) + 1);
1746 		v4mask = v6mask = mask;
1747 	} else {
1748 		if ((ps = strdup(s)) == NULL)
1749 			err(1, "host: strdup");
1750 		v4mask = 32;
1751 		v6mask = 128;
1752 		mask = -1;
1753 	}
1754 
1755 	/* IPv4 address? */
1756 	if (cont && (h = host_v4(s, mask)) != NULL)
1757 		cont = 0;
1758 
1759 	/* IPv6 address? */
1760 	if (cont && (h = host_v6(ps, v6mask)) != NULL)
1761 		cont = 0;
1762 
1763 	/* interface with this name exists? */
1764 	/* expensive with thousands of interfaces - prioritze IPv4/6 check */
1765 	if (cont && (h = host_if(ps, mask, &cont)) != NULL)
1766 		cont = 0;
1767 
1768 	/* dns lookup */
1769 	if (cont && (h = host_dns(ps, v4mask, v6mask)) != NULL)
1770 		cont = 0;
1771 	free(ps);
1772 
1773 	if (h == NULL || cont == 1) {
1774 		fprintf(stderr, "no IP address found for %s\n", s);
1775 		return (NULL);
1776 	}
1777 	return (h);
1778 }
1779 
1780 struct node_host *
1781 host_if(const char *s, int mask, int *cont)
1782 {
1783 	struct node_host	*n, *h = NULL;
1784 	char			*p, *ps;
1785 	int			 flags = 0;
1786 
1787 	if ((ps = strdup(s)) == NULL)
1788 		err(1, "host_if: strdup");
1789 	while ((p = strrchr(ps, ':')) != NULL) {
1790 		if (!strcmp(p+1, "network"))
1791 			flags |= PFI_AFLAG_NETWORK;
1792 		else if (!strcmp(p+1, "broadcast"))
1793 			flags |= PFI_AFLAG_BROADCAST;
1794 		else if (!strcmp(p+1, "peer"))
1795 			flags |= PFI_AFLAG_PEER;
1796 		else if (!strcmp(p+1, "0"))
1797 			flags |= PFI_AFLAG_NOALIAS;
1798 		else {
1799 			free(ps);
1800 			return (NULL);
1801 		}
1802 		*p = '\0';
1803 		*cont = 0;
1804 	}
1805 	if (flags & (flags - 1) & PFI_AFLAG_MODEMASK) { /* Yep! */
1806 		fprintf(stderr, "illegal combination of interface modifiers\n");
1807 		free(ps);
1808 		return (NULL);
1809 	}
1810 	if ((flags & (PFI_AFLAG_NETWORK|PFI_AFLAG_BROADCAST)) && mask > -1) {
1811 		fprintf(stderr, "network or broadcast lookup, but "
1812 		    "extra netmask given\n");
1813 		free(ps);
1814 		return (NULL);
1815 	}
1816 	if (ifa_exists(ps) || !strncmp(ps, "self", IFNAMSIZ)) {
1817 		/* interface with this name exists */
1818 		h = ifa_lookup(ps, flags);
1819 		for (n = h; n != NULL && mask > -1; n = n->next)
1820 			set_ipmask(n, mask);
1821 	}
1822 
1823 	free(ps);
1824 	return (h);
1825 }
1826 
1827 struct node_host *
1828 host_v4(const char *s, int mask)
1829 {
1830 	struct node_host	*h = NULL;
1831 	struct in_addr		 ina;
1832 	int			 bits = 32;
1833 
1834 	memset(&ina, 0, sizeof(struct in_addr));
1835 	if (strrchr(s, '/') != NULL) {
1836 		if ((bits = inet_net_pton(AF_INET, s, &ina, sizeof(ina))) == -1)
1837 			return (NULL);
1838 	} else {
1839 		if (inet_pton(AF_INET, s, &ina) != 1)
1840 			return (NULL);
1841 	}
1842 
1843 	h = calloc(1, sizeof(struct node_host));
1844 	if (h == NULL)
1845 		err(1, "address: calloc");
1846 	h->ifname = NULL;
1847 	h->af = AF_INET;
1848 	h->addr.v.a.addr.addr32[0] = ina.s_addr;
1849 	set_ipmask(h, bits);
1850 	h->next = NULL;
1851 	h->tail = h;
1852 
1853 	return (h);
1854 }
1855 
1856 struct node_host *
1857 host_v6(const char *s, int mask)
1858 {
1859 	struct addrinfo		 hints, *res;
1860 	struct node_host	*h = NULL;
1861 
1862 	memset(&hints, 0, sizeof(hints));
1863 	hints.ai_family = AF_INET6;
1864 	hints.ai_socktype = SOCK_DGRAM; /*dummy*/
1865 	hints.ai_flags = AI_NUMERICHOST;
1866 	if (getaddrinfo(s, "0", &hints, &res) == 0) {
1867 		h = calloc(1, sizeof(struct node_host));
1868 		if (h == NULL)
1869 			err(1, "address: calloc");
1870 		h->ifname = NULL;
1871 		h->af = AF_INET6;
1872 		memcpy(&h->addr.v.a.addr,
1873 		    &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr,
1874 		    sizeof(h->addr.v.a.addr));
1875 		h->ifindex =
1876 		    ((struct sockaddr_in6 *)res->ai_addr)->sin6_scope_id;
1877 		set_ipmask(h, mask);
1878 		freeaddrinfo(res);
1879 		h->next = NULL;
1880 		h->tail = h;
1881 	}
1882 
1883 	return (h);
1884 }
1885 
1886 struct node_host *
1887 host_dns(const char *s, int v4mask, int v6mask)
1888 {
1889 	struct addrinfo		 hints, *res0, *res;
1890 	struct node_host	*n, *h = NULL;
1891 	int			 error, noalias = 0;
1892 	int			 got4 = 0, got6 = 0;
1893 	char			*p, *ps;
1894 
1895 	if ((ps = strdup(s)) == NULL)
1896 		err(1, "host_dns: strdup");
1897 	if ((p = strrchr(ps, ':')) != NULL && !strcmp(p, ":0")) {
1898 		noalias = 1;
1899 		*p = '\0';
1900 	}
1901 	memset(&hints, 0, sizeof(hints));
1902 	hints.ai_family = PF_UNSPEC;
1903 	hints.ai_socktype = SOCK_STREAM; /* DUMMY */
1904 	error = getaddrinfo(ps, NULL, &hints, &res0);
1905 	if (error) {
1906 		free(ps);
1907 		return (h);
1908 	}
1909 
1910 	for (res = res0; res; res = res->ai_next) {
1911 		if (res->ai_family != AF_INET &&
1912 		    res->ai_family != AF_INET6)
1913 			continue;
1914 		if (noalias) {
1915 			if (res->ai_family == AF_INET) {
1916 				if (got4)
1917 					continue;
1918 				got4 = 1;
1919 			} else {
1920 				if (got6)
1921 					continue;
1922 				got6 = 1;
1923 			}
1924 		}
1925 		n = calloc(1, sizeof(struct node_host));
1926 		if (n == NULL)
1927 			err(1, "host_dns: calloc");
1928 		n->ifname = NULL;
1929 		n->af = res->ai_family;
1930 		if (res->ai_family == AF_INET) {
1931 			memcpy(&n->addr.v.a.addr,
1932 			    &((struct sockaddr_in *)
1933 			    res->ai_addr)->sin_addr.s_addr,
1934 			    sizeof(struct in_addr));
1935 			set_ipmask(n, v4mask);
1936 		} else {
1937 			memcpy(&n->addr.v.a.addr,
1938 			    &((struct sockaddr_in6 *)
1939 			    res->ai_addr)->sin6_addr.s6_addr,
1940 			    sizeof(struct in6_addr));
1941 			n->ifindex =
1942 			    ((struct sockaddr_in6 *)
1943 			    res->ai_addr)->sin6_scope_id;
1944 			set_ipmask(n, v6mask);
1945 		}
1946 		n->next = NULL;
1947 		n->tail = n;
1948 		if (h == NULL)
1949 			h = n;
1950 		else {
1951 			h->tail->next = n;
1952 			h->tail = n;
1953 		}
1954 	}
1955 	freeaddrinfo(res0);
1956 	free(ps);
1957 
1958 	return (h);
1959 }
1960 
1961 /*
1962  * convert a hostname to a list of addresses and put them in the given buffer.
1963  * test:
1964  *	if set to 1, only simple addresses are accepted (no netblock, no "!").
1965  */
1966 int
1967 append_addr(struct pfr_buffer *b, char *s, int test)
1968 {
1969 	char			 *r;
1970 	struct node_host	*h, *n;
1971 	int			 rv, not = 0;
1972 
1973 	for (r = s; *r == '!'; r++)
1974 		not = !not;
1975 	if ((n = host(r)) == NULL) {
1976 		errno = 0;
1977 		return (-1);
1978 	}
1979 	rv = append_addr_host(b, n, test, not);
1980 	do {
1981 		h = n;
1982 		n = n->next;
1983 		free(h);
1984 	} while (n != NULL);
1985 	return (rv);
1986 }
1987 
1988 /*
1989  * same as previous function, but with a pre-parsed input and the ability
1990  * to "negate" the result. Does not free the node_host list.
1991  * not:
1992  *      setting it to 1 is equivalent to adding "!" in front of parameter s.
1993  */
1994 int
1995 append_addr_host(struct pfr_buffer *b, struct node_host *n, int test, int not)
1996 {
1997 	int			 bits;
1998 	struct pfr_addr		 addr;
1999 
2000 	do {
2001 		bzero(&addr, sizeof(addr));
2002 		addr.pfra_not = n->not ^ not;
2003 		addr.pfra_af = n->af;
2004 		addr.pfra_net = unmask(&n->addr.v.a.mask, n->af);
2005 		switch (n->af) {
2006 		case AF_INET:
2007 			addr.pfra_ip4addr.s_addr = n->addr.v.a.addr.addr32[0];
2008 			bits = 32;
2009 			break;
2010 		case AF_INET6:
2011 			memcpy(&addr.pfra_ip6addr, &n->addr.v.a.addr.v6,
2012 			    sizeof(struct in6_addr));
2013 			bits = 128;
2014 			break;
2015 		default:
2016 			errno = EINVAL;
2017 			return (-1);
2018 		}
2019 		if ((test && (not || addr.pfra_net != bits)) ||
2020 		    addr.pfra_net > bits) {
2021 			errno = EINVAL;
2022 			return (-1);
2023 		}
2024 		if (pfr_buf_add(b, &addr))
2025 			return (-1);
2026 	} while ((n = n->next) != NULL);
2027 
2028 	return (0);
2029 }
2030 
2031 int
2032 pfctl_add_trans(struct pfr_buffer *buf, int rs_num, const char *anchor)
2033 {
2034 	struct pfioc_trans_e trans;
2035 
2036 	bzero(&trans, sizeof(trans));
2037 	trans.rs_num = rs_num;
2038 	if (strlcpy(trans.anchor, anchor,
2039 	    sizeof(trans.anchor)) >= sizeof(trans.anchor))
2040 		errx(1, "pfctl_add_trans: strlcpy");
2041 
2042 	return pfr_buf_add(buf, &trans);
2043 }
2044 
2045 u_int32_t
2046 pfctl_get_ticket(struct pfr_buffer *buf, int rs_num, const char *anchor)
2047 {
2048 	struct pfioc_trans_e *p;
2049 
2050 	PFRB_FOREACH(p, buf)
2051 		if (rs_num == p->rs_num && !strcmp(anchor, p->anchor))
2052 			return (p->ticket);
2053 	errx(1, "pfctl_get_ticket: assertion failed");
2054 }
2055 
2056 int
2057 pfctl_trans(int dev, struct pfr_buffer *buf, u_long cmd, int from)
2058 {
2059 	struct pfioc_trans trans;
2060 
2061 	bzero(&trans, sizeof(trans));
2062 	trans.size = buf->pfrb_size - from;
2063 	trans.esize = sizeof(struct pfioc_trans_e);
2064 	trans.array = ((struct pfioc_trans_e *)buf->pfrb_caddr) + from;
2065 	return ioctl(dev, cmd, &trans);
2066 }
2067