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