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