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