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