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