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