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