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