xref: /openbsd-src/sbin/pfctl/pfctl_parser.c (revision 897fc685943471cf985a0fe38ba076ea6fe74fa5)
1 /*	$OpenBSD: pfctl_parser.c,v 1.319 2018/02/08 02:26:39 henning Exp $ */
2 
3 /*
4  * Copyright (c) 2001 Daniel Hartmeier
5  * Copyright (c) 2002 - 2013 Henning Brauer <henning@openbsd.org>
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  *    - Redistributions of source code must retain the above copyright
13  *      notice, this list of conditions and the following disclaimer.
14  *    - Redistributions in binary form must reproduce the above
15  *      copyright notice, this list of conditions and the following
16  *      disclaimer in the documentation and/or other materials provided
17  *      with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
22  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
23  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
24  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
25  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
29  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  *
32  */
33 
34 #include <sys/types.h>
35 #include <sys/ioctl.h>
36 #include <sys/socket.h>
37 #include <net/if_dl.h>
38 #include <net/if.h>
39 #include <netinet/in.h>
40 #include <netinet/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, struct pfctl_watermarks *synflwats, 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 	if (opts & PF_OPT_VERBOSE) {
636 		printf("Adaptive Syncookies Watermarks\n");
637 		printf("  %-25s %14d states\n", "start", synflwats->hi);
638 		printf("  %-25s %14d states\n", "end", synflwats->lo);
639 	}
640 }
641 
642 void
643 print_src_node(struct pf_src_node *sn, int opts)
644 {
645 	struct pf_addr_wrap aw;
646 	int min, sec;
647 
648 	memset(&aw, 0, sizeof(aw));
649 	if (sn->af == AF_INET)
650 		aw.v.a.mask.addr32[0] = 0xffffffff;
651 	else
652 		memset(&aw.v.a.mask, 0xff, sizeof(aw.v.a.mask));
653 
654 	aw.v.a.addr = sn->addr;
655 	print_addr(&aw, sn->af, opts & PF_OPT_VERBOSE2);
656 
657 	if (!PF_AZERO(&sn->raddr, sn->af)) {
658 		if (sn->type == PF_SN_NAT)
659 			printf(" nat-to ");
660 		else if (sn->type == PF_SN_RDR)
661 			printf(" rdr-to ");
662 		else if (sn->type == PF_SN_ROUTE)
663 			printf(" route-to ");
664 		else
665 			printf(" ??? (%u) ", sn->type);
666 		aw.v.a.addr = sn->raddr;
667 		print_addr(&aw, sn->naf ? sn->naf : sn->af,
668 		    opts & PF_OPT_VERBOSE2);
669 	}
670 
671 	printf(" ( states %u, connections %u, rate %u.%u/%us )\n", sn->states,
672 	    sn->conn, sn->conn_rate.count / 1000,
673 	    (sn->conn_rate.count % 1000) / 100, sn->conn_rate.seconds);
674 	if (opts & PF_OPT_VERBOSE) {
675 		sec = sn->creation % 60;
676 		sn->creation /= 60;
677 		min = sn->creation % 60;
678 		sn->creation /= 60;
679 		printf("   age %.2u:%.2u:%.2u", sn->creation, min, sec);
680 		if (sn->states == 0) {
681 			sec = sn->expire % 60;
682 			sn->expire /= 60;
683 			min = sn->expire % 60;
684 			sn->expire /= 60;
685 			printf(", expires in %.2u:%.2u:%.2u",
686 			    sn->expire, min, sec);
687 		}
688 		printf(", %llu pkts, %llu bytes",
689 		    sn->packets[0] + sn->packets[1],
690 		    sn->bytes[0] + sn->bytes[1]);
691 		if (sn->rule.nr != -1)
692 			printf(", rule %u", sn->rule.nr);
693 		printf("\n");
694 	}
695 }
696 
697 void
698 print_rule(struct pf_rule *r, const char *anchor_call, int opts)
699 {
700 	static const char *actiontypes[] = { "pass", "block", "scrub",
701 	    "no scrub", "nat", "no nat", "binat", "no binat", "rdr", "no rdr",
702 	    "", "", "match"};
703 	static const char *anchortypes[] = { "anchor", "anchor", "anchor",
704 	    "anchor", "nat-anchor", "nat-anchor", "binat-anchor",
705 	    "binat-anchor", "rdr-anchor", "rdr-anchor" };
706 	int	i, ropts;
707 	int	verbose = opts & (PF_OPT_VERBOSE2 | PF_OPT_DEBUG);
708 	char	*p;
709 
710 	if ((r->rule_flag & PFRULE_EXPIRED) && (!verbose))
711 		return;
712 
713 	if (verbose)
714 		printf("@%d ", r->nr);
715 
716 	if (r->action > PF_MATCH)
717 		printf("action(%d)", r->action);
718 	else if (anchor_call[0]) {
719 		p = strrchr(anchor_call, '/');
720 		if (p ? p[1] == '_' : anchor_call[0] == '_')
721 			printf("%s", anchortypes[r->action]);
722 		else
723 			printf("%s \"%s\"", anchortypes[r->action],
724 			    anchor_call);
725 	} else
726 		printf("%s", actiontypes[r->action]);
727 	if (r->action == PF_DROP) {
728 		if (r->rule_flag & PFRULE_RETURN)
729 			printf(" return");
730 		else if (r->rule_flag & PFRULE_RETURNRST) {
731 			if (!r->return_ttl)
732 				printf(" return-rst");
733 			else
734 				printf(" return-rst(ttl %d)", r->return_ttl);
735 		} else if (r->rule_flag & PFRULE_RETURNICMP) {
736 			const struct icmpcodeent	*ic, *ic6;
737 
738 			ic = geticmpcodebynumber(r->return_icmp >> 8,
739 			    r->return_icmp & 255, AF_INET);
740 			ic6 = geticmpcodebynumber(r->return_icmp6 >> 8,
741 			    r->return_icmp6 & 255, AF_INET6);
742 
743 			switch (r->af) {
744 			case AF_INET:
745 				printf(" return-icmp");
746 				if (ic == NULL)
747 					printf("(%u)", r->return_icmp & 255);
748 				else
749 					printf("(%s)", ic->name);
750 				break;
751 			case AF_INET6:
752 				printf(" return-icmp6");
753 				if (ic6 == NULL)
754 					printf("(%u)", r->return_icmp6 & 255);
755 				else
756 					printf("(%s)", ic6->name);
757 				break;
758 			default:
759 				printf(" return-icmp");
760 				if (ic == NULL)
761 					printf("(%u, ", r->return_icmp & 255);
762 				else
763 					printf("(%s, ", ic->name);
764 				if (ic6 == NULL)
765 					printf("%u)", r->return_icmp6 & 255);
766 				else
767 					printf("%s)", ic6->name);
768 				break;
769 			}
770 		} else
771 			printf(" drop");
772 	}
773 	if (r->direction == PF_IN)
774 		printf(" in");
775 	else if (r->direction == PF_OUT)
776 		printf(" out");
777 	if (r->log) {
778 		printf(" log");
779 		if (r->log & ~PF_LOG || r->logif) {
780 			int count = 0;
781 
782 			printf(" (");
783 			if (r->log & PF_LOG_ALL)
784 				printf("%sall", count++ ? ", " : "");
785 			if (r->log & PF_LOG_MATCHES)
786 				printf("%smatches", count++ ? ", " : "");
787 			if (r->log & PF_LOG_SOCKET_LOOKUP)
788 				printf("%suser", count++ ? ", " : "");
789 			if (r->logif)
790 				printf("%sto pflog%u", count++ ? ", " : "",
791 				    r->logif);
792 			printf(")");
793 		}
794 	}
795 	if (r->quick)
796 		printf(" quick");
797 	if (r->ifname[0]) {
798 		if (r->ifnot)
799 			printf(" on ! %s", r->ifname);
800 		else
801 			printf(" on %s", r->ifname);
802 	}
803 	if (r->onrdomain >= 0) {
804 		if (r->ifnot)
805 			printf(" on ! rdomain %d", r->onrdomain);
806 		else
807 			printf(" on rdomain %d", r->onrdomain);
808 	}
809 	if (r->af) {
810 		if (r->af == AF_INET)
811 			printf(" inet");
812 		else
813 			printf(" inet6");
814 	}
815 	if (r->proto) {
816 		struct protoent	*p;
817 
818 		if ((p = getprotobynumber(r->proto)) != NULL)
819 			printf(" proto %s", p->p_name);
820 		else
821 			printf(" proto %u", r->proto);
822 	}
823 	print_fromto(&r->src, r->os_fingerprint, &r->dst, r->af, r->proto,
824 	    opts);
825 	if (r->rcv_ifname[0])
826 		printf(" %sreceived-on %s", r->rcvifnot ? "!" : "",
827 		    r->rcv_ifname);
828 	if (r->uid.op)
829 		print_ugid(r->uid.op, r->uid.uid[0], r->uid.uid[1], "user",
830 		    UID_MAX);
831 	if (r->gid.op)
832 		print_ugid(r->gid.op, r->gid.gid[0], r->gid.gid[1], "group",
833 		    GID_MAX);
834 	if (r->flags || r->flagset) {
835 		printf(" flags ");
836 		print_flags(r->flags);
837 		printf("/");
838 		print_flags(r->flagset);
839 	} else if ((r->action == PF_PASS || r->action == PF_MATCH) &&
840 	    (!r->proto || r->proto == IPPROTO_TCP) &&
841 	    !(r->rule_flag & PFRULE_FRAGMENT) &&
842 	    !anchor_call[0] && r->keep_state)
843 		printf(" flags any");
844 	if (r->type) {
845 		const struct icmptypeent	*it;
846 
847 		it = geticmptypebynumber(r->type-1, r->af);
848 		if (r->af != AF_INET6)
849 			printf(" icmp-type");
850 		else
851 			printf(" icmp6-type");
852 		if (it != NULL)
853 			printf(" %s", it->name);
854 		else
855 			printf(" %u", r->type-1);
856 		if (r->code) {
857 			const struct icmpcodeent	*ic;
858 
859 			ic = geticmpcodebynumber(r->type-1, r->code-1, r->af);
860 			if (ic != NULL)
861 				printf(" code %s", ic->name);
862 			else
863 				printf(" code %u", r->code-1);
864 		}
865 	}
866 	if (r->tos)
867 		printf(" tos 0x%2.2x", r->tos);
868 	if (r->prio)
869 		printf(" prio %u", r->prio == PF_PRIO_ZERO ? 0 : r->prio);
870 	if (r->pktrate.limit)
871 		printf(" max-pkt-rate %u/%u", r->pktrate.limit,
872 		    r->pktrate.seconds);
873 
874 	if (r->scrub_flags & PFSTATE_SETMASK || r->qname[0]) {
875 		char *comma = "";
876 		printf(" set (");
877 		if (r->scrub_flags & PFSTATE_SETPRIO) {
878 			if (r->set_prio[0] == r->set_prio[1])
879 				printf("%s prio %u", comma, r->set_prio[0]);
880 			else
881 				printf("%s prio(%u, %u)", comma, r->set_prio[0],
882 				    r->set_prio[1]);
883 			comma = ",";
884 		}
885 		if (r->qname[0]) {
886 			if (r->pqname[0])
887 				printf("%s queue(%s, %s)", comma, r->qname,
888 				    r->pqname);
889 			else
890 				printf("%s queue %s", comma, r->qname);
891 			comma = ",";
892 		}
893 		if (r->scrub_flags & PFSTATE_SETTOS) {
894 			printf("%s tos 0x%2.2x", comma, r->set_tos);
895 			comma = ",";
896 		}
897 		printf(" )");
898 	}
899 
900 	ropts = 0;
901 	if (r->max_states || r->max_src_nodes || r->max_src_states)
902 		ropts = 1;
903 	if (r->rule_flag & PFRULE_NOSYNC)
904 		ropts = 1;
905 	if (r->rule_flag & PFRULE_SRCTRACK)
906 		ropts = 1;
907 	if (r->rule_flag & PFRULE_IFBOUND)
908 		ropts = 1;
909 	if (r->rule_flag & PFRULE_STATESLOPPY)
910 		ropts = 1;
911 	if (r->rule_flag & PFRULE_PFLOW)
912 		ropts = 1;
913 	for (i = 0; !ropts && i < PFTM_MAX; ++i)
914 		if (r->timeout[i])
915 			ropts = 1;
916 
917 	if (!r->keep_state && r->action == PF_PASS && !anchor_call[0])
918 		printf(" no state");
919 	else if (r->keep_state == PF_STATE_NORMAL && ropts)
920 		printf(" keep state");
921 	else if (r->keep_state == PF_STATE_MODULATE)
922 		printf(" modulate state");
923 	else if (r->keep_state == PF_STATE_SYNPROXY)
924 		printf(" synproxy state");
925 	if (r->prob) {
926 		char	buf[20];
927 
928 		snprintf(buf, sizeof(buf), "%f", r->prob*100.0/(UINT_MAX+1.0));
929 		for (i = strlen(buf)-1; i > 0; i--) {
930 			if (buf[i] == '0')
931 				buf[i] = '\0';
932 			else {
933 				if (buf[i] == '.')
934 					buf[i] = '\0';
935 				break;
936 			}
937 		}
938 		printf(" probability %s%%", buf);
939 	}
940 	if (ropts) {
941 		printf(" (");
942 		if (r->max_states) {
943 			printf("max %u", r->max_states);
944 			ropts = 0;
945 		}
946 		if (r->rule_flag & PFRULE_NOSYNC) {
947 			if (!ropts)
948 				printf(", ");
949 			printf("no-sync");
950 			ropts = 0;
951 		}
952 		if (r->rule_flag & PFRULE_SRCTRACK) {
953 			if (!ropts)
954 				printf(", ");
955 			printf("source-track");
956 			if (r->rule_flag & PFRULE_RULESRCTRACK)
957 				printf(" rule");
958 			else
959 				printf(" global");
960 			ropts = 0;
961 		}
962 		if (r->max_src_states) {
963 			if (!ropts)
964 				printf(", ");
965 			printf("max-src-states %u", r->max_src_states);
966 			ropts = 0;
967 		}
968 		if (r->max_src_conn) {
969 			if (!ropts)
970 				printf(", ");
971 			printf("max-src-conn %u", r->max_src_conn);
972 			ropts = 0;
973 		}
974 		if (r->max_src_conn_rate.limit) {
975 			if (!ropts)
976 				printf(", ");
977 			printf("max-src-conn-rate %u/%u",
978 			    r->max_src_conn_rate.limit,
979 			    r->max_src_conn_rate.seconds);
980 			ropts = 0;
981 		}
982 		if (r->max_src_nodes) {
983 			if (!ropts)
984 				printf(", ");
985 			printf("max-src-nodes %u", r->max_src_nodes);
986 			ropts = 0;
987 		}
988 		if (r->overload_tblname[0]) {
989 			if (!ropts)
990 				printf(", ");
991 			printf("overload <%s>", r->overload_tblname);
992 			if (r->flush)
993 				printf(" flush");
994 			if (r->flush & PF_FLUSH_GLOBAL)
995 				printf(" global");
996 		}
997 		if (r->rule_flag & PFRULE_IFBOUND) {
998 			if (!ropts)
999 				printf(", ");
1000 			printf("if-bound");
1001 			ropts = 0;
1002 		}
1003 		if (r->rule_flag & PFRULE_STATESLOPPY) {
1004 			if (!ropts)
1005 				printf(", ");
1006 			printf("sloppy");
1007 			ropts = 0;
1008 		}
1009 		if (r->rule_flag & PFRULE_PFLOW) {
1010 			if (!ropts)
1011 				printf(", ");
1012 			printf("pflow");
1013 			ropts = 0;
1014 		}
1015 		for (i = 0; i < PFTM_MAX; ++i)
1016 			if (r->timeout[i]) {
1017 				int j;
1018 
1019 				if (!ropts)
1020 					printf(", ");
1021 				ropts = 0;
1022 				for (j = 0; pf_timeouts[j].name != NULL;
1023 				    ++j)
1024 					if (pf_timeouts[j].timeout == i)
1025 						break;
1026 				printf("%s %u", pf_timeouts[j].name == NULL ?
1027 				    "inv.timeout" : pf_timeouts[j].name,
1028 				    r->timeout[i]);
1029 			}
1030 		printf(")");
1031 	}
1032 
1033 	if (r->rule_flag & PFRULE_FRAGMENT)
1034 		printf(" fragment");
1035 
1036 	if (r->scrub_flags & PFSTATE_SCRUBMASK || r->min_ttl || r->max_mss) {
1037 		printf(" scrub (");
1038 		ropts = 1;
1039 		if (r->scrub_flags & PFSTATE_NODF) {
1040 			printf("no-df");
1041 			ropts = 0;
1042 		}
1043 		if (r->scrub_flags & PFSTATE_RANDOMID) {
1044 			if (!ropts)
1045 				printf(" ");
1046 			printf("random-id");
1047 			ropts = 0;
1048 		}
1049 		if (r->min_ttl) {
1050 			if (!ropts)
1051 				printf(" ");
1052 			printf("min-ttl %d", r->min_ttl);
1053 			ropts = 0;
1054 		}
1055 		if (r->scrub_flags & PFSTATE_SCRUB_TCP) {
1056 			if (!ropts)
1057 				printf(" ");
1058 			printf("reassemble tcp");
1059 			ropts = 0;
1060 		}
1061 		if (r->max_mss) {
1062 			if (!ropts)
1063 				printf(" ");
1064 			printf("max-mss %d", r->max_mss);
1065 			ropts = 0;
1066 		}
1067 		printf(")");
1068 	}
1069 
1070 	if (r->allow_opts)
1071 		printf(" allow-opts");
1072 	if (r->label[0])
1073 		printf(" label \"%s\"", r->label);
1074 	if (r->rule_flag & PFRULE_ONCE)
1075 		printf(" once");
1076 	if (r->tagname[0])
1077 		printf(" tag %s", r->tagname);
1078 	if (r->match_tagname[0]) {
1079 		if (r->match_tag_not)
1080 			printf(" !");
1081 		printf(" tagged %s", r->match_tagname);
1082 	}
1083 	if (r->rtableid != -1)
1084 		printf(" rtable %u", r->rtableid);
1085 	switch (r->divert.type) {
1086 	case PF_DIVERT_NONE:
1087 		break;
1088 	case PF_DIVERT_TO: {
1089 		/* XXX cut&paste from print_addr */
1090 		char buf[48];
1091 
1092 		printf(" divert-to ");
1093 		if (inet_ntop(r->af, &r->divert.addr, buf, sizeof(buf)) == NULL)
1094 			printf("?");
1095 		else
1096 			printf("%s", buf);
1097 		printf(" port %u", ntohs(r->divert.port));
1098 		break;
1099 	}
1100 	case PF_DIVERT_REPLY:
1101 		printf(" divert-reply");
1102 		break;
1103 	case PF_DIVERT_PACKET:
1104 		printf(" divert-packet port %u", ntohs(r->divert.port));
1105 		break;
1106 	default:
1107 		printf(" divert ???");
1108 		break;
1109 	}
1110 
1111 	if (!anchor_call[0] && r->nat.addr.type != PF_ADDR_NONE &&
1112 	    r->rule_flag & PFRULE_AFTO) {
1113 		printf(" af-to %s from ", r->naf == AF_INET ? "inet" : "inet6");
1114 		print_pool(&r->nat, r->nat.proxy_port[0],
1115 		    r->nat.proxy_port[1], r->naf ? r->naf : r->af,
1116 		    PF_POOL_NAT, verbose);
1117 		if (r->rdr.addr.type != PF_ADDR_NONE) {
1118 			printf(" to ");
1119 			print_pool(&r->rdr, r->rdr.proxy_port[0],
1120 			    r->rdr.proxy_port[1], r->naf ? r->naf : r->af,
1121 			    PF_POOL_RDR, verbose);
1122 		}
1123 	} else if (!anchor_call[0] && r->nat.addr.type != PF_ADDR_NONE) {
1124 		printf (" nat-to ");
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 	} else if (!anchor_call[0] && r->rdr.addr.type != PF_ADDR_NONE) {
1129 		printf (" rdr-to ");
1130 		print_pool(&r->rdr, r->rdr.proxy_port[0],
1131 		    r->rdr.proxy_port[1], r->af, PF_POOL_RDR, verbose);
1132 	}
1133 	if (r->rt) {
1134 		if (r->rt == PF_ROUTETO)
1135 			printf(" route-to");
1136 		else if (r->rt == PF_REPLYTO)
1137 			printf(" reply-to");
1138 		else if (r->rt == PF_DUPTO)
1139 			printf(" dup-to");
1140 		printf(" ");
1141 		print_pool(&r->route, 0, 0, r->af, PF_POOL_ROUTE, verbose);
1142 	}
1143 }
1144 
1145 void
1146 print_tabledef(const char *name, int flags, int addrs,
1147     struct node_tinithead *nodes)
1148 {
1149 	struct node_tinit	*ti, *nti;
1150 	struct node_host	*h;
1151 
1152 	printf("table <%s>", name);
1153 	if (flags & PFR_TFLAG_CONST)
1154 		printf(" const");
1155 	if (flags & PFR_TFLAG_PERSIST)
1156 		printf(" persist");
1157 	if (flags & PFR_TFLAG_COUNTERS)
1158 		printf(" counters");
1159 	SIMPLEQ_FOREACH(ti, nodes, entries) {
1160 		if (ti->file) {
1161 			printf(" file \"%s\"", ti->file);
1162 			continue;
1163 		}
1164 		printf(" {");
1165 		for (;;) {
1166 			for (h = ti->host; h != NULL; h = h->next) {
1167 				printf(h->not ? " !" : " ");
1168 				print_addr(&h->addr, h->af, 0);
1169 				if (h->ifname)
1170 					printf("@%s", h->ifname);
1171 			}
1172 			nti = SIMPLEQ_NEXT(ti, entries);
1173 			if (nti != NULL && nti->file == NULL)
1174 				ti = nti;	/* merge lists */
1175 			else
1176 				break;
1177 		}
1178 		printf(" }");
1179 	}
1180 	if (addrs && SIMPLEQ_EMPTY(nodes))
1181 		printf(" { }");
1182 	printf("\n");
1183 }
1184 
1185 void
1186 print_bwspec(const char *prefix, struct pf_queue_bwspec *bw)
1187 {
1188 	u_int	rate;
1189 	int	i;
1190 	static const char unit[] = " KMG";
1191 
1192 	if (bw->percent)
1193 		printf("%s%u%%", prefix, bw->percent);
1194 	else if (bw->absolute) {
1195 		rate = bw->absolute;
1196 		for (i = 0; rate >= 1000 && i <= 3 && (rate % 1000 == 0); i++)
1197 			rate /= 1000;
1198 		printf("%s%u%c", prefix, rate, unit[i]);
1199 	}
1200 }
1201 
1202 void
1203 print_scspec(const char *prefix, struct pf_queue_scspec *sc)
1204 {
1205 	print_bwspec(prefix, &sc->m2);
1206 	if (sc->d) {
1207 		printf(" burst ");
1208 		print_bwspec("", &sc->m1);
1209 		printf(" for %ums", sc->d);
1210 	}
1211 }
1212 
1213 void
1214 print_queuespec(struct pf_queuespec *q)
1215 {
1216 	printf("queue %s", q->qname);
1217 	if (q->parent[0])
1218 		printf(" parent %s", q->parent);
1219 	else if (q->ifname[0])
1220 		printf(" on %s", q->ifname);
1221 	if (q->flags & PFQS_FLOWQUEUE) {
1222 		printf(" flows %u", q->flowqueue.flows);
1223 		if (q->flowqueue.quantum > 0)
1224 			printf(" quantum %u", q->flowqueue.quantum);
1225 		if (q->flowqueue.interval > 0)
1226 			printf(" interval %ums",
1227 			    q->flowqueue.interval / 1000000);
1228 		if (q->flowqueue.target > 0)
1229 			printf(" target %ums",
1230 			    q->flowqueue.target / 1000000);
1231 	}
1232 	if (q->linkshare.m1.absolute || q->linkshare.m2.absolute) {
1233 		print_scspec(" bandwidth ", &q->linkshare);
1234 		print_scspec(", min ", &q->realtime);
1235 		print_scspec(", max ", &q->upperlimit);
1236 	}
1237 	if (q->flags & PFQS_DEFAULT)
1238 		printf(" default");
1239 	if (q->qlimit)
1240 		printf(" qlimit %u", q->qlimit);
1241 	printf("\n");
1242 }
1243 
1244 int
1245 parse_flags(char *s)
1246 {
1247 	char		*p, *q;
1248 	u_int8_t	 f = 0;
1249 
1250 	for (p = s; *p; p++) {
1251 		if ((q = strchr(tcpflags, *p)) == NULL)
1252 			return -1;
1253 		else
1254 			f |= 1 << (q - tcpflags);
1255 	}
1256 	return (f ? f : PF_TH_ALL);
1257 }
1258 
1259 void
1260 set_ipmask(struct node_host *h, u_int8_t b)
1261 {
1262 	struct pf_addr	*m, *n;
1263 	int		 i, j = 0;
1264 
1265 	m = &h->addr.v.a.mask;
1266 	memset(m, 0, sizeof(*m));
1267 
1268 	while (b >= 32) {
1269 		m->addr32[j++] = 0xffffffff;
1270 		b -= 32;
1271 	}
1272 	for (i = 31; i > 31-b; --i)
1273 		m->addr32[j] |= (1 << i);
1274 	if (b)
1275 		m->addr32[j] = htonl(m->addr32[j]);
1276 
1277 	/* Mask off bits of the address that will never be used. */
1278 	n = &h->addr.v.a.addr;
1279 	if (h->addr.type == PF_ADDR_ADDRMASK)
1280 		for (i = 0; i < 4; i++)
1281 			n->addr32[i] = n->addr32[i] & m->addr32[i];
1282 }
1283 
1284 int
1285 check_netmask(struct node_host *h, sa_family_t af)
1286 {
1287 	struct node_host	*n = NULL;
1288 	struct pf_addr		*m;
1289 
1290 	for (n = h; n != NULL; n = n->next) {
1291 		if (h->addr.type == PF_ADDR_TABLE)
1292 			continue;
1293 		m = &h->addr.v.a.mask;
1294 		/* netmasks > 32 bit are invalid on v4 */
1295 		if (af == AF_INET &&
1296 		    (m->addr32[1] || m->addr32[2] || m->addr32[3])) {
1297 			fprintf(stderr, "netmask %u invalid for IPv4 address\n",
1298 			    unmask(m, AF_INET6));
1299 			return (1);
1300 		}
1301 	}
1302 	return (0);
1303 }
1304 
1305 struct node_host *
1306 gen_dynnode(struct node_host *h, sa_family_t af)
1307 {
1308 	struct node_host	*n;
1309 	struct pf_addr		*m;
1310 
1311 	if (h->addr.type != PF_ADDR_DYNIFTL)
1312 		return (NULL);
1313 
1314 	if ((n = calloc(1, sizeof(*n))) == NULL)
1315 		return (NULL);
1316 	bcopy(h, n, sizeof(*n));
1317 	n->ifname = NULL;
1318 	n->next = NULL;
1319 	n->tail = NULL;
1320 
1321 	/* fix up netmask */
1322 	m = &n->addr.v.a.mask;
1323 	if (af == AF_INET && unmask(m, AF_INET6) > 32)
1324 		set_ipmask(n, 32);
1325 
1326 	return (n);
1327 }
1328 
1329 /* interface lookup routines */
1330 
1331 struct node_host	*iftab;
1332 
1333 void
1334 ifa_load(void)
1335 {
1336 	struct ifaddrs		*ifap, *ifa;
1337 	struct node_host	*n = NULL, *h = NULL;
1338 
1339 	if (getifaddrs(&ifap) < 0)
1340 		err(1, "getifaddrs");
1341 
1342 	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
1343 		if (!(ifa->ifa_addr->sa_family == AF_INET ||
1344 		    ifa->ifa_addr->sa_family == AF_INET6 ||
1345 		    ifa->ifa_addr->sa_family == AF_LINK))
1346 				continue;
1347 		n = calloc(1, sizeof(struct node_host));
1348 		if (n == NULL)
1349 			err(1, "address: calloc");
1350 		n->af = ifa->ifa_addr->sa_family;
1351 		n->ifa_flags = ifa->ifa_flags;
1352 #ifdef __KAME__
1353 		if (n->af == AF_INET6 &&
1354 		    IN6_IS_ADDR_LINKLOCAL(&((struct sockaddr_in6 *)
1355 		    ifa->ifa_addr)->sin6_addr) &&
1356 		    ((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_scope_id ==
1357 		    0) {
1358 			struct sockaddr_in6	*sin6;
1359 
1360 			sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
1361 			sin6->sin6_scope_id = sin6->sin6_addr.s6_addr[2] << 8 |
1362 			    sin6->sin6_addr.s6_addr[3];
1363 			sin6->sin6_addr.s6_addr[2] = 0;
1364 			sin6->sin6_addr.s6_addr[3] = 0;
1365 		}
1366 #endif
1367 		n->ifindex = 0;
1368 		if (n->af == AF_INET) {
1369 			memcpy(&n->addr.v.a.addr, &((struct sockaddr_in *)
1370 			    ifa->ifa_addr)->sin_addr.s_addr,
1371 			    sizeof(struct in_addr));
1372 			memcpy(&n->addr.v.a.mask, &((struct sockaddr_in *)
1373 			    ifa->ifa_netmask)->sin_addr.s_addr,
1374 			    sizeof(struct in_addr));
1375 			if (ifa->ifa_broadaddr != NULL)
1376 				memcpy(&n->bcast, &((struct sockaddr_in *)
1377 				    ifa->ifa_broadaddr)->sin_addr.s_addr,
1378 				    sizeof(struct in_addr));
1379 			if (ifa->ifa_dstaddr != NULL)
1380 				memcpy(&n->peer, &((struct sockaddr_in *)
1381 				    ifa->ifa_dstaddr)->sin_addr.s_addr,
1382 				    sizeof(struct in_addr));
1383 		} else if (n->af == AF_INET6) {
1384 			memcpy(&n->addr.v.a.addr, &((struct sockaddr_in6 *)
1385 			    ifa->ifa_addr)->sin6_addr.s6_addr,
1386 			    sizeof(struct in6_addr));
1387 			memcpy(&n->addr.v.a.mask, &((struct sockaddr_in6 *)
1388 			    ifa->ifa_netmask)->sin6_addr.s6_addr,
1389 			    sizeof(struct in6_addr));
1390 			if (ifa->ifa_broadaddr != NULL)
1391 				memcpy(&n->bcast, &((struct sockaddr_in6 *)
1392 				    ifa->ifa_broadaddr)->sin6_addr.s6_addr,
1393 				    sizeof(struct in6_addr));
1394 			if (ifa->ifa_dstaddr != NULL)
1395 				 memcpy(&n->peer, &((struct sockaddr_in6 *)
1396 				    ifa->ifa_dstaddr)->sin6_addr.s6_addr,
1397 				    sizeof(struct in6_addr));
1398 			n->ifindex = ((struct sockaddr_in6 *)
1399 			    ifa->ifa_addr)->sin6_scope_id;
1400 		} else if (n->af == AF_LINK) {
1401 			n->ifindex = ((struct sockaddr_dl *)
1402 			    ifa->ifa_addr)->sdl_index;
1403 		}
1404 		if ((n->ifname = strdup(ifa->ifa_name)) == NULL)
1405 			err(1, "ifa_load: strdup");
1406 		n->next = NULL;
1407 		n->tail = n;
1408 		if (h == NULL)
1409 			h = n;
1410 		else {
1411 			h->tail->next = n;
1412 			h->tail = n;
1413 		}
1414 	}
1415 
1416 	iftab = h;
1417 	freeifaddrs(ifap);
1418 }
1419 
1420 unsigned int
1421 ifa_nametoindex(const char *ifa_name)
1422 {
1423 	struct node_host	*p;
1424 
1425 	for (p = iftab; p; p = p->next) {
1426 		if (p->af == AF_LINK && strcmp(p->ifname, ifa_name) == 0)
1427 			return (p->ifindex);
1428 	}
1429 	errno = ENXIO;
1430 	return (0);
1431 }
1432 
1433 char *
1434 ifa_indextoname(unsigned int ifindex, char *ifa_name)
1435 {
1436 	struct node_host	*p;
1437 
1438 	for (p = iftab; p; p = p->next) {
1439 		if (p->af == AF_LINK && ifindex == p->ifindex) {
1440 			strlcpy(ifa_name, p->ifname, IFNAMSIZ);
1441 			return (ifa_name);
1442 		}
1443 	}
1444 	errno = ENXIO;
1445 	return (NULL);
1446 }
1447 
1448 struct node_host *
1449 ifa_exists(const char *ifa_name)
1450 {
1451 	struct node_host	*n;
1452 	struct ifgroupreq	ifgr;
1453 	int			s;
1454 
1455 	if (iftab == NULL)
1456 		ifa_load();
1457 
1458 	/* check whether this is a group */
1459 	if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
1460 		err(1, "socket");
1461 	bzero(&ifgr, sizeof(ifgr));
1462 	strlcpy(ifgr.ifgr_name, ifa_name, sizeof(ifgr.ifgr_name));
1463 	if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == 0) {
1464 		/* fake a node_host */
1465 		if ((n = calloc(1, sizeof(*n))) == NULL)
1466 			err(1, "calloc");
1467 		if ((n->ifname = strdup(ifa_name)) == NULL)
1468 			err(1, "strdup");
1469 		close(s);
1470 		return (n);
1471 	}
1472 	close(s);
1473 
1474 	for (n = iftab; n; n = n->next) {
1475 		if (n->af == AF_LINK && !strncmp(n->ifname, ifa_name, IFNAMSIZ))
1476 			return (n);
1477 	}
1478 
1479 	return (NULL);
1480 }
1481 
1482 struct node_host *
1483 ifa_grouplookup(const char *ifa_name, int flags)
1484 {
1485 	struct ifg_req		*ifg;
1486 	struct ifgroupreq	 ifgr;
1487 	int			 s, len;
1488 	struct node_host	*n, *h = NULL;
1489 
1490 	if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
1491 		err(1, "socket");
1492 	bzero(&ifgr, sizeof(ifgr));
1493 	strlcpy(ifgr.ifgr_name, ifa_name, sizeof(ifgr.ifgr_name));
1494 	if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == -1) {
1495 		close(s);
1496 		return (NULL);
1497 	}
1498 
1499 	len = ifgr.ifgr_len;
1500 	if ((ifgr.ifgr_groups = calloc(1, len)) == NULL)
1501 		err(1, "calloc");
1502 	if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == -1)
1503 		err(1, "SIOCGIFGMEMB");
1504 
1505 	for (ifg = ifgr.ifgr_groups; ifg && len >= sizeof(struct ifg_req);
1506 	    ifg++) {
1507 		len -= sizeof(struct ifg_req);
1508 		if ((n = ifa_lookup(ifg->ifgrq_member, flags)) == NULL)
1509 			continue;
1510 		if (h == NULL)
1511 			h = n;
1512 		else {
1513 			h->tail->next = n;
1514 			h->tail = n->tail;
1515 		}
1516 	}
1517 	free(ifgr.ifgr_groups);
1518 	close(s);
1519 
1520 	return (h);
1521 }
1522 
1523 struct node_host *
1524 ifa_lookup(const char *ifa_name, int flags)
1525 {
1526 	struct node_host	*p = NULL, *h = NULL, *n = NULL;
1527 	int			 got4 = 0, got6 = 0;
1528 	const char		 *last_if = NULL;
1529 
1530 	if ((h = ifa_grouplookup(ifa_name, flags)) != NULL)
1531 		return (h);
1532 
1533 	if (!strncmp(ifa_name, "self", IFNAMSIZ))
1534 		ifa_name = NULL;
1535 
1536 	if (iftab == NULL)
1537 		ifa_load();
1538 
1539 	for (p = iftab; p; p = p->next) {
1540 		if (ifa_skip_if(ifa_name, p))
1541 			continue;
1542 		if ((flags & PFI_AFLAG_BROADCAST) && p->af != AF_INET)
1543 			continue;
1544 		if ((flags & PFI_AFLAG_BROADCAST) &&
1545 		    !(p->ifa_flags & IFF_BROADCAST))
1546 			continue;
1547 		if ((flags & PFI_AFLAG_BROADCAST) && p->bcast.v4.s_addr == 0)
1548 			continue;
1549 		if ((flags & PFI_AFLAG_PEER) &&
1550 		    !(p->ifa_flags & IFF_POINTOPOINT))
1551 			continue;
1552 		if ((flags & PFI_AFLAG_NETWORK) && p->ifindex > 0)
1553 			continue;
1554 		if (last_if == NULL || strcmp(last_if, p->ifname))
1555 			got4 = got6 = 0;
1556 		last_if = p->ifname;
1557 		if ((flags & PFI_AFLAG_NOALIAS) && p->af == AF_INET && got4)
1558 			continue;
1559 		if ((flags & PFI_AFLAG_NOALIAS) && p->af == AF_INET6 && got6)
1560 			continue;
1561 		if (p->af == AF_INET)
1562 			got4 = 1;
1563 		else
1564 			got6 = 1;
1565 		n = calloc(1, sizeof(struct node_host));
1566 		if (n == NULL)
1567 			err(1, "address: calloc");
1568 		n->af = p->af;
1569 		if (flags & PFI_AFLAG_BROADCAST)
1570 			memcpy(&n->addr.v.a.addr, &p->bcast,
1571 			    sizeof(struct pf_addr));
1572 		else if (flags & PFI_AFLAG_PEER)
1573 			memcpy(&n->addr.v.a.addr, &p->peer,
1574 			    sizeof(struct pf_addr));
1575 		else
1576 			memcpy(&n->addr.v.a.addr, &p->addr.v.a.addr,
1577 			    sizeof(struct pf_addr));
1578 		if (flags & PFI_AFLAG_NETWORK)
1579 			set_ipmask(n, unmask(&p->addr.v.a.mask, n->af));
1580 		else {
1581 			if (n->af == AF_INET) {
1582 				if (p->ifa_flags & IFF_LOOPBACK &&
1583 				    p->ifa_flags & IFF_LINK1)
1584 					memcpy(&n->addr.v.a.mask,
1585 					    &p->addr.v.a.mask,
1586 					    sizeof(struct pf_addr));
1587 				else
1588 					set_ipmask(n, 32);
1589 			} else
1590 				set_ipmask(n, 128);
1591 		}
1592 		n->ifindex = p->ifindex;
1593 
1594 		n->next = NULL;
1595 		n->tail = n;
1596 		if (h == NULL)
1597 			h = n;
1598 		else {
1599 			h->tail->next = n;
1600 			h->tail = n;
1601 		}
1602 	}
1603 	return (h);
1604 }
1605 
1606 int
1607 ifa_skip_if(const char *filter, struct node_host *p)
1608 {
1609 	int	n;
1610 
1611 	if (p->af != AF_INET && p->af != AF_INET6)
1612 		return (1);
1613 	if (filter == NULL || !*filter)
1614 		return (0);
1615 	if (!strcmp(p->ifname, filter))
1616 		return (0);	/* exact match */
1617 	n = strlen(filter);
1618 	if (n < 1 || n >= IFNAMSIZ)
1619 		return (1);	/* sanity check */
1620 	if (filter[n-1] >= '0' && filter[n-1] <= '9')
1621 		return (1);	/* only do exact match in that case */
1622 	if (strncmp(p->ifname, filter, n))
1623 		return (1);	/* prefix doesn't match */
1624 	return (p->ifname[n] < '0' || p->ifname[n] > '9');
1625 }
1626 
1627 struct node_host *
1628 host(const char *s, int opts)
1629 {
1630 	struct node_host	*h = NULL, *n;
1631 	int			 mask = -1, v4mask = 32, v6mask = 128, cont = 1;
1632 	char			*p, *q, *r, *ps, *if_name;
1633 
1634 	if ((ps = strdup(s)) == NULL)
1635 		err(1, "host: strdup");
1636 
1637 	if ((if_name = strrchr(ps, '@')) != NULL) {
1638 		if_name[0] = '\0';
1639 		if_name++;
1640 	}
1641 
1642 	if ((p = strrchr(ps, '/')) != NULL) {
1643 		if ((r = strdup(ps)) == NULL)
1644 			err(1, "host: strdup");
1645 		mask = strtol(p+1, &q, 0);
1646 		if (!q || *q || mask > 128 || q == (p+1)) {
1647 			fprintf(stderr, "invalid netmask '%s'\n", p);
1648 			free(r);
1649 			free(ps);
1650 			return (NULL);
1651 		}
1652 		p[0] = '\0';
1653 		v4mask = v6mask = mask;
1654 	} else
1655 		r = ps;
1656 
1657 	/* interface with this name exists? */
1658 	if (cont && (h = host_if(ps, mask)) != NULL)
1659 		cont = 0;
1660 
1661 	/* IPv4 address? */
1662 	if (cont && (h = host_v4(r, mask)) != NULL)
1663 		cont = 0;
1664 	if (r != ps)
1665 		free(r);
1666 
1667 	/* IPv6 address? */
1668 	if (cont && (h = host_v6(ps, v6mask)) != NULL)
1669 		cont = 0;
1670 
1671 	/* dns lookup */
1672 	if (cont && (h = host_dns(ps, v4mask, v6mask,
1673 	    (opts & PF_OPT_NODNS))) != NULL)
1674 		cont = 0;
1675 
1676 	if (if_name && if_name[0])
1677 		for (n = h; n != NULL; n = n->next)
1678 			if ((n->ifname = strdup(if_name)) == NULL)
1679 				err(1, "host: strdup");
1680 
1681 	free(ps);	/* after we copy the name out */
1682 	if (h == NULL || cont == 1) {
1683 		fprintf(stderr, "no IP address found for %s\n", s);
1684 		return (NULL);
1685 	}
1686 	for (n = h; n != NULL; n = n->next) {
1687 		n->addr.type = PF_ADDR_ADDRMASK;
1688 		n->weight = 0;
1689 	}
1690 	return (h);
1691 }
1692 
1693 struct node_host *
1694 host_if(const char *s, int mask)
1695 {
1696 	struct node_host	*n, *h = NULL;
1697 	char			*p, *ps;
1698 	int			 flags = 0;
1699 
1700 	if ((ps = strdup(s)) == NULL)
1701 		err(1, "host_if: strdup");
1702 	while ((p = strrchr(ps, ':')) != NULL) {
1703 		if (!strcmp(p+1, "network"))
1704 			flags |= PFI_AFLAG_NETWORK;
1705 		else if (!strcmp(p+1, "broadcast"))
1706 			flags |= PFI_AFLAG_BROADCAST;
1707 		else if (!strcmp(p+1, "peer"))
1708 			flags |= PFI_AFLAG_PEER;
1709 		else if (!strcmp(p+1, "0"))
1710 			flags |= PFI_AFLAG_NOALIAS;
1711 		else {
1712 			free(ps);
1713 			return (NULL);
1714 		}
1715 		*p = '\0';
1716 	}
1717 	if (flags & (flags - 1) & PFI_AFLAG_MODEMASK) { /* Yep! */
1718 		fprintf(stderr, "illegal combination of interface modifiers\n");
1719 		free(ps);
1720 		return (NULL);
1721 	}
1722 	if ((flags & (PFI_AFLAG_NETWORK|PFI_AFLAG_BROADCAST)) && mask > -1) {
1723 		fprintf(stderr, "network or broadcast lookup, but "
1724 		    "extra netmask given\n");
1725 		free(ps);
1726 		return (NULL);
1727 	}
1728 	if (ifa_exists(ps) || !strncmp(ps, "self", IFNAMSIZ)) {
1729 		/* interface with this name exists */
1730 		h = ifa_lookup(ps, flags);
1731 		for (n = h; n != NULL && mask > -1; n = n->next)
1732 			set_ipmask(n, mask);
1733 	}
1734 
1735 	free(ps);
1736 	return (h);
1737 }
1738 
1739 struct node_host *
1740 host_v4(const char *s, int mask)
1741 {
1742 	struct node_host	*h = NULL;
1743 	struct in_addr		 ina;
1744 	int			 bits = 32;
1745 
1746 	memset(&ina, 0, sizeof(struct in_addr));
1747 	if (strrchr(s, '/') != NULL) {
1748 		if ((bits = inet_net_pton(AF_INET, s, &ina, sizeof(ina))) == -1)
1749 			return (NULL);
1750 	} else {
1751 		if (inet_pton(AF_INET, s, &ina) != 1)
1752 			return (NULL);
1753 	}
1754 
1755 	h = calloc(1, sizeof(struct node_host));
1756 	if (h == NULL)
1757 		err(1, "address: calloc");
1758 	h->ifname = NULL;
1759 	h->af = AF_INET;
1760 	h->addr.v.a.addr.addr32[0] = ina.s_addr;
1761 	set_ipmask(h, bits);
1762 	h->next = NULL;
1763 	h->tail = h;
1764 
1765 	return (h);
1766 }
1767 
1768 struct node_host *
1769 host_v6(const char *s, int mask)
1770 {
1771 	struct addrinfo		 hints, *res;
1772 	struct node_host	*h = NULL;
1773 
1774 	memset(&hints, 0, sizeof(hints));
1775 	hints.ai_family = AF_INET6;
1776 	hints.ai_socktype = SOCK_DGRAM; /*dummy*/
1777 	hints.ai_flags = AI_NUMERICHOST;
1778 	if (getaddrinfo(s, "0", &hints, &res) == 0) {
1779 		h = calloc(1, sizeof(struct node_host));
1780 		if (h == NULL)
1781 			err(1, "address: calloc");
1782 		h->ifname = NULL;
1783 		h->af = AF_INET6;
1784 		memcpy(&h->addr.v.a.addr,
1785 		    &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr,
1786 		    sizeof(h->addr.v.a.addr));
1787 		h->ifindex =
1788 		    ((struct sockaddr_in6 *)res->ai_addr)->sin6_scope_id;
1789 		set_ipmask(h, mask);
1790 		freeaddrinfo(res);
1791 		h->next = NULL;
1792 		h->tail = h;
1793 	}
1794 
1795 	return (h);
1796 }
1797 
1798 struct node_host *
1799 host_dns(const char *s, int v4mask, int v6mask, int numeric)
1800 {
1801 	struct addrinfo		 hints, *res0, *res;
1802 	struct node_host	*n, *h = NULL;
1803 	int			 error, noalias = 0;
1804 	int			 got4 = 0, got6 = 0;
1805 	char			*p, *ps;
1806 
1807 	if ((ps = strdup(s)) == NULL)
1808 		err(1, "host_dns: strdup");
1809 	if ((p = strrchr(ps, ':')) != NULL && !strcmp(p, ":0")) {
1810 		noalias = 1;
1811 		*p = '\0';
1812 	}
1813 	memset(&hints, 0, sizeof(hints));
1814 	hints.ai_family = PF_UNSPEC;
1815 	hints.ai_socktype = SOCK_STREAM; /* DUMMY */
1816 	if (numeric)
1817 		hints.ai_flags = AI_NUMERICHOST;
1818 	error = getaddrinfo(ps, NULL, &hints, &res0);
1819 	if (error) {
1820 		free(ps);
1821 		return (h);
1822 	}
1823 
1824 	for (res = res0; res; res = res->ai_next) {
1825 		if (res->ai_family != AF_INET &&
1826 		    res->ai_family != AF_INET6)
1827 			continue;
1828 		if (noalias) {
1829 			if (res->ai_family == AF_INET) {
1830 				if (got4)
1831 					continue;
1832 				got4 = 1;
1833 			} else {
1834 				if (got6)
1835 					continue;
1836 				got6 = 1;
1837 			}
1838 		}
1839 		n = calloc(1, sizeof(struct node_host));
1840 		if (n == NULL)
1841 			err(1, "host_dns: calloc");
1842 		n->ifname = NULL;
1843 		n->af = res->ai_family;
1844 		if (res->ai_family == AF_INET) {
1845 			memcpy(&n->addr.v.a.addr,
1846 			    &((struct sockaddr_in *)
1847 			    res->ai_addr)->sin_addr.s_addr,
1848 			    sizeof(struct in_addr));
1849 			set_ipmask(n, v4mask);
1850 		} else {
1851 			memcpy(&n->addr.v.a.addr,
1852 			    &((struct sockaddr_in6 *)
1853 			    res->ai_addr)->sin6_addr.s6_addr,
1854 			    sizeof(struct in6_addr));
1855 			n->ifindex =
1856 			    ((struct sockaddr_in6 *)
1857 			    res->ai_addr)->sin6_scope_id;
1858 			set_ipmask(n, v6mask);
1859 		}
1860 		n->next = NULL;
1861 		n->tail = n;
1862 		if (h == NULL)
1863 			h = n;
1864 		else {
1865 			h->tail->next = n;
1866 			h->tail = n;
1867 		}
1868 	}
1869 	freeaddrinfo(res0);
1870 	free(ps);
1871 
1872 	return (h);
1873 }
1874 
1875 /*
1876  * convert a hostname to a list of addresses and put them in the given buffer.
1877  * test:
1878  *	if set to 1, only simple addresses are accepted (no netblock, no "!").
1879  */
1880 int
1881 append_addr(struct pfr_buffer *b, char *s, int test, int opts)
1882 {
1883 	static int 		 previous = 0;
1884 	static int		 expect = 0;
1885 	struct pfr_addr		*a;
1886 	struct node_host	*h, *n;
1887 	char			*r;
1888 	const char		*errstr;
1889 	int			 rv, not = 0, i = 0;
1890 	u_int16_t		 weight;
1891 
1892 	/* skip weight if given */
1893 	if (strcmp(s, "weight") == 0) {
1894 		expect = 1;
1895 		return (1); /* expecting further call */
1896 	}
1897 
1898 	/* check if previous host is set */
1899 	if (expect) {
1900 		/* parse and append load balancing weight */
1901 		weight = strtonum(s, 1, USHRT_MAX, &errstr);
1902 		if (errstr) {
1903 			fprintf(stderr, "failed to convert weight %s\n", s);
1904 			return (-1);
1905 		}
1906 		if (previous != -1) {
1907 			PFRB_FOREACH(a, b) {
1908 				if (++i >= previous) {
1909 					a->pfra_weight = weight;
1910 					a->pfra_type = PFRKE_COST;
1911 				}
1912 			}
1913 		}
1914 
1915 		expect = 0;
1916 		return (0);
1917 	}
1918 
1919 	for (r = s; *r == '!'; r++)
1920 		not = !not;
1921 	if ((n = host(r, opts)) == NULL) {
1922 		errno = 0;
1923 		return (-1);
1924 	}
1925 	rv = append_addr_host(b, n, test, not);
1926 	previous = b->pfrb_size;
1927 	do {
1928 		h = n;
1929 		n = n->next;
1930 		free(h);
1931 	} while (n != NULL);
1932 	return (rv);
1933 }
1934 
1935 /*
1936  * same as previous function, but with a pre-parsed input and the ability
1937  * to "negate" the result. Does not free the node_host list.
1938  * not:
1939  *      setting it to 1 is equivalent to adding "!" in front of parameter s.
1940  */
1941 int
1942 append_addr_host(struct pfr_buffer *b, struct node_host *n, int test, int not)
1943 {
1944 	int			 bits;
1945 	struct pfr_addr		 addr;
1946 
1947 	do {
1948 		bzero(&addr, sizeof(addr));
1949 		addr.pfra_not = n->not ^ not;
1950 		addr.pfra_af = n->af;
1951 		addr.pfra_net = unmask(&n->addr.v.a.mask, n->af);
1952 		if (n->ifname) {
1953 			if (strlcpy(addr.pfra_ifname, n->ifname,
1954 		 	   sizeof(addr.pfra_ifname)) >= sizeof(addr.pfra_ifname))
1955 				errx(1, "append_addr_host: strlcpy");
1956 			addr.pfra_type = PFRKE_ROUTE;
1957 		}
1958 		if (n->weight > 0) {
1959 			addr.pfra_weight = n->weight;
1960 			addr.pfra_type = PFRKE_COST;
1961 		}
1962 		switch (n->af) {
1963 		case AF_INET:
1964 			addr.pfra_ip4addr.s_addr = n->addr.v.a.addr.addr32[0];
1965 			bits = 32;
1966 			break;
1967 		case AF_INET6:
1968 			memcpy(&addr.pfra_ip6addr, &n->addr.v.a.addr.v6,
1969 			    sizeof(struct in6_addr));
1970 			bits = 128;
1971 			break;
1972 		default:
1973 			errno = EINVAL;
1974 			return (-1);
1975 		}
1976 		if ((test && (not || addr.pfra_net != bits)) ||
1977 		    addr.pfra_net > bits) {
1978 			errno = EINVAL;
1979 			return (-1);
1980 		}
1981 		if (pfr_buf_add(b, &addr))
1982 			return (-1);
1983 	} while ((n = n->next) != NULL);
1984 
1985 	return (0);
1986 }
1987 
1988 int
1989 pfctl_add_trans(struct pfr_buffer *buf, int type, const char *anchor)
1990 {
1991 	struct pfioc_trans_e trans;
1992 
1993 	bzero(&trans, sizeof(trans));
1994 	trans.type = type;
1995 	if (strlcpy(trans.anchor, anchor,
1996 	    sizeof(trans.anchor)) >= sizeof(trans.anchor))
1997 		errx(1, "pfctl_add_trans: strlcpy");
1998 
1999 	return pfr_buf_add(buf, &trans);
2000 }
2001 
2002 u_int32_t
2003 pfctl_get_ticket(struct pfr_buffer *buf, int type, const char *anchor)
2004 {
2005 	struct pfioc_trans_e *p;
2006 
2007 	PFRB_FOREACH(p, buf)
2008 		if (type == p->type && !strcmp(anchor, p->anchor))
2009 			return (p->ticket);
2010 	errx(1, "pfctl_get_ticket: assertion failed");
2011 }
2012 
2013 int
2014 pfctl_trans(int dev, struct pfr_buffer *buf, u_long cmd, int from)
2015 {
2016 	struct pfioc_trans trans;
2017 
2018 	bzero(&trans, sizeof(trans));
2019 	trans.size = buf->pfrb_size - from;
2020 	trans.esize = sizeof(struct pfioc_trans_e);
2021 	trans.array = ((struct pfioc_trans_e *)buf->pfrb_caddr) + from;
2022 	return ioctl(dev, cmd, &trans);
2023 }
2024