xref: /netbsd-src/dist/pf/sbin/pfctl/pfctl_parser.c (revision de1dfb1250df962f1ff3a011772cf58e605aed11)
1 /*	$NetBSD: pfctl_parser.c,v 1.3 2004/06/24 11:05:10 hannken Exp $	*/
2 /*	$OpenBSD: pfctl_parser.c,v 1.194.2.1 2004/05/05 04:00:50 brad 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 	{ "udp.first",		PFTM_UDP_FIRST_PACKET },
227 	{ "udp.single",		PFTM_UDP_SINGLE },
228 	{ "udp.multiple",	PFTM_UDP_MULTIPLE },
229 	{ "icmp.first",		PFTM_ICMP_FIRST_PACKET },
230 	{ "icmp.error",		PFTM_ICMP_ERROR_REPLY },
231 	{ "other.first",	PFTM_OTHER_FIRST_PACKET },
232 	{ "other.single",	PFTM_OTHER_SINGLE },
233 	{ "other.multiple",	PFTM_OTHER_MULTIPLE },
234 	{ "frag",		PFTM_FRAG },
235 	{ "interval",		PFTM_INTERVAL },
236 	{ "adaptive.start",	PFTM_ADAPTIVE_START },
237 	{ "adaptive.end",	PFTM_ADAPTIVE_END },
238 	{ "src.track",		PFTM_SRC_NODE },
239 	{ NULL,			0 }
240 };
241 
242 const struct icmptypeent *
243 geticmptypebynumber(u_int8_t type, sa_family_t af)
244 {
245 	unsigned int	i;
246 
247 	if (af != AF_INET6) {
248 		for (i=0; i < (sizeof (icmp_type) / sizeof(icmp_type[0]));
249 		    i++) {
250 			if (type == icmp_type[i].type)
251 				return (&icmp_type[i]);
252 		}
253 	} else {
254 		for (i=0; i < (sizeof (icmp6_type) /
255 		    sizeof(icmp6_type[0])); i++) {
256 			if (type == icmp6_type[i].type)
257 				 return (&icmp6_type[i]);
258 		}
259 	}
260 	return (NULL);
261 }
262 
263 const struct icmptypeent *
264 geticmptypebyname(char *w, sa_family_t af)
265 {
266 	unsigned int	i;
267 
268 	if (af != AF_INET6) {
269 		for (i=0; i < (sizeof (icmp_type) / sizeof(icmp_type[0]));
270 		    i++) {
271 			if (!strcmp(w, icmp_type[i].name))
272 				return (&icmp_type[i]);
273 		}
274 	} else {
275 		for (i=0; i < (sizeof (icmp6_type) /
276 		    sizeof(icmp6_type[0])); i++) {
277 			if (!strcmp(w, icmp6_type[i].name))
278 				return (&icmp6_type[i]);
279 		}
280 	}
281 	return (NULL);
282 }
283 
284 const struct icmpcodeent *
285 geticmpcodebynumber(u_int8_t type, u_int8_t code, sa_family_t af)
286 {
287 	unsigned int	i;
288 
289 	if (af != AF_INET6) {
290 		for (i=0; i < (sizeof (icmp_code) / sizeof(icmp_code[0]));
291 		    i++) {
292 			if (type == icmp_code[i].type &&
293 			    code == icmp_code[i].code)
294 				return (&icmp_code[i]);
295 		}
296 	} else {
297 		for (i=0; i < (sizeof (icmp6_code) /
298 		    sizeof(icmp6_code[0])); i++) {
299 			if (type == icmp6_code[i].type &&
300 			    code == icmp6_code[i].code)
301 				return (&icmp6_code[i]);
302 		}
303 	}
304 	return (NULL);
305 }
306 
307 const struct icmpcodeent *
308 geticmpcodebyname(u_long type, char *w, sa_family_t af)
309 {
310 	unsigned int	i;
311 
312 	if (af != AF_INET6) {
313 		for (i=0; i < (sizeof (icmp_code) / sizeof(icmp_code[0]));
314 		    i++) {
315 			if (type == icmp_code[i].type &&
316 			    !strcmp(w, icmp_code[i].name))
317 				return (&icmp_code[i]);
318 		}
319 	} else {
320 		for (i=0; i < (sizeof (icmp6_code) /
321 		    sizeof(icmp6_code[0])); i++) {
322 			if (type == icmp6_code[i].type &&
323 			    !strcmp(w, icmp6_code[i].name))
324 				return (&icmp6_code[i]);
325 		}
326 	}
327 	return (NULL);
328 }
329 
330 void
331 print_op(u_int8_t op, const char *a1, const char *a2)
332 {
333 	if (op == PF_OP_IRG)
334 		printf(" %s >< %s", a1, a2);
335 	else if (op == PF_OP_XRG)
336 		printf(" %s <> %s", a1, a2);
337 	else if (op == PF_OP_EQ)
338 		printf(" = %s", a1);
339 	else if (op == PF_OP_NE)
340 		printf(" != %s", a1);
341 	else if (op == PF_OP_LT)
342 		printf(" < %s", a1);
343 	else if (op == PF_OP_LE)
344 		printf(" <= %s", a1);
345 	else if (op == PF_OP_GT)
346 		printf(" > %s", a1);
347 	else if (op == PF_OP_GE)
348 		printf(" >= %s", a1);
349 	else if (op == PF_OP_RRG)
350 		printf(" %s:%s", a1, a2);
351 }
352 
353 void
354 print_port(u_int8_t op, u_int16_t p1, u_int16_t p2, const char *proto)
355 {
356 	char		 a1[6], a2[6];
357 	struct servent	*s;
358 
359 	s = getservbyport(p1, proto);
360 	p1 = ntohs(p1);
361 	p2 = ntohs(p2);
362 	snprintf(a1, sizeof(a1), "%u", p1);
363 	snprintf(a2, sizeof(a2), "%u", p2);
364 	printf(" port");
365 	if (s != NULL && (op == PF_OP_EQ || op == PF_OP_NE))
366 		print_op(op, s->s_name, a2);
367 	else
368 		print_op(op, a1, a2);
369 }
370 
371 void
372 print_ugid(u_int8_t op, unsigned u1, unsigned u2, const char *t, unsigned umax)
373 {
374 	char	a1[11], a2[11];
375 
376 	snprintf(a1, sizeof(a1), "%u", u1);
377 	snprintf(a2, sizeof(a2), "%u", u2);
378 	printf(" %s", t);
379 	if (u1 == umax && (op == PF_OP_EQ || op == PF_OP_NE))
380 		print_op(op, "unknown", a2);
381 	else
382 		print_op(op, a1, a2);
383 }
384 
385 void
386 print_flags(u_int8_t f)
387 {
388 	int	i;
389 
390 	for (i = 0; tcpflags[i]; ++i)
391 		if (f & (1 << i))
392 			printf("%c", tcpflags[i]);
393 }
394 
395 void
396 print_fromto(struct pf_rule_addr *src, pf_osfp_t osfp, struct pf_rule_addr *dst,
397     sa_family_t af, u_int8_t proto, int verbose)
398 {
399 	char buf[PF_OSFP_LEN*3];
400 	if (src->addr.type == PF_ADDR_ADDRMASK &&
401 	    dst->addr.type == PF_ADDR_ADDRMASK &&
402 	    PF_AZERO(&src->addr.v.a.addr, AF_INET6) &&
403 	    PF_AZERO(&src->addr.v.a.mask, AF_INET6) &&
404 	    PF_AZERO(&dst->addr.v.a.addr, AF_INET6) &&
405 	    PF_AZERO(&dst->addr.v.a.mask, AF_INET6) &&
406 	    !src->not && !dst->not &&
407 	    !src->port_op && !dst->port_op &&
408 	    osfp == PF_OSFP_ANY)
409 		printf(" all");
410 	else {
411 		printf(" from ");
412 		if (src->not)
413 			printf("! ");
414 		print_addr(&src->addr, af, verbose);
415 		if (src->port_op)
416 			print_port(src->port_op, src->port[0],
417 			    src->port[1],
418 			    proto == IPPROTO_TCP ? "tcp" : "udp");
419 		if (osfp != PF_OSFP_ANY)
420 			printf(" os \"%s\"", pfctl_lookup_fingerprint(osfp, buf,
421 			    sizeof(buf)));
422 
423 		printf(" to ");
424 		if (dst->not)
425 			printf("! ");
426 		print_addr(&dst->addr, af, verbose);
427 		if (dst->port_op)
428 			print_port(dst->port_op, dst->port[0],
429 			    dst->port[1],
430 			    proto == IPPROTO_TCP ? "tcp" : "udp");
431 	}
432 }
433 
434 void
435 print_pool(struct pf_pool *pool, u_int16_t p1, u_int16_t p2,
436     sa_family_t af, int id)
437 {
438 	struct pf_pooladdr	*pooladdr;
439 
440 	if ((TAILQ_FIRST(&pool->list) != NULL) &&
441 	    TAILQ_NEXT(TAILQ_FIRST(&pool->list), entries) != NULL)
442 		printf("{ ");
443 	TAILQ_FOREACH(pooladdr, &pool->list, entries){
444 		switch (id) {
445 		case PF_NAT:
446 		case PF_RDR:
447 		case PF_BINAT:
448 			print_addr(&pooladdr->addr, af, 0);
449 			break;
450 		case PF_PASS:
451 			if (PF_AZERO(&pooladdr->addr.v.a.addr, af))
452 				printf("%s", pooladdr->ifname);
453 			else {
454 				printf("(%s ", pooladdr->ifname);
455 				print_addr(&pooladdr->addr, af, 0);
456 				printf(")");
457 			}
458 			break;
459 		default:
460 			break;
461 		}
462 		if (TAILQ_NEXT(pooladdr, entries) != NULL)
463 			printf(", ");
464 		else if (TAILQ_NEXT(TAILQ_FIRST(&pool->list), entries) != NULL)
465 			printf(" }");
466 	}
467 	switch (id) {
468 	case PF_NAT:
469 		if ((p1 != PF_NAT_PROXY_PORT_LOW ||
470 		    p2 != PF_NAT_PROXY_PORT_HIGH) && (p1 != 0 || p2 != 0)) {
471 			if (p1 == p2)
472 				printf(" port %u", p1);
473 			else
474 				printf(" port %u:%u", p1, p2);
475 		}
476 		break;
477 	case PF_RDR:
478 		if (p1) {
479 			printf(" port %u", p1);
480 			if (p2 && (p2 != p1))
481 				printf(":%u", p2);
482 		}
483 		break;
484 	default:
485 		break;
486 	}
487 	switch (pool->opts & PF_POOL_TYPEMASK) {
488 	case PF_POOL_NONE:
489 		break;
490 	case PF_POOL_BITMASK:
491 		printf(" bitmask");
492 		break;
493 	case PF_POOL_RANDOM:
494 		printf(" random");
495 		break;
496 	case PF_POOL_SRCHASH:
497 		printf(" source-hash 0x%08x%08x%08x%08x",
498 		    pool->key.key32[0], pool->key.key32[1],
499 		    pool->key.key32[2], pool->key.key32[3]);
500 		break;
501 	case PF_POOL_ROUNDROBIN:
502 		printf(" round-robin");
503 		break;
504 	}
505 	if (pool->opts & PF_POOL_STICKYADDR)
506 		printf(" sticky-address");
507 	if (id == PF_NAT && p1 == 0 && p2 == 0)
508 		printf(" static-port");
509 }
510 
511 const char	*pf_reasons[PFRES_MAX+1] = PFRES_NAMES;
512 const char	*pf_fcounters[FCNT_MAX+1] = FCNT_NAMES;
513 const char	*pf_scounters[FCNT_MAX+1] = FCNT_NAMES;
514 
515 void
516 print_status(struct pf_status *s, int opts)
517 {
518 	char	statline[80], *running;
519 	time_t	runtime;
520 	int	i;
521 
522 	runtime = time(NULL) - s->since;
523 	running = s->running ? "Enabled" : "Disabled";
524 
525 	if (s->since) {
526 		unsigned	sec, min, hrs, day = runtime;
527 
528 		sec = day % 60;
529 		day /= 60;
530 		min = day % 60;
531 		day /= 60;
532 		hrs = day % 24;
533 		day /= 24;
534 		snprintf(statline, sizeof(statline),
535 		    "Status: %s for %u days %.2u:%.2u:%.2u",
536 		    running, day, hrs, min, sec);
537 	} else
538 		snprintf(statline, sizeof(statline), "Status: %s", running);
539 	printf("%-44s", statline);
540 	switch (s->debug) {
541 	case PF_DEBUG_NONE:
542 		printf("%15s\n\n", "Debug: None");
543 		break;
544 	case PF_DEBUG_URGENT:
545 		printf("%15s\n\n", "Debug: Urgent");
546 		break;
547 	case PF_DEBUG_MISC:
548 		printf("%15s\n\n", "Debug: Misc");
549 		break;
550 	case PF_DEBUG_NOISY:
551 		printf("%15s\n\n", "Debug: Loud");
552 		break;
553 	}
554 	printf("Hostid: 0x%08x\n\n", ntohl(s->hostid));
555 	if (s->ifname[0] != 0) {
556 		printf("Interface Stats for %-16s %5s %16s\n",
557 		    s->ifname, "IPv4", "IPv6");
558 		printf("  %-25s %14llu %16llu\n", "Bytes In",
559 		    (unsigned long long)s->bcounters[0][0],
560 		    (unsigned long long)s->bcounters[1][0]);
561 		printf("  %-25s %14llu %16llu\n", "Bytes Out",
562 		    (unsigned long long)s->bcounters[0][1],
563 		    (unsigned long long)s->bcounters[1][1]);
564 		printf("  Packets In\n");
565 		printf("    %-23s %14llu %16llu\n", "Passed",
566 		    (unsigned long long)s->pcounters[0][0][PF_PASS],
567 		    (unsigned long long)s->pcounters[1][0][PF_PASS]);
568 		printf("    %-23s %14llu %16llu\n", "Blocked",
569 		    (unsigned long long)s->pcounters[0][0][PF_DROP],
570 		    (unsigned long long)s->pcounters[1][0][PF_DROP]);
571 		printf("  Packets Out\n");
572 		printf("    %-23s %14llu %16llu\n", "Passed",
573 		    (unsigned long long)s->pcounters[0][1][PF_PASS],
574 		    (unsigned long long)s->pcounters[1][1][PF_PASS]);
575 		printf("    %-23s %14llu %16llu\n\n", "Blocked",
576 		    (unsigned long long)s->pcounters[0][1][PF_DROP],
577 		    (unsigned long long)s->pcounters[1][1][PF_DROP]);
578 	}
579 	printf("%-27s %14s %16s\n", "State Table", "Total", "Rate");
580 	printf("  %-25s %14u %14s\n", "current entries", s->states, "");
581 	for (i = 0; i < FCNT_MAX; i++) {
582 		printf("  %-25s %14llu ", pf_fcounters[i],
583 			    (unsigned long long)s->fcounters[i]);
584 		if (runtime > 0)
585 			printf("%14.1f/s\n",
586 			    (double)s->fcounters[i] / (double)runtime);
587 		else
588 			printf("%14s\n", "");
589 	}
590 	if (opts & PF_OPT_VERBOSE) {
591 		printf("Source Tracking Table\n");
592 		printf("  %-25s %14u %14s\n", "current entries",
593 		    s->src_nodes, "");
594 		for (i = 0; i < SCNT_MAX; i++) {
595 			printf("  %-25s %14lld ", pf_scounters[i],
596 				    (unsigned long long)s->scounters[i]);
597 			if (runtime > 0)
598 				printf("%14.1f/s\n",
599 				    (double)s->scounters[i] / (double)runtime);
600 			else
601 				printf("%14s\n", "");
602 		}
603 	}
604 	printf("Counters\n");
605 	for (i = 0; i < PFRES_MAX; i++) {
606 		printf("  %-25s %14llu ", pf_reasons[i],
607 		    (unsigned long long)s->counters[i]);
608 		if (runtime > 0)
609 			printf("%14.1f/s\n",
610 			    (double)s->counters[i] / (double)runtime);
611 		else
612 			printf("%14s\n", "");
613 	}
614 }
615 
616 void
617 print_src_node(struct pf_src_node *sn, int opts)
618 {
619 	struct pf_addr_wrap aw;
620 	int min, sec;
621 
622 	memset(&aw, 0, sizeof(aw));
623 	if (sn->af == AF_INET)
624 		aw.v.a.mask.addr32[0] = 0xffffffff;
625 	else
626 		memset(&aw.v.a.mask, 0xff, sizeof(aw.v.a.mask));
627 
628 	aw.v.a.addr = sn->addr;
629 	print_addr(&aw, sn->af, opts & PF_OPT_VERBOSE2);
630 	printf(" -> ");
631 	aw.v.a.addr = sn->raddr;
632 	print_addr(&aw, sn->af, opts & PF_OPT_VERBOSE2);
633 	printf(" (%d states)\n", sn->states);
634 	if (opts & PF_OPT_VERBOSE) {
635 		sec = sn->creation % 60;
636 		sn->creation /= 60;
637 		min = sn->creation % 60;
638 		sn->creation /= 60;
639 		printf("   age %.2u:%.2u:%.2u", sn->creation, min, sec);
640 		if (sn->states == 0) {
641 			sec = sn->expire % 60;
642 			sn->expire /= 60;
643 			min = sn->expire % 60;
644 			sn->expire /= 60;
645 			printf(", expires in %.2u:%.2u:%.2u",
646 			    sn->expire, min, sec);
647 		}
648 		printf(", %u pkts, %u bytes", sn->packets, sn->bytes);
649 		switch (sn->ruletype) {
650 		case PF_NAT:
651 			if (sn->rule.nr != -1)
652 				printf(", nat rule %u", sn->rule.nr);
653 			break;
654 		case PF_RDR:
655 			if (sn->rule.nr != -1)
656 				printf(", rdr rule %u", sn->rule.nr);
657 			break;
658 		case PF_PASS:
659 			if (sn->rule.nr != -1)
660 				printf(", filter rule %u", sn->rule.nr);
661 			break;
662 		}
663 		printf("\n");
664 	}
665 }
666 
667 void
668 print_rule(struct pf_rule *r, int verbose)
669 {
670 	static const char *actiontypes[] = { "pass", "block", "scrub", "nat",
671 	    "no nat", "binat", "no binat", "rdr", "no rdr" };
672 	static const char *anchortypes[] = { "anchor", "anchor", "anchor",
673 	    "nat-anchor", "nat-anchor", "binat-anchor", "binat-anchor",
674 	    "rdr-anchor", "rdr-anchor" };
675 	int	i, opts;
676 
677 	if (verbose)
678 		printf("@%d ", r->nr);
679 	if (r->action > PF_NORDR)
680 		printf("action(%d)", r->action);
681 	else if (r->anchorname[0])
682 		printf("%s %s", anchortypes[r->action], r->anchorname);
683 	else {
684 		printf("%s", actiontypes[r->action]);
685 		if (r->natpass)
686 			printf(" pass");
687 	}
688 	if (r->action == PF_DROP) {
689 		if (r->rule_flag & PFRULE_RETURN)
690 			printf(" return");
691 		else if (r->rule_flag & PFRULE_RETURNRST) {
692 			if (!r->return_ttl)
693 				printf(" return-rst");
694 			else
695 				printf(" return-rst(ttl %d)", r->return_ttl);
696 		} else if (r->rule_flag & PFRULE_RETURNICMP) {
697 			const struct icmpcodeent	*ic, *ic6;
698 
699 			ic = geticmpcodebynumber(r->return_icmp >> 8,
700 			    r->return_icmp & 255, AF_INET);
701 			ic6 = geticmpcodebynumber(r->return_icmp6 >> 8,
702 			    r->return_icmp6 & 255, AF_INET6);
703 
704 			switch (r->af) {
705 			case AF_INET:
706 				printf(" return-icmp");
707 				if (ic == NULL)
708 					printf("(%u)", r->return_icmp & 255);
709 				else
710 					printf("(%s)", ic->name);
711 				break;
712 			case AF_INET6:
713 				printf(" return-icmp6");
714 				if (ic6 == NULL)
715 					printf("(%u)", r->return_icmp6 & 255);
716 				else
717 					printf("(%s)", ic6->name);
718 				break;
719 			default:
720 				printf(" return-icmp");
721 				if (ic == NULL)
722 					printf("(%u, ", r->return_icmp & 255);
723 				else
724 					printf("(%s, ", ic->name);
725 				if (ic6 == NULL)
726 					printf("%u)", r->return_icmp6 & 255);
727 				else
728 					printf("%s)", ic6->name);
729 				break;
730 			}
731 		} else
732 			printf(" drop");
733 	}
734 	if (r->direction == PF_IN)
735 		printf(" in");
736 	else if (r->direction == PF_OUT)
737 		printf(" out");
738 	if (r->log == 1)
739 		printf(" log");
740 	else if (r->log == 2)
741 		printf(" log-all");
742 	if (r->quick)
743 		printf(" quick");
744 	if (r->ifname[0]) {
745 		if (r->ifnot)
746 			printf(" on ! %s", r->ifname);
747 		else
748 			printf(" on %s", r->ifname);
749 	}
750 	if (r->rt) {
751 		if (r->rt == PF_ROUTETO)
752 			printf(" route-to");
753 		else if (r->rt == PF_REPLYTO)
754 			printf(" reply-to");
755 		else if (r->rt == PF_DUPTO)
756 			printf(" dup-to");
757 		else if (r->rt == PF_FASTROUTE)
758 			printf(" fastroute");
759 		if (r->rt != PF_FASTROUTE) {
760 			printf(" ");
761 			print_pool(&r->rpool, 0, 0, r->af, PF_PASS);
762 		}
763 	}
764 	if (r->af) {
765 		if (r->af == AF_INET)
766 			printf(" inet");
767 		else
768 			printf(" inet6");
769 	}
770 	if (r->proto) {
771 		struct protoent	*p;
772 
773 		if ((p = getprotobynumber(r->proto)) != NULL)
774 			printf(" proto %s", p->p_name);
775 		else
776 			printf(" proto %u", r->proto);
777 	}
778 	print_fromto(&r->src, r->os_fingerprint, &r->dst, r->af, r->proto,
779 	    verbose);
780 	if (r->uid.op)
781 		print_ugid(r->uid.op, r->uid.uid[0], r->uid.uid[1], "user",
782 		    UID_MAX);
783 	if (r->gid.op)
784 		print_ugid(r->gid.op, r->gid.gid[0], r->gid.gid[1], "group",
785 		    GID_MAX);
786 	if (r->flags || r->flagset) {
787 		printf(" flags ");
788 		print_flags(r->flags);
789 		printf("/");
790 		print_flags(r->flagset);
791 	}
792 	if (r->type) {
793 		const struct icmptypeent	*it;
794 
795 		it = geticmptypebynumber(r->type-1, r->af);
796 		if (r->af != AF_INET6)
797 			printf(" icmp-type");
798 		else
799 			printf(" icmp6-type");
800 		if (it != NULL)
801 			printf(" %s", it->name);
802 		else
803 			printf(" %u", r->type-1);
804 		if (r->code) {
805 			const struct icmpcodeent	*ic;
806 
807 			ic = geticmpcodebynumber(r->type-1, r->code-1, r->af);
808 			if (ic != NULL)
809 				printf(" code %s", ic->name);
810 			else
811 				printf(" code %u", r->code-1);
812 		}
813 	}
814 	if (r->tos)
815 		printf(" tos 0x%2.2x", r->tos);
816 	if (r->keep_state == PF_STATE_NORMAL)
817 		printf(" keep state");
818 	else if (r->keep_state == PF_STATE_MODULATE)
819 		printf(" modulate state");
820 	else if (r->keep_state == PF_STATE_SYNPROXY)
821 		printf(" synproxy state");
822 	opts = 0;
823 	if (r->max_states || r->max_src_nodes || r->max_src_states)
824 		opts = 1;
825 	if (r->rule_flag & PFRULE_NOSYNC)
826 		opts = 1;
827 	if (r->rule_flag & PFRULE_SRCTRACK)
828 		opts = 1;
829 	if (r->rule_flag & (PFRULE_IFBOUND | PFRULE_GRBOUND))
830 		opts = 1;
831 	for (i = 0; !opts && i < PFTM_MAX; ++i)
832 		if (r->timeout[i])
833 			opts = 1;
834 	if (opts) {
835 		printf(" (");
836 		if (r->max_states) {
837 			printf("max %u", r->max_states);
838 			opts = 0;
839 		}
840 		if (r->rule_flag & PFRULE_NOSYNC) {
841 			if (!opts)
842 				printf(", ");
843 			printf("no-sync");
844 			opts = 0;
845 		}
846 		if (r->rule_flag & PFRULE_SRCTRACK) {
847 			if (!opts)
848 				printf(", ");
849 			printf("source-track");
850 			if (r->rule_flag & PFRULE_RULESRCTRACK)
851 				printf(" rule");
852 			else
853 				printf(" global");
854 			opts = 0;
855 		}
856 		if (r->max_src_states) {
857 			if (!opts)
858 				printf(", ");
859 			printf("max-src-states %u", r->max_src_states);
860 			opts = 0;
861 		}
862 		if (r->max_src_nodes) {
863 			if (!opts)
864 				printf(", ");
865 			printf("max-src-nodes %u", r->max_src_nodes);
866 			opts = 0;
867 		}
868 		if (r->rule_flag & PFRULE_IFBOUND) {
869 			if (!opts)
870 				printf(", ");
871 			printf("if-bound");
872 			opts = 0;
873 		}
874 		if (r->rule_flag & PFRULE_GRBOUND) {
875 			if (!opts)
876 				printf(", ");
877 			printf("group-bound");
878 			opts = 0;
879 		}
880 		for (i = 0; i < PFTM_MAX; ++i)
881 			if (r->timeout[i]) {
882 				if (!opts)
883 					printf(", ");
884 				opts = 0;
885 				printf("%s %u", pf_timeouts[i].name,
886 				    r->timeout[i]);
887 			}
888 		printf(")");
889 	}
890 	if (r->rule_flag & PFRULE_FRAGMENT)
891 		printf(" fragment");
892 	if (r->rule_flag & PFRULE_NODF)
893 		printf(" no-df");
894 	if (r->rule_flag & PFRULE_RANDOMID)
895 		printf(" random-id");
896 	if (r->min_ttl)
897 		printf(" min-ttl %d", r->min_ttl);
898 	if (r->max_mss)
899 		printf(" max-mss %d", r->max_mss);
900 	if (r->allow_opts)
901 		printf(" allow-opts");
902 	if (r->action == PF_SCRUB) {
903 		if (r->rule_flag & PFRULE_REASSEMBLE_TCP)
904 			printf(" reassemble tcp");
905 
906 		if (r->rule_flag & PFRULE_FRAGDROP)
907 			printf(" fragment drop-ovl");
908 		else if (r->rule_flag & PFRULE_FRAGCROP)
909 			printf(" fragment crop");
910 		else
911 			printf(" fragment reassemble");
912 	}
913 	if (r->label[0])
914 		printf(" label \"%s\"", r->label);
915 	if (r->qname[0] && r->pqname[0])
916 		printf(" queue(%s, %s)", r->qname, r->pqname);
917 	else if (r->qname[0])
918 		printf(" queue %s", r->qname);
919 	if (r->tagname[0])
920 		printf(" tag %s", r->tagname);
921 	if (r->match_tagname[0]) {
922 		if (r->match_tag_not)
923 			printf(" !");
924 		printf(" tagged %s", r->match_tagname);
925 	}
926 	if (!r->anchorname[0] && (r->action == PF_NAT ||
927 	    r->action == PF_BINAT || r->action == PF_RDR)) {
928 		printf(" -> ");
929 		print_pool(&r->rpool, r->rpool.proxy_port[0],
930 		    r->rpool.proxy_port[1], r->af, r->action);
931 	}
932 	printf("\n");
933 }
934 
935 void
936 print_tabledef(const char *name, int flags, int addrs,
937     struct node_tinithead *nodes)
938 {
939 	struct node_tinit	*ti, *nti;
940 	struct node_host	*h;
941 
942 	printf("table <%s>", name);
943 	if (flags & PFR_TFLAG_CONST)
944 		printf(" const");
945 	if (flags & PFR_TFLAG_PERSIST)
946 		printf(" persist");
947 	SIMPLEQ_FOREACH(ti, nodes, entries) {
948 		if (ti->file) {
949 			printf(" file \"%s\"", ti->file);
950 			continue;
951 		}
952 		printf(" {");
953 		for (;;) {
954 			for (h = ti->host; h != NULL; h = h->next) {
955 				printf(h->not ? " !" : " ");
956 				print_addr(&h->addr, h->af, 0);
957 			}
958 			nti = SIMPLEQ_NEXT(ti, entries);
959 			if (nti != NULL && nti->file == NULL)
960 				ti = nti;	/* merge lists */
961 			else
962 				break;
963 		}
964 		printf(" }");
965 	}
966 	if (addrs && SIMPLEQ_EMPTY(nodes))
967 		printf(" { }");
968 	printf("\n");
969 }
970 
971 int
972 parse_flags(char *s)
973 {
974 	char		*p, *q;
975 	u_int8_t	 f = 0;
976 
977 	for (p = s; *p; p++) {
978 		if ((q = strchr(tcpflags, *p)) == NULL)
979 			return -1;
980 		else
981 			f |= 1 << (q - tcpflags);
982 	}
983 	return (f ? f : PF_TH_ALL);
984 }
985 
986 void
987 set_ipmask(struct node_host *h, u_int8_t b)
988 {
989 	struct pf_addr	*m, *n;
990 	int		 i, j = 0;
991 
992 	m = &h->addr.v.a.mask;
993 
994 	for (i = 0; i < 4; i++)
995 		m->addr32[i] = 0;
996 
997 	while (b >= 32) {
998 		m->addr32[j++] = 0xffffffff;
999 		b -= 32;
1000 	}
1001 	for (i = 31; i > 31-b; --i)
1002 		m->addr32[j] |= (1 << i);
1003 	if (b)
1004 		m->addr32[j] = htonl(m->addr32[j]);
1005 
1006 	/* Mask off bits of the address that will never be used. */
1007 	n = &h->addr.v.a.addr;
1008 	if (h->addr.type == PF_ADDR_ADDRMASK)
1009 		for (i = 0; i < 4; i++)
1010 			n->addr32[i] = n->addr32[i] & m->addr32[i];
1011 }
1012 
1013 int
1014 check_netmask(struct node_host *h, sa_family_t af)
1015 {
1016 	struct node_host	*n = NULL;
1017 	struct pf_addr	*m;
1018 
1019 	for (n = h; n != NULL; n = n->next) {
1020 		if (h->addr.type == PF_ADDR_TABLE)
1021 			continue;
1022 		m = &h->addr.v.a.mask;
1023 		/* fix up netmask for dynaddr */
1024 		if (af == AF_INET && h->addr.type == PF_ADDR_DYNIFTL &&
1025 		    unmask(m, AF_INET6) > 32)
1026 			set_ipmask(n, 32);
1027 		/* netmasks > 32 bit are invalid on v4 */
1028 		if (af == AF_INET &&
1029 		    (m->addr32[1] || m->addr32[2] || m->addr32[3])) {
1030 			fprintf(stderr, "netmask %u invalid for IPv4 address\n",
1031 			    unmask(m, AF_INET6));
1032 			return (1);
1033 		}
1034 	}
1035 	return (0);
1036 }
1037 
1038 /* interface lookup routines */
1039 
1040 struct node_host	*iftab;
1041 
1042 void
1043 ifa_load(void)
1044 {
1045 	struct ifaddrs		*ifap, *ifa;
1046 	struct node_host	*n = NULL, *h = NULL;
1047 	struct pfr_buffer	 b;
1048 	struct pfi_if		*p;
1049 
1050 	if (getifaddrs(&ifap) < 0)
1051 		err(1, "getifaddrs");
1052 
1053 	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
1054 		if (!(ifa->ifa_addr->sa_family == AF_INET ||
1055 		    ifa->ifa_addr->sa_family == AF_INET6 ||
1056 		    ifa->ifa_addr->sa_family == AF_LINK))
1057 				continue;
1058 		n = calloc(1, sizeof(struct node_host));
1059 		if (n == NULL)
1060 			err(1, "address: calloc");
1061 		n->af = ifa->ifa_addr->sa_family;
1062 		n->ifa_flags = ifa->ifa_flags;
1063 #ifdef __KAME__
1064 		if (n->af == AF_INET6 &&
1065 		    IN6_IS_ADDR_LINKLOCAL(&((struct sockaddr_in6 *)
1066 		    ifa->ifa_addr)->sin6_addr) &&
1067 		    ((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_scope_id ==
1068 		    0) {
1069 			struct sockaddr_in6	*sin6;
1070 
1071 			sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
1072 			sin6->sin6_scope_id = sin6->sin6_addr.s6_addr[2] << 8 |
1073 			    sin6->sin6_addr.s6_addr[3];
1074 			sin6->sin6_addr.s6_addr[2] = 0;
1075 			sin6->sin6_addr.s6_addr[3] = 0;
1076 		}
1077 #endif
1078 		n->ifindex = 0;
1079 		if (n->af == AF_INET) {
1080 			memcpy(&n->addr.v.a.addr, &((struct sockaddr_in *)
1081 			    ifa->ifa_addr)->sin_addr.s_addr,
1082 			    sizeof(struct in_addr));
1083 			memcpy(&n->addr.v.a.mask, &((struct sockaddr_in *)
1084 			    ifa->ifa_netmask)->sin_addr.s_addr,
1085 			    sizeof(struct in_addr));
1086 			if (ifa->ifa_broadaddr != NULL)
1087 				memcpy(&n->bcast, &((struct sockaddr_in *)
1088 				    ifa->ifa_broadaddr)->sin_addr.s_addr,
1089 				    sizeof(struct in_addr));
1090 			if (ifa->ifa_dstaddr != NULL)
1091 				memcpy(&n->peer, &((struct sockaddr_in *)
1092 				    ifa->ifa_dstaddr)->sin_addr.s_addr,
1093 				    sizeof(struct in_addr));
1094 		} else if (n->af == AF_INET6) {
1095 			memcpy(&n->addr.v.a.addr, &((struct sockaddr_in6 *)
1096 			    ifa->ifa_addr)->sin6_addr.s6_addr,
1097 			    sizeof(struct in6_addr));
1098 			memcpy(&n->addr.v.a.mask, &((struct sockaddr_in6 *)
1099 			    ifa->ifa_netmask)->sin6_addr.s6_addr,
1100 			    sizeof(struct in6_addr));
1101 			if (ifa->ifa_broadaddr != NULL)
1102 				memcpy(&n->bcast, &((struct sockaddr_in6 *)
1103 				    ifa->ifa_broadaddr)->sin6_addr.s6_addr,
1104 				    sizeof(struct in6_addr));
1105 			if (ifa->ifa_dstaddr != NULL)
1106 				 memcpy(&n->peer, &((struct sockaddr_in6 *)
1107 				    ifa->ifa_dstaddr)->sin6_addr.s6_addr,
1108 				    sizeof(struct in6_addr));
1109 			n->ifindex = ((struct sockaddr_in6 *)
1110 			    ifa->ifa_addr)->sin6_scope_id;
1111 		}
1112 		if ((n->ifname = strdup(ifa->ifa_name)) == NULL)
1113 			err(1, "ifa_load: strdup");
1114 		n->next = NULL;
1115 		n->tail = n;
1116 		if (h == NULL)
1117 			h = n;
1118 		else {
1119 			h->tail->next = n;
1120 			h->tail = n;
1121 		}
1122 	}
1123 
1124 	/* add interface groups, including clonable and dynamic stuff */
1125 	bzero(&b, sizeof(b));
1126 	b.pfrb_type = PFRB_IFACES;
1127 	for (;;) {
1128 		if (pfr_buf_grow(&b, b.pfrb_size))
1129 			err(1, "ifa_load: pfr_buf_grow");
1130 		b.pfrb_size = b.pfrb_msize;
1131 		if (pfi_get_ifaces(NULL, b.pfrb_caddr, &b.pfrb_size,
1132 		    PFI_FLAG_GROUP))
1133 			err(1, "ifa_load: pfi_get_ifaces");
1134 		if (b.pfrb_size <= b.pfrb_msize)
1135 			break;
1136 	}
1137 	PFRB_FOREACH(p, &b) {
1138 		n = calloc(1, sizeof(struct node_host));
1139 		if (n == NULL)
1140 			err(1, "address: calloc");
1141 		n->af = AF_LINK;
1142 		n->ifa_flags = PF_IFA_FLAG_GROUP;
1143 		if (p->pfif_flags & PFI_IFLAG_DYNAMIC)
1144 			n->ifa_flags |= PF_IFA_FLAG_DYNAMIC;
1145 		if (p->pfif_flags & PFI_IFLAG_CLONABLE)
1146 			n->ifa_flags |= PF_IFA_FLAG_CLONABLE;
1147 		if (!strcmp(p->pfif_name, "lo"))
1148 			n->ifa_flags |= IFF_LOOPBACK;
1149 		if ((n->ifname = strdup(p->pfif_name)) == NULL)
1150 			err(1, "ifa_load: strdup");
1151 		n->next = NULL;
1152 		n->tail = n;
1153 		if (h == NULL)
1154 			h = n;
1155 		else {
1156 			h->tail->next = n;
1157 			h->tail = n;
1158 		}
1159 	}
1160 
1161 	iftab = h;
1162 	freeifaddrs(ifap);
1163 }
1164 
1165 struct node_host *
1166 ifa_exists(const char *ifa_name, int group_ok)
1167 {
1168 	struct node_host	*n;
1169 	char			*p, buf[IFNAMSIZ];
1170 	int			 group;
1171 
1172 	group = !isdigit(ifa_name[strlen(ifa_name) - 1]);
1173 	if (group && !group_ok)
1174 		return (NULL);
1175 	if (iftab == NULL)
1176 		ifa_load();
1177 
1178 	for (n = iftab; n; n = n->next) {
1179 		if (n->af == AF_LINK && !strncmp(n->ifname, ifa_name, IFNAMSIZ))
1180 			return (n);
1181 	}
1182 	if (!group) {
1183 		/* look for clonable and/or dynamic interface */
1184 		strlcpy(buf, ifa_name, sizeof(buf));
1185 		for (p = buf + strlen(buf) - 1; p > buf && isdigit(*p); p--)
1186 			*p = '\0';
1187 		for (n = iftab; n != NULL; n = n->next)
1188 			if (n->af == AF_LINK &&
1189 			    !strncmp(n->ifname, buf, IFNAMSIZ))
1190 				break;
1191 		if (n != NULL && n->ifa_flags &
1192 		    (PF_IFA_FLAG_DYNAMIC | PF_IFA_FLAG_CLONABLE))
1193 			return (n);	/* XXX */
1194 	}
1195 	return (NULL);
1196 }
1197 
1198 struct node_host *
1199 ifa_lookup(const char *ifa_name, int flags)
1200 {
1201 	struct node_host	*p = NULL, *h = NULL, *n = NULL;
1202 	int			 got4 = 0, got6 = 0;
1203 	const char		 *last_if = NULL;
1204 
1205 	if (!strncmp(ifa_name, "self", IFNAMSIZ))
1206 		ifa_name = NULL;
1207 
1208 	if (iftab == NULL)
1209 		ifa_load();
1210 
1211 	for (p = iftab; p; p = p->next) {
1212 		if (ifa_skip_if(ifa_name, p))
1213 			continue;
1214 		if ((flags & PFI_AFLAG_BROADCAST) && p->af != AF_INET)
1215 			continue;
1216 		if ((flags & PFI_AFLAG_BROADCAST) &&
1217 		    !(p->ifa_flags & IFF_BROADCAST))
1218 			continue;
1219 		if ((flags & PFI_AFLAG_PEER) &&
1220 		    !(p->ifa_flags & IFF_POINTOPOINT))
1221 			continue;
1222 		if ((flags & PFI_AFLAG_NETWORK) && p->ifindex > 0)
1223 			continue;
1224 		if (last_if == NULL || strcmp(last_if, p->ifname))
1225 			got4 = got6 = 0;
1226 		last_if = p->ifname;
1227 		if ((flags & PFI_AFLAG_NOALIAS) && p->af == AF_INET && got4)
1228 			continue;
1229 		if ((flags & PFI_AFLAG_NOALIAS) && p->af == AF_INET6 && got6)
1230 			continue;
1231 		if (p->af == AF_INET)
1232 			got4 = 1;
1233 		else
1234 			got6 = 1;
1235 		n = calloc(1, sizeof(struct node_host));
1236 		if (n == NULL)
1237 			err(1, "address: calloc");
1238 		n->af = p->af;
1239 		if (flags & PFI_AFLAG_BROADCAST)
1240 			memcpy(&n->addr.v.a.addr, &p->bcast,
1241 			    sizeof(struct pf_addr));
1242 		else if (flags & PFI_AFLAG_PEER)
1243 			memcpy(&n->addr.v.a.addr, &p->peer,
1244 			    sizeof(struct pf_addr));
1245 		else
1246 			memcpy(&n->addr.v.a.addr, &p->addr.v.a.addr,
1247 			    sizeof(struct pf_addr));
1248 		if (flags & PFI_AFLAG_NETWORK)
1249 			set_ipmask(n, unmask(&p->addr.v.a.mask, n->af));
1250 		else {
1251 			if (n->af == AF_INET) {
1252 				if (p->ifa_flags & IFF_LOOPBACK &&
1253 				    p->ifa_flags & IFF_LINK1)
1254 					memcpy(&n->addr.v.a.mask,
1255 					    &p->addr.v.a.mask,
1256 					    sizeof(struct pf_addr));
1257 				else
1258 					set_ipmask(n, 32);
1259 			} else
1260 				set_ipmask(n, 128);
1261 		}
1262 		n->ifindex = p->ifindex;
1263 
1264 		n->next = NULL;
1265 		n->tail = n;
1266 		if (h == NULL)
1267 			h = n;
1268 		else {
1269 			h->tail->next = n;
1270 			h->tail = n;
1271 		}
1272 	}
1273 	return (h);
1274 }
1275 
1276 int
1277 ifa_skip_if(const char *filter, struct node_host *p)
1278 {
1279 	int	n;
1280 
1281 	if (p->af != AF_INET && p->af != AF_INET6)
1282 		return (1);
1283 	if (filter == NULL || !*filter)
1284 		return (0);
1285 	if (!strcmp(p->ifname, filter))
1286 		return (0);	/* exact match */
1287 	n = strlen(filter);
1288 	if (n < 1 || n >= IFNAMSIZ)
1289 		return (1);	/* sanity check */
1290 	if (filter[n-1] >= '0' && filter[n-1] <= '9')
1291 		return (1);	/* only do exact match in that case */
1292 	if (strncmp(p->ifname, filter, n))
1293 		return (1);	/* prefix doesn't match */
1294 	return (p->ifname[n] < '0' || p->ifname[n] > '9');
1295 }
1296 
1297 
1298 struct node_host *
1299 host(const char *s)
1300 {
1301 	struct node_host	*h = NULL;
1302 	int			 mask, v4mask, v6mask, cont = 1;
1303 	char			*p, *q, *ps;
1304 
1305 	if ((p = strrchr(s, '/')) != NULL) {
1306 		mask = strtol(p+1, &q, 0);
1307 		if (!q || *q || mask > 128 || q == (p+1)) {
1308 			fprintf(stderr, "invalid netmask\n");
1309 			return (NULL);
1310 		}
1311 		if ((ps = malloc(strlen(s) - strlen(p) + 1)) == NULL)
1312 			err(1, "host: malloc");
1313 		strlcpy(ps, s, strlen(s) - strlen(p) + 1);
1314 		v4mask = v6mask = mask;
1315 	} else {
1316 		if ((ps = strdup(s)) == NULL)
1317 			err(1, "host: strdup");
1318 		v4mask = 32;
1319 		v6mask = 128;
1320 		mask = -1;
1321 	}
1322 
1323 	/* interface with this name exists? */
1324 	if (cont && (h = host_if(ps, mask)) != NULL)
1325 		cont = 0;
1326 
1327 	/* IPv4 address? */
1328 	if (cont && (h = host_v4(s, mask)) != NULL)
1329 		cont = 0;
1330 
1331 	/* IPv6 address? */
1332 	if (cont && (h = host_v6(ps, v6mask)) != NULL)
1333 		cont = 0;
1334 
1335 	/* dns lookup */
1336 	if (cont && (h = host_dns(ps, v4mask, v6mask)) != NULL)
1337 		cont = 0;
1338 	free(ps);
1339 
1340 	if (h == NULL || cont == 1) {
1341 		fprintf(stderr, "no IP address found for %s\n", s);
1342 		return (NULL);
1343 	}
1344 	return (h);
1345 }
1346 
1347 struct node_host *
1348 host_if(const char *s, int mask)
1349 {
1350 	struct node_host	*n, *h = NULL;
1351 	char			*p, *ps;
1352 	int			 flags = 0;
1353 
1354 	if ((ps = strdup(s)) == NULL)
1355 		err(1, "host_if: strdup");
1356 	while ((p = strrchr(ps, ':')) != NULL) {
1357 		if (!strcmp(p+1, "network"))
1358 			flags |= PFI_AFLAG_NETWORK;
1359 		else if (!strcmp(p+1, "broadcast"))
1360 			flags |= PFI_AFLAG_BROADCAST;
1361 		else if (!strcmp(p+1, "peer"))
1362 			flags |= PFI_AFLAG_PEER;
1363 		else if (!strcmp(p+1, "0"))
1364 			flags |= PFI_AFLAG_NOALIAS;
1365 		else {
1366 			free(ps);
1367 			return (NULL);
1368 		}
1369 		*p = '\0';
1370 	}
1371 	if (flags & (flags - 1) & PFI_AFLAG_MODEMASK) { /* Yep! */
1372 		fprintf(stderr, "illegal combination of interface modifiers\n");
1373 		free(ps);
1374 		return (NULL);
1375 	}
1376 	if ((flags & (PFI_AFLAG_NETWORK|PFI_AFLAG_BROADCAST)) && mask > -1) {
1377 		fprintf(stderr, "network or broadcast lookup, but "
1378 		    "extra netmask given\n");
1379 		free(ps);
1380 		return (NULL);
1381 	}
1382 	if (ifa_exists(ps, 1) || !strncmp(ps, "self", IFNAMSIZ)) {
1383 		/* interface with this name exists */
1384 		h = ifa_lookup(ps, flags);
1385 		for (n = h; n != NULL && mask > -1; n = n->next)
1386 			set_ipmask(n, mask);
1387 	}
1388 
1389 	free(ps);
1390 	return (h);
1391 }
1392 
1393 struct node_host *
1394 host_v4(const char *s, int mask)
1395 {
1396 	struct node_host	*h = NULL;
1397 	struct in_addr		 ina;
1398 	int			 bits = 32;
1399 
1400 	memset(&ina, 0, sizeof(struct in_addr));
1401 	if (strrchr(s, '/') != NULL) {
1402 		if ((bits = inet_net_pton(AF_INET, s, &ina, sizeof(ina))) == -1)
1403 			return (NULL);
1404 	} else {
1405 		if (inet_pton(AF_INET, s, &ina) != 1)
1406 			return (NULL);
1407 	}
1408 
1409 	h = calloc(1, sizeof(struct node_host));
1410 	if (h == NULL)
1411 		err(1, "address: calloc");
1412 	h->ifname = NULL;
1413 	h->af = AF_INET;
1414 	h->addr.v.a.addr.addr32[0] = ina.s_addr;
1415 	set_ipmask(h, bits);
1416 	h->next = NULL;
1417 	h->tail = h;
1418 
1419 	return (h);
1420 }
1421 
1422 struct node_host *
1423 host_v6(const char *s, int mask)
1424 {
1425 	struct addrinfo		 hints, *res;
1426 	struct node_host	*h = NULL;
1427 
1428 	memset(&hints, 0, sizeof(hints));
1429 	hints.ai_family = AF_INET6;
1430 	hints.ai_socktype = SOCK_DGRAM; /*dummy*/
1431 	hints.ai_flags = AI_NUMERICHOST;
1432 	if (getaddrinfo(s, "0", &hints, &res) == 0) {
1433 		h = calloc(1, sizeof(struct node_host));
1434 		if (h == NULL)
1435 			err(1, "address: calloc");
1436 		h->ifname = NULL;
1437 		h->af = AF_INET6;
1438 		memcpy(&h->addr.v.a.addr,
1439 		    &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr,
1440 		    sizeof(h->addr.v.a.addr));
1441 		h->ifindex =
1442 		    ((struct sockaddr_in6 *)res->ai_addr)->sin6_scope_id;
1443 		set_ipmask(h, mask);
1444 		freeaddrinfo(res);
1445 		h->next = NULL;
1446 		h->tail = h;
1447 	}
1448 
1449 	return (h);
1450 }
1451 
1452 struct node_host *
1453 host_dns(const char *s, int v4mask, int v6mask)
1454 {
1455 	struct addrinfo		 hints, *res0, *res;
1456 	struct node_host	*n, *h = NULL;
1457 	int			 error, noalias = 0;
1458 	int			 got4 = 0, got6 = 0;
1459 	char			*p, *ps;
1460 
1461 	if ((ps = strdup(s)) == NULL)
1462 		err(1, "host_if: strdup");
1463 	if ((p = strrchr(ps, ':')) != NULL && !strcmp(p, ":0")) {
1464 		noalias = 1;
1465 		*p = '\0';
1466 	}
1467 	memset(&hints, 0, sizeof(hints));
1468 	hints.ai_family = PF_UNSPEC;
1469 	hints.ai_socktype = SOCK_STREAM; /* DUMMY */
1470 	error = getaddrinfo(ps, NULL, &hints, &res0);
1471 	if (error)
1472 		return (h);
1473 
1474 	for (res = res0; res; res = res->ai_next) {
1475 		if (res->ai_family != AF_INET &&
1476 		    res->ai_family != AF_INET6)
1477 			continue;
1478 		if (noalias) {
1479 			if (res->ai_family == AF_INET) {
1480 				if (got4)
1481 					continue;
1482 				got4 = 1;
1483 			} else {
1484 				if (got6)
1485 					continue;
1486 				got6 = 1;
1487 			}
1488 		}
1489 		n = calloc(1, sizeof(struct node_host));
1490 		if (n == NULL)
1491 			err(1, "host_dns: calloc");
1492 		n->ifname = NULL;
1493 		n->af = res->ai_family;
1494 		if (res->ai_family == AF_INET) {
1495 			memcpy(&n->addr.v.a.addr,
1496 			    &((struct sockaddr_in *)
1497 			    res->ai_addr)->sin_addr.s_addr,
1498 			    sizeof(struct in_addr));
1499 			set_ipmask(n, v4mask);
1500 		} else {
1501 			memcpy(&n->addr.v.a.addr,
1502 			    &((struct sockaddr_in6 *)
1503 			    res->ai_addr)->sin6_addr.s6_addr,
1504 			    sizeof(struct in6_addr));
1505 			n->ifindex =
1506 			    ((struct sockaddr_in6 *)
1507 			    res->ai_addr)->sin6_scope_id;
1508 			set_ipmask(n, v6mask);
1509 		}
1510 		n->next = NULL;
1511 		n->tail = n;
1512 		if (h == NULL)
1513 			h = n;
1514 		else {
1515 			h->tail->next = n;
1516 			h->tail = n;
1517 		}
1518 	}
1519 	freeaddrinfo(res0);
1520 	free(ps);
1521 
1522 	return (h);
1523 }
1524 
1525 /*
1526  * convert a hostname to a list of addresses and put them in the given buffer.
1527  * test:
1528  *	if set to 1, only simple addresses are accepted (no netblock, no "!").
1529  */
1530 int
1531 append_addr(struct pfr_buffer *b, char *s, int test)
1532 {
1533 	char			 *r;
1534 	struct node_host	*h, *n;
1535 	int			 rv, not = 0;
1536 
1537 	for (r = s; *r == '!'; r++)
1538 		not = !not;
1539 	if ((n = host(r)) == NULL) {
1540 		errno = 0;
1541 		return (-1);
1542 	}
1543 	rv = append_addr_host(b, n, test, not);
1544 	do {
1545 		h = n;
1546 		n = n->next;
1547 		free(h);
1548 	} while (n != NULL);
1549 	return (rv);
1550 }
1551 
1552 /*
1553  * same as previous function, but with a pre-parsed input and the ability
1554  * to "negate" the result. Does not free the node_host list.
1555  * not:
1556  *      setting it to 1 is equivalent to adding "!" in front of parameter s.
1557  */
1558 int
1559 append_addr_host(struct pfr_buffer *b, struct node_host *n, int test, int not)
1560 {
1561 	int			 bits;
1562 	struct pfr_addr		 addr;
1563 
1564 	do {
1565 		bzero(&addr, sizeof(addr));
1566 		addr.pfra_not = n->not ^ not;
1567 		addr.pfra_af = n->af;
1568 		addr.pfra_net = unmask(&n->addr.v.a.mask, n->af);
1569 		switch (n->af) {
1570 		case AF_INET:
1571 			addr.pfra_ip4addr.s_addr = n->addr.v.a.addr.addr32[0];
1572 			bits = 32;
1573 			break;
1574 		case AF_INET6:
1575 			memcpy(&addr.pfra_ip6addr, &n->addr.v.a.addr.v6,
1576 			    sizeof(struct in6_addr));
1577 			bits = 128;
1578 			break;
1579 		default:
1580 			errno = EINVAL;
1581 			return (-1);
1582 		}
1583 		if ((test && (not || addr.pfra_net != bits)) ||
1584 		    addr.pfra_net > bits) {
1585 			errno = EINVAL;
1586 			return (-1);
1587 		}
1588 		if (pfr_buf_add(b, &addr))
1589 			return (-1);
1590 	} while ((n = n->next) != NULL);
1591 
1592 	return (0);
1593 }
1594 
1595 int
1596 pfctl_add_trans(struct pfr_buffer *buf, int rs_num, const char *anchor,
1597     const char *ruleset)
1598 {
1599 	struct pfioc_trans_e trans;
1600 
1601 	bzero(&trans, sizeof(trans));
1602 	trans.rs_num = rs_num;
1603 	if (strlcpy(trans.anchor, anchor,
1604 	    sizeof(trans.anchor)) >= sizeof(trans.anchor) ||
1605 	    strlcpy(trans.ruleset, ruleset,
1606 	    sizeof(trans.ruleset)) >= sizeof(trans.ruleset))
1607 		errx(1, "pfctl_add_trans: strlcpy");
1608 
1609 	return pfr_buf_add(buf, &trans);
1610 }
1611 
1612 u_int32_t
1613 pfctl_get_ticket(struct pfr_buffer *buf, int rs_num, const char *anchor,
1614     const char *ruleset)
1615 {
1616 	struct pfioc_trans_e *p;
1617 
1618 	PFRB_FOREACH(p, buf)
1619 		if (rs_num == p->rs_num && !strcmp(anchor, p->anchor) &&
1620 		    !strcmp(ruleset, p->ruleset))
1621 			return (p->ticket);
1622 	errx(1, "pfr_get_ticket: assertion failed");
1623 }
1624 
1625 int
1626 pfctl_trans(int dev, struct pfr_buffer *buf, u_long cmd, int from)
1627 {
1628 	struct pfioc_trans trans;
1629 
1630 	bzero(&trans, sizeof(trans));
1631 	trans.size = buf->pfrb_size - from;
1632 	trans.esize = sizeof(struct pfioc_trans_e);
1633 	trans.array = ((struct pfioc_trans_e *)buf->pfrb_caddr) + from;
1634 	return ioctl(dev, cmd, &trans);
1635 }
1636