xref: /netbsd-src/dist/pf/sbin/pfctl/pfctl_parser.c (revision 23c8222edbfb0f0932d88a8351d3a0cf817dfb9e)
1 /*	$NetBSD: pfctl_parser.c,v 1.5 2004/11/14 11:26:48 yamt Exp $	*/
2 /*	$OpenBSD: pfctl_parser.c,v 1.203 2004/07/16 23:44:25 frantzen Exp $ */
3 
4 /*
5  * Copyright (c) 2001 Daniel Hartmeier
6  * Copyright (c) 2002,2003 Henning Brauer
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  *    - Redistributions of source code must retain the above copyright
14  *      notice, this list of conditions and the following disclaimer.
15  *    - Redistributions in binary form must reproduce the above
16  *      copyright notice, this list of conditions and the following
17  *      disclaimer in the documentation and/or other materials provided
18  *      with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
28  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
30  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31  * POSSIBILITY OF SUCH DAMAGE.
32  *
33  */
34 
35 #include <sys/types.h>
36 #include <sys/ioctl.h>
37 #include <sys/socket.h>
38 #include <net/if.h>
39 #include <netinet/in.h>
40 #include <netinet/in_systm.h>
41 #include <netinet/ip.h>
42 #include <netinet/ip_icmp.h>
43 #include <netinet/icmp6.h>
44 #include <net/pfvar.h>
45 #include <arpa/inet.h>
46 
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <ctype.h>
51 #include <netdb.h>
52 #include <stdarg.h>
53 #include <errno.h>
54 #include <err.h>
55 #include <ifaddrs.h>
56 #ifdef __NetBSD__
57 #include <limits.h>
58 #endif
59 
60 #include "pfctl_parser.h"
61 #include "pfctl.h"
62 
63 void		 print_op (u_int8_t, const char *, const char *);
64 void		 print_port (u_int8_t, u_int16_t, u_int16_t, const char *);
65 void		 print_ugid (u_int8_t, unsigned, unsigned, const char *, unsigned);
66 void		 print_flags (u_int8_t);
67 void		 print_fromto(struct pf_rule_addr *, pf_osfp_t,
68 		    struct pf_rule_addr *, u_int8_t, u_int8_t, int);
69 int		 ifa_skip_if(const char *filter, struct node_host *p);
70 
71 struct node_host	*host_if(const char *, int);
72 struct node_host	*host_v4(const char *, int);
73 struct node_host	*host_v6(const char *, int);
74 struct node_host	*host_dns(const char *, int, int);
75 
76 const char *tcpflags = "FSRPAUEW";
77 
78 static const struct icmptypeent icmp_type[] = {
79 	{ "echoreq",	ICMP_ECHO },
80 	{ "echorep",	ICMP_ECHOREPLY },
81 	{ "unreach",	ICMP_UNREACH },
82 	{ "squench",	ICMP_SOURCEQUENCH },
83 	{ "redir",	ICMP_REDIRECT },
84 #ifdef ICMP_ALTHOSTADDR
85 	{ "althost",	ICMP_ALTHOSTADDR },
86 #endif
87 	{ "routeradv",	ICMP_ROUTERADVERT },
88 	{ "routersol",	ICMP_ROUTERSOLICIT },
89 	{ "timex",	ICMP_TIMXCEED },
90 	{ "paramprob",	ICMP_PARAMPROB },
91 	{ "timereq",	ICMP_TSTAMP },
92 	{ "timerep",	ICMP_TSTAMPREPLY },
93 	{ "inforeq",	ICMP_IREQ },
94 	{ "inforep",	ICMP_IREQREPLY },
95 	{ "maskreq",	ICMP_MASKREQ },
96 	{ "maskrep",	ICMP_MASKREPLY },
97 #ifdef ICMP_TRACEROUTE
98 	{ "trace",	ICMP_TRACEROUTE },
99 #endif
100 #ifdef ICMP_DATACONVERR
101 	{ "dataconv",	ICMP_DATACONVERR },
102 #endif
103 #ifdef ICMP_MOBILE_REDIRECT
104 	{ "mobredir",	ICMP_MOBILE_REDIRECT },
105 #endif
106 #ifdef ICMP_IPV6_WHEREAREYOU
107 	{ "ipv6-where",	ICMP_IPV6_WHEREAREYOU },
108 #endif
109 #ifdef ICMP_IPV6_IAMHERE
110 	{ "ipv6-here",	ICMP_IPV6_IAMHERE },
111 #endif
112 #ifdef ICMP_MOBILE_REGREQUEST
113 	{ "mobregreq",	ICMP_MOBILE_REGREQUEST },
114 #endif
115 #ifdef ICMP_MOBILE_REGREPLY
116 	{ "mobregrep",	ICMP_MOBILE_REGREPLY },
117 #endif
118 #ifdef ICMP_SKIP
119 	{ "skip",	ICMP_SKIP },
120 #endif
121 #ifdef ICMP_PHOTURIS
122 	{ "photuris",	ICMP_PHOTURIS }
123 #endif
124 };
125 
126 static const struct icmptypeent icmp6_type[] = {
127 	{ "unreach",	ICMP6_DST_UNREACH },
128 	{ "toobig",	ICMP6_PACKET_TOO_BIG },
129 	{ "timex",	ICMP6_TIME_EXCEEDED },
130 	{ "paramprob",	ICMP6_PARAM_PROB },
131 	{ "echoreq",	ICMP6_ECHO_REQUEST },
132 	{ "echorep",	ICMP6_ECHO_REPLY },
133 	{ "groupqry",	ICMP6_MEMBERSHIP_QUERY },
134 	{ "listqry",	MLD_LISTENER_QUERY },
135 	{ "grouprep",	ICMP6_MEMBERSHIP_REPORT },
136 	{ "listenrep",	MLD_LISTENER_REPORT },
137 	{ "groupterm",	ICMP6_MEMBERSHIP_REDUCTION },
138 	{ "listendone", MLD_LISTENER_DONE },
139 	{ "routersol",	ND_ROUTER_SOLICIT },
140 	{ "routeradv",	ND_ROUTER_ADVERT },
141 	{ "neighbrsol", ND_NEIGHBOR_SOLICIT },
142 	{ "neighbradv", ND_NEIGHBOR_ADVERT },
143 	{ "redir",	ND_REDIRECT },
144 	{ "routrrenum", ICMP6_ROUTER_RENUMBERING },
145 	{ "wrureq",	ICMP6_WRUREQUEST },
146 	{ "wrurep",	ICMP6_WRUREPLY },
147 	{ "fqdnreq",	ICMP6_FQDN_QUERY },
148 	{ "fqdnrep",	ICMP6_FQDN_REPLY },
149 	{ "niqry",	ICMP6_NI_QUERY },
150 	{ "nirep",	ICMP6_NI_REPLY },
151 	{ "mtraceresp",	MLD_MTRACE_RESP },
152 	{ "mtrace",	MLD_MTRACE }
153 };
154 
155 static const struct icmpcodeent icmp_code[] = {
156 	{ "net-unr",		ICMP_UNREACH,	ICMP_UNREACH_NET },
157 	{ "host-unr",		ICMP_UNREACH,	ICMP_UNREACH_HOST },
158 	{ "proto-unr",		ICMP_UNREACH,	ICMP_UNREACH_PROTOCOL },
159 	{ "port-unr",		ICMP_UNREACH,	ICMP_UNREACH_PORT },
160 	{ "needfrag",		ICMP_UNREACH,	ICMP_UNREACH_NEEDFRAG },
161 	{ "srcfail",		ICMP_UNREACH,	ICMP_UNREACH_SRCFAIL },
162 	{ "net-unk",		ICMP_UNREACH,	ICMP_UNREACH_NET_UNKNOWN },
163 	{ "host-unk",		ICMP_UNREACH,	ICMP_UNREACH_HOST_UNKNOWN },
164 	{ "isolate",		ICMP_UNREACH,	ICMP_UNREACH_ISOLATED },
165 	{ "net-prohib",		ICMP_UNREACH,	ICMP_UNREACH_NET_PROHIB },
166 	{ "host-prohib",	ICMP_UNREACH,	ICMP_UNREACH_HOST_PROHIB },
167 	{ "net-tos",		ICMP_UNREACH,	ICMP_UNREACH_TOSNET },
168 	{ "host-tos",		ICMP_UNREACH,	ICMP_UNREACH_TOSHOST },
169 #ifdef ICMP_UNREACH_FILTER_PROHIB
170 	{ "filter-prohib",	ICMP_UNREACH,	ICMP_UNREACH_FILTER_PROHIB },
171 #endif
172 #ifdef ICMP_UNREACH_HOST_PRECEDENCE
173 	{ "host-preced",	ICMP_UNREACH,	ICMP_UNREACH_HOST_PRECEDENCE },
174 #endif
175 #ifdef ICMP_UNREACH_PRECEDENCE_CUTOFF
176 	{ "cutoff-preced",	ICMP_UNREACH,	ICMP_UNREACH_PRECEDENCE_CUTOFF },
177 #endif
178 	{ "redir-net",		ICMP_REDIRECT,	ICMP_REDIRECT_NET },
179 	{ "redir-host",		ICMP_REDIRECT,	ICMP_REDIRECT_HOST },
180 	{ "redir-tos-net",	ICMP_REDIRECT,	ICMP_REDIRECT_TOSNET },
181 	{ "redir-tos-host",	ICMP_REDIRECT,	ICMP_REDIRECT_TOSHOST },
182 #ifdef ICMP_ROUTERADVERT_NORMAL
183 	{ "normal-adv",		ICMP_ROUTERADVERT, ICMP_ROUTERADVERT_NORMAL },
184 #endif
185 #ifdef ICMP_ROUTERADVERT_NOROUTE_COMMON
186 	{ "common-adv",		ICMP_ROUTERADVERT, ICMP_ROUTERADVERT_NOROUTE_COMMON },
187 #endif
188 	{ "transit",		ICMP_TIMXCEED,	ICMP_TIMXCEED_INTRANS },
189 	{ "reassemb",		ICMP_TIMXCEED,	ICMP_TIMXCEED_REASS },
190 #ifdef ICMP_PARAMPROB_ERRATPTR
191 	{ "badhead",		ICMP_PARAMPROB,	ICMP_PARAMPROB_ERRATPTR },
192 #endif
193 	{ "optmiss",		ICMP_PARAMPROB,	ICMP_PARAMPROB_OPTABSENT },
194 #ifdef ICMP_PARAMPROB_LENGTH
195 	{ "badlen",		ICMP_PARAMPROB,	ICMP_PARAMPROB_LENGTH },
196 #endif
197 #ifdef ICMP_PHOTURIS
198 	{ "unknown-ind",	ICMP_PHOTURIS,	ICMP_PHOTURIS_UNKNOWN_INDEX },
199 	{ "auth-fail",		ICMP_PHOTURIS,	ICMP_PHOTURIS_AUTH_FAILED },
200 	{ "decrypt-fail",	ICMP_PHOTURIS,	ICMP_PHOTURIS_DECRYPT_FAILED }
201 #endif
202 };
203 
204 static const struct icmpcodeent icmp6_code[] = {
205 	{ "admin-unr", ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADMIN },
206 	{ "noroute-unr", ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_NOROUTE },
207 	{ "notnbr-unr",	ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_NOTNEIGHBOR },
208 	{ "beyond-unr", ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_BEYONDSCOPE },
209 	{ "addr-unr", ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR },
210 	{ "port-unr", ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_NOPORT },
211 	{ "transit", ICMP6_TIME_EXCEEDED, ICMP6_TIME_EXCEED_TRANSIT },
212 	{ "reassemb", ICMP6_TIME_EXCEEDED, ICMP6_TIME_EXCEED_REASSEMBLY },
213 	{ "badhead", ICMP6_PARAM_PROB, ICMP6_PARAMPROB_HEADER },
214 	{ "nxthdr", ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER },
215 	{ "redironlink", ND_REDIRECT, ND_REDIRECT_ONLINK },
216 	{ "redirrouter", ND_REDIRECT, ND_REDIRECT_ROUTER }
217 };
218 
219 const struct pf_timeout pf_timeouts[] = {
220 	{ "tcp.first",		PFTM_TCP_FIRST_PACKET },
221 	{ "tcp.opening",	PFTM_TCP_OPENING },
222 	{ "tcp.established",	PFTM_TCP_ESTABLISHED },
223 	{ "tcp.closing",	PFTM_TCP_CLOSING },
224 	{ "tcp.finwait",	PFTM_TCP_FIN_WAIT },
225 	{ "tcp.closed",		PFTM_TCP_CLOSED },
226 	{ "tcp.tsdiff",		PFTM_TS_DIFF },
227 	{ "udp.first",		PFTM_UDP_FIRST_PACKET },
228 	{ "udp.single",		PFTM_UDP_SINGLE },
229 	{ "udp.multiple",	PFTM_UDP_MULTIPLE },
230 	{ "icmp.first",		PFTM_ICMP_FIRST_PACKET },
231 	{ "icmp.error",		PFTM_ICMP_ERROR_REPLY },
232 	{ "other.first",	PFTM_OTHER_FIRST_PACKET },
233 	{ "other.single",	PFTM_OTHER_SINGLE },
234 	{ "other.multiple",	PFTM_OTHER_MULTIPLE },
235 	{ "frag",		PFTM_FRAG },
236 	{ "interval",		PFTM_INTERVAL },
237 	{ "adaptive.start",	PFTM_ADAPTIVE_START },
238 	{ "adaptive.end",	PFTM_ADAPTIVE_END },
239 	{ "src.track",		PFTM_SRC_NODE },
240 	{ NULL,			0 }
241 };
242 
243 const struct icmptypeent *
244 geticmptypebynumber(u_int8_t type, sa_family_t af)
245 {
246 	unsigned int	i;
247 
248 	if (af != AF_INET6) {
249 		for (i=0; i < (sizeof (icmp_type) / sizeof(icmp_type[0]));
250 		    i++) {
251 			if (type == icmp_type[i].type)
252 				return (&icmp_type[i]);
253 		}
254 	} else {
255 		for (i=0; i < (sizeof (icmp6_type) /
256 		    sizeof(icmp6_type[0])); i++) {
257 			if (type == icmp6_type[i].type)
258 				 return (&icmp6_type[i]);
259 		}
260 	}
261 	return (NULL);
262 }
263 
264 const struct icmptypeent *
265 geticmptypebyname(char *w, sa_family_t af)
266 {
267 	unsigned int	i;
268 
269 	if (af != AF_INET6) {
270 		for (i=0; i < (sizeof (icmp_type) / sizeof(icmp_type[0]));
271 		    i++) {
272 			if (!strcmp(w, icmp_type[i].name))
273 				return (&icmp_type[i]);
274 		}
275 	} else {
276 		for (i=0; i < (sizeof (icmp6_type) /
277 		    sizeof(icmp6_type[0])); i++) {
278 			if (!strcmp(w, icmp6_type[i].name))
279 				return (&icmp6_type[i]);
280 		}
281 	}
282 	return (NULL);
283 }
284 
285 const struct icmpcodeent *
286 geticmpcodebynumber(u_int8_t type, u_int8_t code, sa_family_t af)
287 {
288 	unsigned int	i;
289 
290 	if (af != AF_INET6) {
291 		for (i=0; i < (sizeof (icmp_code) / sizeof(icmp_code[0]));
292 		    i++) {
293 			if (type == icmp_code[i].type &&
294 			    code == icmp_code[i].code)
295 				return (&icmp_code[i]);
296 		}
297 	} else {
298 		for (i=0; i < (sizeof (icmp6_code) /
299 		    sizeof(icmp6_code[0])); i++) {
300 			if (type == icmp6_code[i].type &&
301 			    code == icmp6_code[i].code)
302 				return (&icmp6_code[i]);
303 		}
304 	}
305 	return (NULL);
306 }
307 
308 const struct icmpcodeent *
309 geticmpcodebyname(u_long type, char *w, sa_family_t af)
310 {
311 	unsigned int	i;
312 
313 	if (af != AF_INET6) {
314 		for (i=0; i < (sizeof (icmp_code) / sizeof(icmp_code[0]));
315 		    i++) {
316 			if (type == icmp_code[i].type &&
317 			    !strcmp(w, icmp_code[i].name))
318 				return (&icmp_code[i]);
319 		}
320 	} else {
321 		for (i=0; i < (sizeof (icmp6_code) /
322 		    sizeof(icmp6_code[0])); i++) {
323 			if (type == icmp6_code[i].type &&
324 			    !strcmp(w, icmp6_code[i].name))
325 				return (&icmp6_code[i]);
326 		}
327 	}
328 	return (NULL);
329 }
330 
331 void
332 print_op(u_int8_t op, const char *a1, const char *a2)
333 {
334 	if (op == PF_OP_IRG)
335 		printf(" %s >< %s", a1, a2);
336 	else if (op == PF_OP_XRG)
337 		printf(" %s <> %s", a1, a2);
338 	else if (op == PF_OP_EQ)
339 		printf(" = %s", a1);
340 	else if (op == PF_OP_NE)
341 		printf(" != %s", a1);
342 	else if (op == PF_OP_LT)
343 		printf(" < %s", a1);
344 	else if (op == PF_OP_LE)
345 		printf(" <= %s", a1);
346 	else if (op == PF_OP_GT)
347 		printf(" > %s", a1);
348 	else if (op == PF_OP_GE)
349 		printf(" >= %s", a1);
350 	else if (op == PF_OP_RRG)
351 		printf(" %s:%s", a1, a2);
352 }
353 
354 void
355 print_port(u_int8_t op, u_int16_t p1, u_int16_t p2, const char *proto)
356 {
357 	char		 a1[6], a2[6];
358 	struct servent	*s;
359 
360 	s = getservbyport(p1, proto);
361 	p1 = ntohs(p1);
362 	p2 = ntohs(p2);
363 	snprintf(a1, sizeof(a1), "%u", p1);
364 	snprintf(a2, sizeof(a2), "%u", p2);
365 	printf(" port");
366 	if (s != NULL && (op == PF_OP_EQ || op == PF_OP_NE))
367 		print_op(op, s->s_name, a2);
368 	else
369 		print_op(op, a1, a2);
370 }
371 
372 void
373 print_ugid(u_int8_t op, unsigned u1, unsigned u2, const char *t, unsigned umax)
374 {
375 	char	a1[11], a2[11];
376 
377 	snprintf(a1, sizeof(a1), "%u", u1);
378 	snprintf(a2, sizeof(a2), "%u", u2);
379 	printf(" %s", t);
380 	if (u1 == umax && (op == PF_OP_EQ || op == PF_OP_NE))
381 		print_op(op, "unknown", a2);
382 	else
383 		print_op(op, a1, a2);
384 }
385 
386 void
387 print_flags(u_int8_t f)
388 {
389 	int	i;
390 
391 	for (i = 0; tcpflags[i]; ++i)
392 		if (f & (1 << i))
393 			printf("%c", tcpflags[i]);
394 }
395 
396 void
397 print_fromto(struct pf_rule_addr *src, pf_osfp_t osfp, struct pf_rule_addr *dst,
398     sa_family_t af, u_int8_t proto, int verbose)
399 {
400 	char buf[PF_OSFP_LEN*3];
401 	if (src->addr.type == PF_ADDR_ADDRMASK &&
402 	    dst->addr.type == PF_ADDR_ADDRMASK &&
403 	    PF_AZERO(&src->addr.v.a.addr, AF_INET6) &&
404 	    PF_AZERO(&src->addr.v.a.mask, AF_INET6) &&
405 	    PF_AZERO(&dst->addr.v.a.addr, AF_INET6) &&
406 	    PF_AZERO(&dst->addr.v.a.mask, AF_INET6) &&
407 	    !src->neg && !dst->neg &&
408 	    !src->port_op && !dst->port_op &&
409 	    osfp == PF_OSFP_ANY)
410 		printf(" all");
411 	else {
412 		printf(" from ");
413 		if (src->neg)
414 			printf("! ");
415 		print_addr(&src->addr, af, verbose);
416 		if (src->port_op)
417 			print_port(src->port_op, src->port[0],
418 			    src->port[1],
419 			    proto == IPPROTO_TCP ? "tcp" : "udp");
420 		if (osfp != PF_OSFP_ANY)
421 			printf(" os \"%s\"", pfctl_lookup_fingerprint(osfp, buf,
422 			    sizeof(buf)));
423 
424 		printf(" to ");
425 		if (dst->neg)
426 			printf("! ");
427 		print_addr(&dst->addr, af, verbose);
428 		if (dst->port_op)
429 			print_port(dst->port_op, dst->port[0],
430 			    dst->port[1],
431 			    proto == IPPROTO_TCP ? "tcp" : "udp");
432 	}
433 }
434 
435 void
436 print_pool(struct pf_pool *pool, u_int16_t p1, u_int16_t p2,
437     sa_family_t af, int id)
438 {
439 	struct pf_pooladdr	*pooladdr;
440 
441 	if ((TAILQ_FIRST(&pool->list) != NULL) &&
442 	    TAILQ_NEXT(TAILQ_FIRST(&pool->list), entries) != NULL)
443 		printf("{ ");
444 	TAILQ_FOREACH(pooladdr, &pool->list, entries){
445 		switch (id) {
446 		case PF_NAT:
447 		case PF_RDR:
448 		case PF_BINAT:
449 			print_addr(&pooladdr->addr, af, 0);
450 			break;
451 		case PF_PASS:
452 			if (PF_AZERO(&pooladdr->addr.v.a.addr, af))
453 				printf("%s", pooladdr->ifname);
454 			else {
455 				printf("(%s ", pooladdr->ifname);
456 				print_addr(&pooladdr->addr, af, 0);
457 				printf(")");
458 			}
459 			break;
460 		default:
461 			break;
462 		}
463 		if (TAILQ_NEXT(pooladdr, entries) != NULL)
464 			printf(", ");
465 		else if (TAILQ_NEXT(TAILQ_FIRST(&pool->list), entries) != NULL)
466 			printf(" }");
467 	}
468 	switch (id) {
469 	case PF_NAT:
470 		if ((p1 != PF_NAT_PROXY_PORT_LOW ||
471 		    p2 != PF_NAT_PROXY_PORT_HIGH) && (p1 != 0 || p2 != 0)) {
472 			if (p1 == p2)
473 				printf(" port %u", p1);
474 			else
475 				printf(" port %u:%u", p1, p2);
476 		}
477 		break;
478 	case PF_RDR:
479 		if (p1) {
480 			printf(" port %u", p1);
481 			if (p2 && (p2 != p1))
482 				printf(":%u", p2);
483 		}
484 		break;
485 	default:
486 		break;
487 	}
488 	switch (pool->opts & PF_POOL_TYPEMASK) {
489 	case PF_POOL_NONE:
490 		break;
491 	case PF_POOL_BITMASK:
492 		printf(" bitmask");
493 		break;
494 	case PF_POOL_RANDOM:
495 		printf(" random");
496 		break;
497 	case PF_POOL_SRCHASH:
498 		printf(" source-hash 0x%08x%08x%08x%08x",
499 		    pool->key.key32[0], pool->key.key32[1],
500 		    pool->key.key32[2], pool->key.key32[3]);
501 		break;
502 	case PF_POOL_ROUNDROBIN:
503 		printf(" round-robin");
504 		break;
505 	}
506 	if (pool->opts & PF_POOL_STICKYADDR)
507 		printf(" sticky-address");
508 	if (id == PF_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_fcounters[FCNT_MAX+1] = FCNT_NAMES;
514 const char	*pf_scounters[FCNT_MAX+1] = FCNT_NAMES;
515 
516 void
517 print_status(struct pf_status *s, int opts)
518 {
519 	char	statline[80], *running;
520 	time_t	runtime;
521 	int	i;
522 
523 	runtime = time(NULL) - s->since;
524 	running = s->running ? "Enabled" : "Disabled";
525 
526 	if (s->since) {
527 		unsigned	sec, min, hrs, day = runtime;
528 
529 		sec = day % 60;
530 		day /= 60;
531 		min = day % 60;
532 		day /= 60;
533 		hrs = day % 24;
534 		day /= 24;
535 		snprintf(statline, sizeof(statline),
536 		    "Status: %s for %u days %.2u:%.2u:%.2u",
537 		    running, day, hrs, min, sec);
538 	} else
539 		snprintf(statline, sizeof(statline), "Status: %s", running);
540 	printf("%-44s", statline);
541 	switch (s->debug) {
542 	case PF_DEBUG_NONE:
543 		printf("%15s\n\n", "Debug: None");
544 		break;
545 	case PF_DEBUG_URGENT:
546 		printf("%15s\n\n", "Debug: Urgent");
547 		break;
548 	case PF_DEBUG_MISC:
549 		printf("%15s\n\n", "Debug: Misc");
550 		break;
551 	case PF_DEBUG_NOISY:
552 		printf("%15s\n\n", "Debug: Loud");
553 		break;
554 	}
555 	printf("Hostid: 0x%08x\n\n", ntohl(s->hostid));
556 	if (s->ifname[0] != 0) {
557 		printf("Interface Stats for %-16s %5s %16s\n",
558 		    s->ifname, "IPv4", "IPv6");
559 		printf("  %-25s %14llu %16llu\n", "Bytes In",
560 		    (unsigned long long)s->bcounters[0][0],
561 		    (unsigned long long)s->bcounters[1][0]);
562 		printf("  %-25s %14llu %16llu\n", "Bytes Out",
563 		    (unsigned long long)s->bcounters[0][1],
564 		    (unsigned long long)s->bcounters[1][1]);
565 		printf("  Packets In\n");
566 		printf("    %-23s %14llu %16llu\n", "Passed",
567 		    (unsigned long long)s->pcounters[0][0][PF_PASS],
568 		    (unsigned long long)s->pcounters[1][0][PF_PASS]);
569 		printf("    %-23s %14llu %16llu\n", "Blocked",
570 		    (unsigned long long)s->pcounters[0][0][PF_DROP],
571 		    (unsigned long long)s->pcounters[1][0][PF_DROP]);
572 		printf("  Packets Out\n");
573 		printf("    %-23s %14llu %16llu\n", "Passed",
574 		    (unsigned long long)s->pcounters[0][1][PF_PASS],
575 		    (unsigned long long)s->pcounters[1][1][PF_PASS]);
576 		printf("    %-23s %14llu %16llu\n\n", "Blocked",
577 		    (unsigned long long)s->pcounters[0][1][PF_DROP],
578 		    (unsigned long long)s->pcounters[1][1][PF_DROP]);
579 	}
580 	printf("%-27s %14s %16s\n", "State Table", "Total", "Rate");
581 	printf("  %-25s %14u %14s\n", "current entries", s->states, "");
582 	for (i = 0; i < FCNT_MAX; i++) {
583 		printf("  %-25s %14llu ", pf_fcounters[i],
584 			    (unsigned long long)s->fcounters[i]);
585 		if (runtime > 0)
586 			printf("%14.1f/s\n",
587 			    (double)s->fcounters[i] / (double)runtime);
588 		else
589 			printf("%14s\n", "");
590 	}
591 	if (opts & PF_OPT_VERBOSE) {
592 		printf("Source Tracking Table\n");
593 		printf("  %-25s %14u %14s\n", "current entries",
594 		    s->src_nodes, "");
595 		for (i = 0; i < SCNT_MAX; i++) {
596 			printf("  %-25s %14lld ", pf_scounters[i],
597 				    (unsigned long long)s->scounters[i]);
598 			if (runtime > 0)
599 				printf("%14.1f/s\n",
600 				    (double)s->scounters[i] / (double)runtime);
601 			else
602 				printf("%14s\n", "");
603 		}
604 	}
605 	printf("Counters\n");
606 	for (i = 0; i < PFRES_MAX; i++) {
607 		printf("  %-25s %14llu ", pf_reasons[i],
608 		    (unsigned long long)s->counters[i]);
609 		if (runtime > 0)
610 			printf("%14.1f/s\n",
611 			    (double)s->counters[i] / (double)runtime);
612 		else
613 			printf("%14s\n", "");
614 	}
615 }
616 
617 void
618 print_src_node(struct pf_src_node *sn, int opts)
619 {
620 	struct pf_addr_wrap aw;
621 	int min, sec;
622 
623 	memset(&aw, 0, sizeof(aw));
624 	if (sn->af == AF_INET)
625 		aw.v.a.mask.addr32[0] = 0xffffffff;
626 	else
627 		memset(&aw.v.a.mask, 0xff, sizeof(aw.v.a.mask));
628 
629 	aw.v.a.addr = sn->addr;
630 	print_addr(&aw, sn->af, opts & PF_OPT_VERBOSE2);
631 	printf(" -> ");
632 	aw.v.a.addr = sn->raddr;
633 	print_addr(&aw, sn->af, opts & PF_OPT_VERBOSE2);
634 	printf(" (%d states)\n", sn->states);
635 	if (opts & PF_OPT_VERBOSE) {
636 		sec = sn->creation % 60;
637 		sn->creation /= 60;
638 		min = sn->creation % 60;
639 		sn->creation /= 60;
640 		printf("   age %.2u:%.2u:%.2u", sn->creation, min, sec);
641 		if (sn->states == 0) {
642 			sec = sn->expire % 60;
643 			sn->expire /= 60;
644 			min = sn->expire % 60;
645 			sn->expire /= 60;
646 			printf(", expires in %.2u:%.2u:%.2u",
647 			    sn->expire, min, sec);
648 		}
649 		printf(", %u pkts, %u bytes", sn->packets, sn->bytes);
650 		switch (sn->ruletype) {
651 		case PF_NAT:
652 			if (sn->rule.nr != -1)
653 				printf(", nat rule %u", sn->rule.nr);
654 			break;
655 		case PF_RDR:
656 			if (sn->rule.nr != -1)
657 				printf(", rdr rule %u", sn->rule.nr);
658 			break;
659 		case PF_PASS:
660 			if (sn->rule.nr != -1)
661 				printf(", filter rule %u", sn->rule.nr);
662 			break;
663 		}
664 		printf("\n");
665 	}
666 }
667 
668 void
669 print_rule(struct pf_rule *r, const char *anchor_call, int verbose)
670 {
671 	static const char *actiontypes[] = { "pass", "block", "scrub", "nat",
672 	    "no nat", "binat", "no binat", "rdr", "no rdr" };
673 	static const char *anchortypes[] = { "anchor", "anchor", "anchor",
674 	    "nat-anchor", "nat-anchor", "binat-anchor", "binat-anchor",
675 	    "rdr-anchor", "rdr-anchor" };
676 	int	i, opts;
677 
678 	if (verbose)
679 		printf("@%d ", r->nr);
680 	if (r->action > PF_NORDR)
681 		printf("action(%d)", r->action);
682 	else if (anchor_call[0])
683 		printf("%s %s", anchortypes[r->action], anchor_call);
684 	else {
685 		printf("%s", actiontypes[r->action]);
686 		if (r->natpass)
687 			printf(" pass");
688 	}
689 	if (r->action == PF_DROP) {
690 		if (r->rule_flag & PFRULE_RETURN)
691 			printf(" return");
692 		else if (r->rule_flag & PFRULE_RETURNRST) {
693 			if (!r->return_ttl)
694 				printf(" return-rst");
695 			else
696 				printf(" return-rst(ttl %d)", r->return_ttl);
697 		} else if (r->rule_flag & PFRULE_RETURNICMP) {
698 			const struct icmpcodeent	*ic, *ic6;
699 
700 			ic = geticmpcodebynumber(r->return_icmp >> 8,
701 			    r->return_icmp & 255, AF_INET);
702 			ic6 = geticmpcodebynumber(r->return_icmp6 >> 8,
703 			    r->return_icmp6 & 255, AF_INET6);
704 
705 			switch (r->af) {
706 			case AF_INET:
707 				printf(" return-icmp");
708 				if (ic == NULL)
709 					printf("(%u)", r->return_icmp & 255);
710 				else
711 					printf("(%s)", ic->name);
712 				break;
713 			case AF_INET6:
714 				printf(" return-icmp6");
715 				if (ic6 == NULL)
716 					printf("(%u)", r->return_icmp6 & 255);
717 				else
718 					printf("(%s)", ic6->name);
719 				break;
720 			default:
721 				printf(" return-icmp");
722 				if (ic == NULL)
723 					printf("(%u, ", r->return_icmp & 255);
724 				else
725 					printf("(%s, ", ic->name);
726 				if (ic6 == NULL)
727 					printf("%u)", r->return_icmp6 & 255);
728 				else
729 					printf("%s)", ic6->name);
730 				break;
731 			}
732 		} else
733 			printf(" drop");
734 	}
735 	if (r->direction == PF_IN)
736 		printf(" in");
737 	else if (r->direction == PF_OUT)
738 		printf(" out");
739 	if (r->log == 1)
740 		printf(" log");
741 	else if (r->log == 2)
742 		printf(" log-all");
743 	if (r->quick)
744 		printf(" quick");
745 	if (r->ifname[0]) {
746 		if (r->ifnot)
747 			printf(" on ! %s", r->ifname);
748 		else
749 			printf(" on %s", r->ifname);
750 	}
751 	if (r->rt) {
752 		if (r->rt == PF_ROUTETO)
753 			printf(" route-to");
754 		else if (r->rt == PF_REPLYTO)
755 			printf(" reply-to");
756 		else if (r->rt == PF_DUPTO)
757 			printf(" dup-to");
758 		else if (r->rt == PF_FASTROUTE)
759 			printf(" fastroute");
760 		if (r->rt != PF_FASTROUTE) {
761 			printf(" ");
762 			print_pool(&r->rpool, 0, 0, r->af, PF_PASS);
763 		}
764 	}
765 	if (r->af) {
766 		if (r->af == AF_INET)
767 			printf(" inet");
768 		else
769 			printf(" inet6");
770 	}
771 	if (r->proto) {
772 		struct protoent	*p;
773 
774 		if ((p = getprotobynumber(r->proto)) != NULL)
775 			printf(" proto %s", p->p_name);
776 		else
777 			printf(" proto %u", r->proto);
778 	}
779 	print_fromto(&r->src, r->os_fingerprint, &r->dst, r->af, r->proto,
780 	    verbose);
781 	if (r->uid.op)
782 		print_ugid(r->uid.op, r->uid.uid[0], r->uid.uid[1], "user",
783 		    UID_MAX);
784 	if (r->gid.op)
785 		print_ugid(r->gid.op, r->gid.gid[0], r->gid.gid[1], "group",
786 		    GID_MAX);
787 	if (r->flags || r->flagset) {
788 		printf(" flags ");
789 		print_flags(r->flags);
790 		printf("/");
791 		print_flags(r->flagset);
792 	}
793 	if (r->type) {
794 		const struct icmptypeent	*it;
795 
796 		it = geticmptypebynumber(r->type-1, r->af);
797 		if (r->af != AF_INET6)
798 			printf(" icmp-type");
799 		else
800 			printf(" icmp6-type");
801 		if (it != NULL)
802 			printf(" %s", it->name);
803 		else
804 			printf(" %u", r->type-1);
805 		if (r->code) {
806 			const struct icmpcodeent	*ic;
807 
808 			ic = geticmpcodebynumber(r->type-1, r->code-1, r->af);
809 			if (ic != NULL)
810 				printf(" code %s", ic->name);
811 			else
812 				printf(" code %u", r->code-1);
813 		}
814 	}
815 	if (r->tos)
816 		printf(" tos 0x%2.2x", r->tos);
817 	if (r->keep_state == PF_STATE_NORMAL)
818 		printf(" keep state");
819 	else if (r->keep_state == PF_STATE_MODULATE)
820 		printf(" modulate state");
821 	else if (r->keep_state == PF_STATE_SYNPROXY)
822 		printf(" synproxy state");
823 	if (r->prob) {
824 		char	buf[20];
825 
826 		snprintf(buf, sizeof(buf), "%f", r->prob*100.0/(UINT_MAX+1.0));
827 		for (i = strlen(buf)-1; i > 0; i--) {
828 			if (buf[i] == '0')
829 				buf[i] = '\0';
830 			else {
831 				if (buf[i] == '.')
832 					buf[i] = '\0';
833 				break;
834 			}
835 		}
836 		printf(" probability %s%%", buf);
837 	}
838 	opts = 0;
839 	if (r->max_states || r->max_src_nodes || r->max_src_states)
840 		opts = 1;
841 	if (r->rule_flag & PFRULE_NOSYNC)
842 		opts = 1;
843 	if (r->rule_flag & PFRULE_SRCTRACK)
844 		opts = 1;
845 	if (r->rule_flag & (PFRULE_IFBOUND | PFRULE_GRBOUND))
846 		opts = 1;
847 	for (i = 0; !opts && i < PFTM_MAX; ++i)
848 		if (r->timeout[i])
849 			opts = 1;
850 	if (opts) {
851 		printf(" (");
852 		if (r->max_states) {
853 			printf("max %u", r->max_states);
854 			opts = 0;
855 		}
856 		if (r->rule_flag & PFRULE_NOSYNC) {
857 			if (!opts)
858 				printf(", ");
859 			printf("no-sync");
860 			opts = 0;
861 		}
862 		if (r->rule_flag & PFRULE_SRCTRACK) {
863 			if (!opts)
864 				printf(", ");
865 			printf("source-track");
866 			if (r->rule_flag & PFRULE_RULESRCTRACK)
867 				printf(" rule");
868 			else
869 				printf(" global");
870 			opts = 0;
871 		}
872 		if (r->max_src_states) {
873 			if (!opts)
874 				printf(", ");
875 			printf("max-src-states %u", r->max_src_states);
876 			opts = 0;
877 		}
878 		if (r->max_src_nodes) {
879 			if (!opts)
880 				printf(", ");
881 			printf("max-src-nodes %u", r->max_src_nodes);
882 			opts = 0;
883 		}
884 		if (r->rule_flag & PFRULE_IFBOUND) {
885 			if (!opts)
886 				printf(", ");
887 			printf("if-bound");
888 			opts = 0;
889 		}
890 		if (r->rule_flag & PFRULE_GRBOUND) {
891 			if (!opts)
892 				printf(", ");
893 			printf("group-bound");
894 			opts = 0;
895 		}
896 		for (i = 0; i < PFTM_MAX; ++i)
897 			if (r->timeout[i]) {
898 				if (!opts)
899 					printf(", ");
900 				opts = 0;
901 				printf("%s %u", pf_timeouts[i].name,
902 				    r->timeout[i]);
903 			}
904 		printf(")");
905 	}
906 	if (r->rule_flag & PFRULE_FRAGMENT)
907 		printf(" fragment");
908 	if (r->rule_flag & PFRULE_NODF)
909 		printf(" no-df");
910 	if (r->rule_flag & PFRULE_RANDOMID)
911 		printf(" random-id");
912 	if (r->min_ttl)
913 		printf(" min-ttl %d", r->min_ttl);
914 	if (r->max_mss)
915 		printf(" max-mss %d", r->max_mss);
916 	if (r->allow_opts)
917 		printf(" allow-opts");
918 	if (r->action == PF_SCRUB) {
919 		if (r->rule_flag & PFRULE_REASSEMBLE_TCP)
920 			printf(" reassemble tcp");
921 
922 		if (r->rule_flag & PFRULE_FRAGDROP)
923 			printf(" fragment drop-ovl");
924 		else if (r->rule_flag & PFRULE_FRAGCROP)
925 			printf(" fragment crop");
926 		else
927 			printf(" fragment reassemble");
928 	}
929 	if (r->label[0])
930 		printf(" label \"%s\"", r->label);
931 	if (r->qname[0] && r->pqname[0])
932 		printf(" queue(%s, %s)", r->qname, r->pqname);
933 	else if (r->qname[0])
934 		printf(" queue %s", r->qname);
935 	if (r->tagname[0])
936 		printf(" tag %s", r->tagname);
937 	if (r->match_tagname[0]) {
938 		if (r->match_tag_not)
939 			printf(" !");
940 		printf(" tagged %s", r->match_tagname);
941 	}
942 	if (!anchor_call[0] && (r->action == PF_NAT ||
943 	    r->action == PF_BINAT || r->action == PF_RDR)) {
944 		printf(" -> ");
945 		print_pool(&r->rpool, r->rpool.proxy_port[0],
946 		    r->rpool.proxy_port[1], r->af, r->action);
947 	}
948 	printf("\n");
949 }
950 
951 void
952 print_tabledef(const char *name, int flags, int addrs,
953     struct node_tinithead *nodes)
954 {
955 	struct node_tinit	*ti, *nti;
956 	struct node_host	*h;
957 
958 	printf("table <%s>", name);
959 	if (flags & PFR_TFLAG_CONST)
960 		printf(" const");
961 	if (flags & PFR_TFLAG_PERSIST)
962 		printf(" persist");
963 	SIMPLEQ_FOREACH(ti, nodes, entries) {
964 		if (ti->file) {
965 			printf(" file \"%s\"", ti->file);
966 			continue;
967 		}
968 		printf(" {");
969 		for (;;) {
970 			for (h = ti->host; h != NULL; h = h->next) {
971 				printf(h->not ? " !" : " ");
972 				print_addr(&h->addr, h->af, 0);
973 			}
974 			nti = SIMPLEQ_NEXT(ti, entries);
975 			if (nti != NULL && nti->file == NULL)
976 				ti = nti;	/* merge lists */
977 			else
978 				break;
979 		}
980 		printf(" }");
981 	}
982 	if (addrs && SIMPLEQ_EMPTY(nodes))
983 		printf(" { }");
984 	printf("\n");
985 }
986 
987 int
988 parse_flags(char *s)
989 {
990 	char		*p, *q;
991 	u_int8_t	 f = 0;
992 
993 	for (p = s; *p; p++) {
994 		if ((q = strchr(tcpflags, *p)) == NULL)
995 			return -1;
996 		else
997 			f |= 1 << (q - tcpflags);
998 	}
999 	return (f ? f : PF_TH_ALL);
1000 }
1001 
1002 void
1003 set_ipmask(struct node_host *h, u_int8_t b)
1004 {
1005 	struct pf_addr	*m, *n;
1006 	int		 i, j = 0;
1007 
1008 	m = &h->addr.v.a.mask;
1009 	memset(m, 0, sizeof(*m));
1010 
1011 	while (b >= 32) {
1012 		m->addr32[j++] = 0xffffffff;
1013 		b -= 32;
1014 	}
1015 	for (i = 31; i > 31-b; --i)
1016 		m->addr32[j] |= (1 << i);
1017 	if (b)
1018 		m->addr32[j] = htonl(m->addr32[j]);
1019 
1020 	/* Mask off bits of the address that will never be used. */
1021 	n = &h->addr.v.a.addr;
1022 	if (h->addr.type == PF_ADDR_ADDRMASK)
1023 		for (i = 0; i < 4; i++)
1024 			n->addr32[i] = n->addr32[i] & m->addr32[i];
1025 }
1026 
1027 int
1028 check_netmask(struct node_host *h, sa_family_t af)
1029 {
1030 	struct node_host	*n = NULL;
1031 	struct pf_addr	*m;
1032 
1033 	for (n = h; n != NULL; n = n->next) {
1034 		if (h->addr.type == PF_ADDR_TABLE)
1035 			continue;
1036 		m = &h->addr.v.a.mask;
1037 		/* fix up netmask for dynaddr */
1038 		if (af == AF_INET && h->addr.type == PF_ADDR_DYNIFTL &&
1039 		    unmask(m, AF_INET6) > 32)
1040 			set_ipmask(n, 32);
1041 		/* netmasks > 32 bit are invalid on v4 */
1042 		if (af == AF_INET &&
1043 		    (m->addr32[1] || m->addr32[2] || m->addr32[3])) {
1044 			fprintf(stderr, "netmask %u invalid for IPv4 address\n",
1045 			    unmask(m, AF_INET6));
1046 			return (1);
1047 		}
1048 	}
1049 	return (0);
1050 }
1051 
1052 /* interface lookup routines */
1053 
1054 struct node_host	*iftab;
1055 
1056 void
1057 ifa_load(void)
1058 {
1059 	struct ifaddrs		*ifap, *ifa;
1060 	struct node_host	*n = NULL, *h = NULL;
1061 
1062 	if (getifaddrs(&ifap) < 0)
1063 		err(1, "getifaddrs");
1064 
1065 	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
1066 		if (!(ifa->ifa_addr->sa_family == AF_INET ||
1067 		    ifa->ifa_addr->sa_family == AF_INET6 ||
1068 		    ifa->ifa_addr->sa_family == AF_LINK))
1069 				continue;
1070 		n = calloc(1, sizeof(struct node_host));
1071 		if (n == NULL)
1072 			err(1, "address: calloc");
1073 		n->af = ifa->ifa_addr->sa_family;
1074 		n->ifa_flags = ifa->ifa_flags;
1075 #ifdef __KAME__
1076 		if (n->af == AF_INET6 &&
1077 		    IN6_IS_ADDR_LINKLOCAL(&((struct sockaddr_in6 *)
1078 		    ifa->ifa_addr)->sin6_addr) &&
1079 		    ((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_scope_id ==
1080 		    0) {
1081 			struct sockaddr_in6	*sin6;
1082 
1083 			sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
1084 			sin6->sin6_scope_id = sin6->sin6_addr.s6_addr[2] << 8 |
1085 			    sin6->sin6_addr.s6_addr[3];
1086 			sin6->sin6_addr.s6_addr[2] = 0;
1087 			sin6->sin6_addr.s6_addr[3] = 0;
1088 		}
1089 #endif
1090 		n->ifindex = 0;
1091 		if (n->af == AF_INET) {
1092 			memcpy(&n->addr.v.a.addr, &((struct sockaddr_in *)
1093 			    ifa->ifa_addr)->sin_addr.s_addr,
1094 			    sizeof(struct in_addr));
1095 			memcpy(&n->addr.v.a.mask, &((struct sockaddr_in *)
1096 			    ifa->ifa_netmask)->sin_addr.s_addr,
1097 			    sizeof(struct in_addr));
1098 			if (ifa->ifa_broadaddr != NULL)
1099 				memcpy(&n->bcast, &((struct sockaddr_in *)
1100 				    ifa->ifa_broadaddr)->sin_addr.s_addr,
1101 				    sizeof(struct in_addr));
1102 			if (ifa->ifa_dstaddr != NULL)
1103 				memcpy(&n->peer, &((struct sockaddr_in *)
1104 				    ifa->ifa_dstaddr)->sin_addr.s_addr,
1105 				    sizeof(struct in_addr));
1106 		} else if (n->af == AF_INET6) {
1107 			memcpy(&n->addr.v.a.addr, &((struct sockaddr_in6 *)
1108 			    ifa->ifa_addr)->sin6_addr.s6_addr,
1109 			    sizeof(struct in6_addr));
1110 			memcpy(&n->addr.v.a.mask, &((struct sockaddr_in6 *)
1111 			    ifa->ifa_netmask)->sin6_addr.s6_addr,
1112 			    sizeof(struct in6_addr));
1113 			if (ifa->ifa_broadaddr != NULL)
1114 				memcpy(&n->bcast, &((struct sockaddr_in6 *)
1115 				    ifa->ifa_broadaddr)->sin6_addr.s6_addr,
1116 				    sizeof(struct in6_addr));
1117 			if (ifa->ifa_dstaddr != NULL)
1118 				 memcpy(&n->peer, &((struct sockaddr_in6 *)
1119 				    ifa->ifa_dstaddr)->sin6_addr.s6_addr,
1120 				    sizeof(struct in6_addr));
1121 			n->ifindex = ((struct sockaddr_in6 *)
1122 			    ifa->ifa_addr)->sin6_scope_id;
1123 		}
1124 		if ((n->ifname = strdup(ifa->ifa_name)) == NULL)
1125 			err(1, "ifa_load: strdup");
1126 		n->next = NULL;
1127 		n->tail = n;
1128 		if (h == NULL)
1129 			h = n;
1130 		else {
1131 			h->tail->next = n;
1132 			h->tail = n;
1133 		}
1134 	}
1135 
1136 	iftab = h;
1137 	freeifaddrs(ifap);
1138 }
1139 
1140 struct node_host *
1141 ifa_exists(const char *ifa_name, int group_ok)
1142 {
1143 	struct node_host	*n;
1144 
1145 	if (iftab == NULL)
1146 		ifa_load();
1147 
1148 	for (n = iftab; n; n = n->next) {
1149 		if (n->af == AF_LINK && !strncmp(n->ifname, ifa_name, IFNAMSIZ))
1150 			return (n);
1151 	}
1152 
1153 	return (NULL);
1154 }
1155 
1156 struct node_host *
1157 ifa_lookup(const char *ifa_name, int flags)
1158 {
1159 	struct node_host	*p = NULL, *h = NULL, *n = NULL;
1160 	int			 got4 = 0, got6 = 0;
1161 	const char		 *last_if = NULL;
1162 
1163 	if (!strncmp(ifa_name, "self", IFNAMSIZ))
1164 		ifa_name = NULL;
1165 
1166 	if (iftab == NULL)
1167 		ifa_load();
1168 
1169 	for (p = iftab; p; p = p->next) {
1170 		if (ifa_skip_if(ifa_name, p))
1171 			continue;
1172 		if ((flags & PFI_AFLAG_BROADCAST) && p->af != AF_INET)
1173 			continue;
1174 		if ((flags & PFI_AFLAG_BROADCAST) &&
1175 		    !(p->ifa_flags & IFF_BROADCAST))
1176 			continue;
1177 		if ((flags & PFI_AFLAG_PEER) &&
1178 		    !(p->ifa_flags & IFF_POINTOPOINT))
1179 			continue;
1180 		if ((flags & PFI_AFLAG_NETWORK) && p->ifindex > 0)
1181 			continue;
1182 		if (last_if == NULL || strcmp(last_if, p->ifname))
1183 			got4 = got6 = 0;
1184 		last_if = p->ifname;
1185 		if ((flags & PFI_AFLAG_NOALIAS) && p->af == AF_INET && got4)
1186 			continue;
1187 		if ((flags & PFI_AFLAG_NOALIAS) && p->af == AF_INET6 && got6)
1188 			continue;
1189 		if (p->af == AF_INET)
1190 			got4 = 1;
1191 		else
1192 			got6 = 1;
1193 		n = calloc(1, sizeof(struct node_host));
1194 		if (n == NULL)
1195 			err(1, "address: calloc");
1196 		n->af = p->af;
1197 		if (flags & PFI_AFLAG_BROADCAST)
1198 			memcpy(&n->addr.v.a.addr, &p->bcast,
1199 			    sizeof(struct pf_addr));
1200 		else if (flags & PFI_AFLAG_PEER)
1201 			memcpy(&n->addr.v.a.addr, &p->peer,
1202 			    sizeof(struct pf_addr));
1203 		else
1204 			memcpy(&n->addr.v.a.addr, &p->addr.v.a.addr,
1205 			    sizeof(struct pf_addr));
1206 		if (flags & PFI_AFLAG_NETWORK)
1207 			set_ipmask(n, unmask(&p->addr.v.a.mask, n->af));
1208 		else {
1209 			if (n->af == AF_INET) {
1210 				if (p->ifa_flags & IFF_LOOPBACK &&
1211 				    p->ifa_flags & IFF_LINK1)
1212 					memcpy(&n->addr.v.a.mask,
1213 					    &p->addr.v.a.mask,
1214 					    sizeof(struct pf_addr));
1215 				else
1216 					set_ipmask(n, 32);
1217 			} else
1218 				set_ipmask(n, 128);
1219 		}
1220 		n->ifindex = p->ifindex;
1221 
1222 		n->next = NULL;
1223 		n->tail = n;
1224 		if (h == NULL)
1225 			h = n;
1226 		else {
1227 			h->tail->next = n;
1228 			h->tail = n;
1229 		}
1230 	}
1231 	return (h);
1232 }
1233 
1234 int
1235 ifa_skip_if(const char *filter, struct node_host *p)
1236 {
1237 	int	n;
1238 
1239 	if (p->af != AF_INET && p->af != AF_INET6)
1240 		return (1);
1241 	if (filter == NULL || !*filter)
1242 		return (0);
1243 	if (!strcmp(p->ifname, filter))
1244 		return (0);	/* exact match */
1245 	n = strlen(filter);
1246 	if (n < 1 || n >= IFNAMSIZ)
1247 		return (1);	/* sanity check */
1248 	if (filter[n-1] >= '0' && filter[n-1] <= '9')
1249 		return (1);	/* only do exact match in that case */
1250 	if (strncmp(p->ifname, filter, n))
1251 		return (1);	/* prefix doesn't match */
1252 	return (p->ifname[n] < '0' || p->ifname[n] > '9');
1253 }
1254 
1255 
1256 struct node_host *
1257 host(const char *s)
1258 {
1259 	struct node_host	*h = NULL;
1260 	int			 mask, v4mask, v6mask, cont = 1;
1261 	char			*p, *q, *ps;
1262 
1263 	if ((p = strrchr(s, '/')) != NULL) {
1264 		mask = strtol(p+1, &q, 0);
1265 		if (!q || *q || mask > 128 || q == (p+1)) {
1266 			fprintf(stderr, "invalid netmask\n");
1267 			return (NULL);
1268 		}
1269 		if ((ps = malloc(strlen(s) - strlen(p) + 1)) == NULL)
1270 			err(1, "host: malloc");
1271 		strlcpy(ps, s, strlen(s) - strlen(p) + 1);
1272 		v4mask = v6mask = mask;
1273 	} else {
1274 		if ((ps = strdup(s)) == NULL)
1275 			err(1, "host: strdup");
1276 		v4mask = 32;
1277 		v6mask = 128;
1278 		mask = -1;
1279 	}
1280 
1281 	/* interface with this name exists? */
1282 	if (cont && (h = host_if(ps, mask)) != NULL)
1283 		cont = 0;
1284 
1285 	/* IPv4 address? */
1286 	if (cont && (h = host_v4(s, mask)) != NULL)
1287 		cont = 0;
1288 
1289 	/* IPv6 address? */
1290 	if (cont && (h = host_v6(ps, v6mask)) != NULL)
1291 		cont = 0;
1292 
1293 	/* dns lookup */
1294 	if (cont && (h = host_dns(ps, v4mask, v6mask)) != NULL)
1295 		cont = 0;
1296 	free(ps);
1297 
1298 	if (h == NULL || cont == 1) {
1299 		fprintf(stderr, "no IP address found for %s\n", s);
1300 		return (NULL);
1301 	}
1302 	return (h);
1303 }
1304 
1305 struct node_host *
1306 host_if(const char *s, int mask)
1307 {
1308 	struct node_host	*n, *h = NULL;
1309 	char			*p, *ps;
1310 	int			 flags = 0;
1311 
1312 	if ((ps = strdup(s)) == NULL)
1313 		err(1, "host_if: strdup");
1314 	while ((p = strrchr(ps, ':')) != NULL) {
1315 		if (!strcmp(p+1, "network"))
1316 			flags |= PFI_AFLAG_NETWORK;
1317 		else if (!strcmp(p+1, "broadcast"))
1318 			flags |= PFI_AFLAG_BROADCAST;
1319 		else if (!strcmp(p+1, "peer"))
1320 			flags |= PFI_AFLAG_PEER;
1321 		else if (!strcmp(p+1, "0"))
1322 			flags |= PFI_AFLAG_NOALIAS;
1323 		else {
1324 			free(ps);
1325 			return (NULL);
1326 		}
1327 		*p = '\0';
1328 	}
1329 	if (flags & (flags - 1) & PFI_AFLAG_MODEMASK) { /* Yep! */
1330 		fprintf(stderr, "illegal combination of interface modifiers\n");
1331 		free(ps);
1332 		return (NULL);
1333 	}
1334 	if ((flags & (PFI_AFLAG_NETWORK|PFI_AFLAG_BROADCAST)) && mask > -1) {
1335 		fprintf(stderr, "network or broadcast lookup, but "
1336 		    "extra netmask given\n");
1337 		free(ps);
1338 		return (NULL);
1339 	}
1340 	if (ifa_exists(ps, 1) || !strncmp(ps, "self", IFNAMSIZ)) {
1341 		/* interface with this name exists */
1342 		h = ifa_lookup(ps, flags);
1343 		for (n = h; n != NULL && mask > -1; n = n->next)
1344 			set_ipmask(n, mask);
1345 	}
1346 
1347 	free(ps);
1348 	return (h);
1349 }
1350 
1351 struct node_host *
1352 host_v4(const char *s, int mask)
1353 {
1354 	struct node_host	*h = NULL;
1355 	struct in_addr		 ina;
1356 	int			 bits = 32;
1357 
1358 	memset(&ina, 0, sizeof(struct in_addr));
1359 	if (strrchr(s, '/') != NULL) {
1360 		if ((bits = inet_net_pton(AF_INET, s, &ina, sizeof(ina))) == -1)
1361 			return (NULL);
1362 	} else {
1363 		if (inet_pton(AF_INET, s, &ina) != 1)
1364 			return (NULL);
1365 	}
1366 
1367 	h = calloc(1, sizeof(struct node_host));
1368 	if (h == NULL)
1369 		err(1, "address: calloc");
1370 	h->ifname = NULL;
1371 	h->af = AF_INET;
1372 	h->addr.v.a.addr.addr32[0] = ina.s_addr;
1373 	set_ipmask(h, bits);
1374 	h->next = NULL;
1375 	h->tail = h;
1376 
1377 	return (h);
1378 }
1379 
1380 struct node_host *
1381 host_v6(const char *s, int mask)
1382 {
1383 	struct addrinfo		 hints, *res;
1384 	struct node_host	*h = NULL;
1385 
1386 	memset(&hints, 0, sizeof(hints));
1387 	hints.ai_family = AF_INET6;
1388 	hints.ai_socktype = SOCK_DGRAM; /*dummy*/
1389 	hints.ai_flags = AI_NUMERICHOST;
1390 	if (getaddrinfo(s, "0", &hints, &res) == 0) {
1391 		h = calloc(1, sizeof(struct node_host));
1392 		if (h == NULL)
1393 			err(1, "address: calloc");
1394 		h->ifname = NULL;
1395 		h->af = AF_INET6;
1396 		memcpy(&h->addr.v.a.addr,
1397 		    &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr,
1398 		    sizeof(h->addr.v.a.addr));
1399 		h->ifindex =
1400 		    ((struct sockaddr_in6 *)res->ai_addr)->sin6_scope_id;
1401 		set_ipmask(h, mask);
1402 		freeaddrinfo(res);
1403 		h->next = NULL;
1404 		h->tail = h;
1405 	}
1406 
1407 	return (h);
1408 }
1409 
1410 struct node_host *
1411 host_dns(const char *s, int v4mask, int v6mask)
1412 {
1413 	struct addrinfo		 hints, *res0, *res;
1414 	struct node_host	*n, *h = NULL;
1415 	int			 error, noalias = 0;
1416 	int			 got4 = 0, got6 = 0;
1417 	char			*p, *ps;
1418 
1419 	if ((ps = strdup(s)) == NULL)
1420 		err(1, "host_dns: strdup");
1421 	if ((p = strrchr(ps, ':')) != NULL && !strcmp(p, ":0")) {
1422 		noalias = 1;
1423 		*p = '\0';
1424 	}
1425 	memset(&hints, 0, sizeof(hints));
1426 	hints.ai_family = PF_UNSPEC;
1427 	hints.ai_socktype = SOCK_STREAM; /* DUMMY */
1428 	error = getaddrinfo(ps, NULL, &hints, &res0);
1429 	if (error) {
1430 		free(ps);
1431 		return (h);
1432 	}
1433 
1434 	for (res = res0; res; res = res->ai_next) {
1435 		if (res->ai_family != AF_INET &&
1436 		    res->ai_family != AF_INET6)
1437 			continue;
1438 		if (noalias) {
1439 			if (res->ai_family == AF_INET) {
1440 				if (got4)
1441 					continue;
1442 				got4 = 1;
1443 			} else {
1444 				if (got6)
1445 					continue;
1446 				got6 = 1;
1447 			}
1448 		}
1449 		n = calloc(1, sizeof(struct node_host));
1450 		if (n == NULL)
1451 			err(1, "host_dns: calloc");
1452 		n->ifname = NULL;
1453 		n->af = res->ai_family;
1454 		if (res->ai_family == AF_INET) {
1455 			memcpy(&n->addr.v.a.addr,
1456 			    &((struct sockaddr_in *)
1457 			    res->ai_addr)->sin_addr.s_addr,
1458 			    sizeof(struct in_addr));
1459 			set_ipmask(n, v4mask);
1460 		} else {
1461 			memcpy(&n->addr.v.a.addr,
1462 			    &((struct sockaddr_in6 *)
1463 			    res->ai_addr)->sin6_addr.s6_addr,
1464 			    sizeof(struct in6_addr));
1465 			n->ifindex =
1466 			    ((struct sockaddr_in6 *)
1467 			    res->ai_addr)->sin6_scope_id;
1468 			set_ipmask(n, v6mask);
1469 		}
1470 		n->next = NULL;
1471 		n->tail = n;
1472 		if (h == NULL)
1473 			h = n;
1474 		else {
1475 			h->tail->next = n;
1476 			h->tail = n;
1477 		}
1478 	}
1479 	freeaddrinfo(res0);
1480 	free(ps);
1481 
1482 	return (h);
1483 }
1484 
1485 /*
1486  * convert a hostname to a list of addresses and put them in the given buffer.
1487  * test:
1488  *	if set to 1, only simple addresses are accepted (no netblock, no "!").
1489  */
1490 int
1491 append_addr(struct pfr_buffer *b, char *s, int test)
1492 {
1493 	char			 *r;
1494 	struct node_host	*h, *n;
1495 	int			 rv, not = 0;
1496 
1497 	for (r = s; *r == '!'; r++)
1498 		not = !not;
1499 	if ((n = host(r)) == NULL) {
1500 		errno = 0;
1501 		return (-1);
1502 	}
1503 	rv = append_addr_host(b, n, test, not);
1504 	do {
1505 		h = n;
1506 		n = n->next;
1507 		free(h);
1508 	} while (n != NULL);
1509 	return (rv);
1510 }
1511 
1512 /*
1513  * same as previous function, but with a pre-parsed input and the ability
1514  * to "negate" the result. Does not free the node_host list.
1515  * not:
1516  *      setting it to 1 is equivalent to adding "!" in front of parameter s.
1517  */
1518 int
1519 append_addr_host(struct pfr_buffer *b, struct node_host *n, int test, int not)
1520 {
1521 	int			 bits;
1522 	struct pfr_addr		 addr;
1523 
1524 	do {
1525 		bzero(&addr, sizeof(addr));
1526 		addr.pfra_not = n->not ^ not;
1527 		addr.pfra_af = n->af;
1528 		addr.pfra_net = unmask(&n->addr.v.a.mask, n->af);
1529 		switch (n->af) {
1530 		case AF_INET:
1531 			addr.pfra_ip4addr.s_addr = n->addr.v.a.addr.addr32[0];
1532 			bits = 32;
1533 			break;
1534 		case AF_INET6:
1535 			memcpy(&addr.pfra_ip6addr, &n->addr.v.a.addr.v6,
1536 			    sizeof(struct in6_addr));
1537 			bits = 128;
1538 			break;
1539 		default:
1540 			errno = EINVAL;
1541 			return (-1);
1542 		}
1543 		if ((test && (not || addr.pfra_net != bits)) ||
1544 		    addr.pfra_net > bits) {
1545 			errno = EINVAL;
1546 			return (-1);
1547 		}
1548 		if (pfr_buf_add(b, &addr))
1549 			return (-1);
1550 	} while ((n = n->next) != NULL);
1551 
1552 	return (0);
1553 }
1554 
1555 int
1556 pfctl_add_trans(struct pfr_buffer *buf, int rs_num, const char *anchor)
1557 {
1558 	struct pfioc_trans_e trans;
1559 
1560 	bzero(&trans, sizeof(trans));
1561 	trans.rs_num = rs_num;
1562 	if (strlcpy(trans.anchor, anchor,
1563 	    sizeof(trans.anchor)) >= sizeof(trans.anchor))
1564 		errx(1, "pfctl_add_trans: strlcpy");
1565 
1566 	return pfr_buf_add(buf, &trans);
1567 }
1568 
1569 u_int32_t
1570 pfctl_get_ticket(struct pfr_buffer *buf, int rs_num, const char *anchor)
1571 {
1572 	struct pfioc_trans_e *p;
1573 
1574 	PFRB_FOREACH(p, buf)
1575 		if (rs_num == p->rs_num && !strcmp(anchor, p->anchor))
1576 			return (p->ticket);
1577 	errx(1, "pfctl_get_ticket: assertion failed");
1578 }
1579 
1580 int
1581 pfctl_trans(int dev, struct pfr_buffer *buf, u_long cmd, int from)
1582 {
1583 	struct pfioc_trans trans;
1584 
1585 	bzero(&trans, sizeof(trans));
1586 	trans.size = buf->pfrb_size - from;
1587 	trans.esize = sizeof(struct pfioc_trans_e);
1588 	trans.array = ((struct pfioc_trans_e *)buf->pfrb_caddr) + from;
1589 	return ioctl(dev, cmd, &trans);
1590 }
1591