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