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