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