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