Home | History | Annotate | Line # | Download | only in dns
rpz.c revision 1.3
      1 /*	$NetBSD: rpz.c,v 1.3 2019/01/09 16:55:12 christos Exp $	*/
      2 
      3 /*
      4  * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
      5  *
      6  * This Source Code Form is subject to the terms of the Mozilla Public
      7  * License, v. 2.0. If a copy of the MPL was not distributed with this
      8  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
      9  *
     10  * See the COPYRIGHT file distributed with this work for additional
     11  * information regarding copyright ownership.
     12  */
     13 
     14 /*! \file */
     15 
     16 #include <config.h>
     17 
     18 #include <inttypes.h>
     19 #include <stdbool.h>
     20 #include <stdlib.h>
     21 
     22 #include <isc/buffer.h>
     23 #include <isc/mem.h>
     24 #include <isc/net.h>
     25 #include <isc/netaddr.h>
     26 #include <isc/print.h>
     27 #include <isc/rwlock.h>
     28 #include <isc/string.h>
     29 #include <isc/task.h>
     30 #include <isc/util.h>
     31 
     32 #include <dns/db.h>
     33 #include <dns/dbiterator.h>
     34 #include <dns/dnsrps.h>
     35 #include <dns/events.h>
     36 #include <dns/fixedname.h>
     37 #include <dns/log.h>
     38 #include <dns/rdata.h>
     39 #include <dns/rdataset.h>
     40 #include <dns/rdatastruct.h>
     41 #include <dns/rdatasetiter.h>
     42 #include <dns/result.h>
     43 #include <dns/rbt.h>
     44 #include <dns/rpz.h>
     45 #include <dns/view.h>
     46 
     47 
     48 /*
     49  * Parallel radix trees for databases of response policy IP addresses
     50  *
     51  * The radix or patricia trees are somewhat specialized to handle response
     52  * policy addresses by representing the two sets of IP addresses and name
     53  * server IP addresses in a single tree.  One set of IP addresses is
     54  * for rpz-ip policies or policies triggered by addresses in A or
     55  * AAAA records in responses.
     56  * The second set is for rpz-nsip policies or policies triggered by addresses
     57  * in A or AAAA records for NS records that are authorities for responses.
     58  *
     59  * Each leaf indicates that an IP address is listed in the IP address or the
     60  * name server IP address policy sub-zone (or both) of the corresponding
     61  * response policy zone.  The policy data such as a CNAME or an A record
     62  * is kept in the policy zone.  After an IP address has been found in a radix
     63  * tree, the node in the policy zone's database is found by converting
     64  * the IP address to a domain name in a canonical form.
     65  *
     66  *
     67  * The response policy zone canonical form of an IPv6 address is one of:
     68  *	prefix.W.W.W.W.W.W.W.W
     69  *	prefix.WORDS.zz
     70  *	prefix.WORDS.zz.WORDS
     71  *	prefix.zz.WORDS
     72  *  where
     73  *	prefix	is the prefix length of the IPv6 address between 1 and 128
     74  *	W	is a number between 0 and 65535
     75  *	WORDS	is one or more numbers W separated with "."
     76  *	zz	corresponds to :: in the standard IPv6 text representation
     77  *
     78  * The canonical form of IPv4 addresses is:
     79  *	prefix.B.B.B.B
     80  *  where
     81  *	prefix	is the prefix length of the address between 1 and 32
     82  *	B	is a number between 0 and 255
     83  *
     84  * Names for IPv4 addresses are distinguished from IPv6 addresses by having
     85  * 5 labels all of which are numbers, and a prefix between 1 and 32.
     86  */
     87 
     88 /*
     89  * Nodes hashtable calculation parameters
     90  */
     91 #define DNS_RPZ_HTSIZE_MAX	24
     92 #define DNS_RPZ_HTSIZE_DIV	3
     93 
     94 /*
     95  * Maximum number of nodes to process per quantum
     96  */
     97 #define DNS_RPZ_QUANTUM 1024
     98 
     99 static void
    100 dns_rpz_update_from_db(dns_rpz_zone_t *rpz);
    101 
    102 static void
    103 dns_rpz_update_taskaction(isc_task_t *task, isc_event_t *event);
    104 
    105 /*
    106  * Use a private definition of IPv6 addresses because s6_addr32 is not
    107  * always defined and our IPv6 addresses are in non-standard byte order
    108  */
    109 typedef uint32_t		dns_rpz_cidr_word_t;
    110 #define DNS_RPZ_CIDR_WORD_BITS	((int)sizeof(dns_rpz_cidr_word_t)*8)
    111 #define DNS_RPZ_CIDR_KEY_BITS	((int)sizeof(dns_rpz_cidr_key_t)*8)
    112 #define DNS_RPZ_CIDR_WORDS	(128/DNS_RPZ_CIDR_WORD_BITS)
    113 typedef struct {
    114 	dns_rpz_cidr_word_t	w[DNS_RPZ_CIDR_WORDS];
    115 } dns_rpz_cidr_key_t;
    116 
    117 #define ADDR_V4MAPPED		0xffff
    118 #define KEY_IS_IPV4(prefix,ip) ((prefix) >= 96 && (ip)->w[0] == 0 &&	\
    119 				(ip)->w[1] == 0 && (ip)->w[2] == ADDR_V4MAPPED)
    120 
    121 #define DNS_RPZ_WORD_MASK(b) ((b) == 0 ? (dns_rpz_cidr_word_t)(-1)	\
    122 			      : ((dns_rpz_cidr_word_t)(-1)		\
    123 				 << (DNS_RPZ_CIDR_WORD_BITS - (b))))
    124 
    125 /*
    126  * Get bit #n from the array of words of an IP address.
    127  */
    128 #define DNS_RPZ_IP_BIT(ip, n) (1 & ((ip)->w[(n)/DNS_RPZ_CIDR_WORD_BITS] >>  \
    129 				    (DNS_RPZ_CIDR_WORD_BITS		    \
    130 				     - 1 - ((n) % DNS_RPZ_CIDR_WORD_BITS))))
    131 
    132 /*
    133  * A triplet of arrays of bits flagging the existence of
    134  * client-IP, IP, and NSIP policy triggers.
    135  */
    136 typedef struct dns_rpz_addr_zbits dns_rpz_addr_zbits_t;
    137 struct dns_rpz_addr_zbits {
    138 	dns_rpz_zbits_t		client_ip;
    139 	dns_rpz_zbits_t		ip;
    140 	dns_rpz_zbits_t		nsip;
    141 };
    142 
    143 /*
    144  * A CIDR or radix tree node.
    145  */
    146 struct dns_rpz_cidr_node {
    147 	dns_rpz_cidr_node_t	*parent;
    148 	dns_rpz_cidr_node_t	*child[2];
    149 	dns_rpz_cidr_key_t	ip;
    150 	dns_rpz_prefix_t	prefix;
    151 	dns_rpz_addr_zbits_t	set;
    152 	dns_rpz_addr_zbits_t	sum;
    153 };
    154 
    155 /*
    156  * A pair of arrays of bits flagging the existence of
    157  * QNAME and NSDNAME policy triggers.
    158  */
    159 typedef struct dns_rpz_nm_zbits dns_rpz_nm_zbits_t;
    160 struct dns_rpz_nm_zbits {
    161 	dns_rpz_zbits_t		qname;
    162 	dns_rpz_zbits_t		ns;
    163 };
    164 
    165 /*
    166  * The data in a RBT node has two pairs of bits for policy zones.
    167  * One pair is for the corresponding name of the node such as example.com
    168  * and the other pair is for a wildcard child such as *.example.com.
    169  */
    170 typedef struct dns_rpz_nm_data dns_rpz_nm_data_t;
    171 struct dns_rpz_nm_data {
    172 	dns_rpz_nm_zbits_t	set;
    173 	dns_rpz_nm_zbits_t	wild;
    174 };
    175 
    176 #if 0
    177 /*
    178  * Catch a name while debugging.
    179  */
    180 static void
    181 catch_name(const dns_name_t *src_name, const char *tgt, const char *str) {
    182 	dns_fixedname_t tgt_namef;
    183 	dns_name_t *tgt_name;
    184 
    185 	tgt_name = dns_fixedname_initname(&tgt_namef);
    186 	dns_name_fromstring(tgt_name, tgt, DNS_NAME_DOWNCASE, NULL);
    187 	if (dns_name_equal(src_name, tgt_name)) {
    188 		isc_log_write(dns_lctx, DNS_LOGCATEGORY_RPZ,
    189 			      DNS_LOGMODULE_RBTDB, DNS_RPZ_ERROR_LEVEL,
    190 			      "rpz hit failed: %s %s", str, tgt);
    191 	}
    192 }
    193 #endif
    194 
    195 const char *
    196 dns_rpz_type2str(dns_rpz_type_t type) {
    197 	switch (type) {
    198 	case DNS_RPZ_TYPE_CLIENT_IP:
    199 		return ("CLIENT-IP");
    200 	case DNS_RPZ_TYPE_QNAME:
    201 		return ("QNAME");
    202 	case DNS_RPZ_TYPE_IP:
    203 		return ("IP");
    204 	case DNS_RPZ_TYPE_NSIP:
    205 		return ("NSIP");
    206 	case DNS_RPZ_TYPE_NSDNAME:
    207 		return ("NSDNAME");
    208 	case DNS_RPZ_TYPE_BAD:
    209 		break;
    210 	}
    211 	FATAL_ERROR(__FILE__, __LINE__, "impossible rpz type %d", type);
    212 	return ("impossible");
    213 }
    214 
    215 dns_rpz_policy_t
    216 dns_rpz_str2policy(const char *str) {
    217 	static struct {
    218 		const char *str;
    219 		dns_rpz_policy_t policy;
    220 	} tbl[] = {
    221 		{"given",	DNS_RPZ_POLICY_GIVEN},
    222 		{"disabled",	DNS_RPZ_POLICY_DISABLED},
    223 		{"passthru",	DNS_RPZ_POLICY_PASSTHRU},
    224 		{"drop",	DNS_RPZ_POLICY_DROP},
    225 		{"tcp-only",	DNS_RPZ_POLICY_TCP_ONLY},
    226 		{"nxdomain",	DNS_RPZ_POLICY_NXDOMAIN},
    227 		{"nodata",	DNS_RPZ_POLICY_NODATA},
    228 		{"cname",	DNS_RPZ_POLICY_CNAME},
    229 		{"no-op",	DNS_RPZ_POLICY_PASSTHRU},   /* old passthru */
    230 	};
    231 	unsigned int n;
    232 
    233 	if (str == NULL)
    234 		return (DNS_RPZ_POLICY_ERROR);
    235 	for (n = 0; n < sizeof(tbl)/sizeof(tbl[0]); ++n) {
    236 		if (!strcasecmp(tbl[n].str, str))
    237 			return (tbl[n].policy);
    238 	}
    239 	return (DNS_RPZ_POLICY_ERROR);
    240 }
    241 
    242 const char *
    243 dns_rpz_policy2str(dns_rpz_policy_t policy) {
    244 	const char *str;
    245 
    246 	switch (policy) {
    247 	case DNS_RPZ_POLICY_PASSTHRU:
    248 		str = "PASSTHRU";
    249 		break;
    250 	case DNS_RPZ_POLICY_DROP:
    251 		str = "DROP";
    252 		break;
    253 	case DNS_RPZ_POLICY_TCP_ONLY:
    254 		str = "TCP-ONLY";
    255 		break;
    256 	case DNS_RPZ_POLICY_NXDOMAIN:
    257 		str = "NXDOMAIN";
    258 		break;
    259 	case DNS_RPZ_POLICY_NODATA:
    260 		str = "NODATA";
    261 		break;
    262 	case DNS_RPZ_POLICY_RECORD:
    263 		str = "Local-Data";
    264 		break;
    265 	case DNS_RPZ_POLICY_CNAME:
    266 	case DNS_RPZ_POLICY_WILDCNAME:
    267 		str = "CNAME";
    268 		break;
    269 	case DNS_RPZ_POLICY_MISS:
    270 		str = "MISS";
    271 		break;
    272 	default:
    273 		INSIST(0);
    274 		ISC_UNREACHABLE();
    275 	}
    276 	return (str);
    277 }
    278 
    279 /*
    280  * Return the bit number of the highest set bit in 'zbit'.
    281  * (for example, 0x01 returns 0, 0xFF returns 7, etc.)
    282  */
    283 static int
    284 zbit_to_num(dns_rpz_zbits_t zbit) {
    285 	dns_rpz_num_t rpz_num;
    286 
    287 	REQUIRE(zbit != 0);
    288 	rpz_num = 0;
    289 	if ((zbit & 0xffffffff00000000ULL) != 0) {
    290 		zbit >>= 32;
    291 		rpz_num += 32;
    292 	}
    293 	if ((zbit & 0xffff0000) != 0) {
    294 		zbit >>= 16;
    295 		rpz_num += 16;
    296 	}
    297 	if ((zbit & 0xff00) != 0) {
    298 		zbit >>= 8;
    299 		rpz_num += 8;
    300 	}
    301 	if ((zbit & 0xf0) != 0) {
    302 		zbit >>= 4;
    303 		rpz_num += 4;
    304 	}
    305 	if ((zbit & 0xc) != 0) {
    306 		zbit >>= 2;
    307 		rpz_num += 2;
    308 	}
    309 	if ((zbit & 2) != 0)
    310 		++rpz_num;
    311 	return (rpz_num);
    312 }
    313 
    314 /*
    315  * Make a set of bit masks given one or more bits and their type.
    316  */
    317 static void
    318 make_addr_set(dns_rpz_addr_zbits_t *tgt_set, dns_rpz_zbits_t zbits,
    319 	      dns_rpz_type_t type)
    320 {
    321 	switch (type) {
    322 	case DNS_RPZ_TYPE_CLIENT_IP:
    323 		tgt_set->client_ip = zbits;
    324 		tgt_set->ip = 0;
    325 		tgt_set->nsip = 0;
    326 		break;
    327 	case DNS_RPZ_TYPE_IP:
    328 		tgt_set->client_ip = 0;
    329 		tgt_set->ip = zbits;
    330 		tgt_set->nsip = 0;
    331 		break;
    332 	case DNS_RPZ_TYPE_NSIP:
    333 		tgt_set->client_ip = 0;
    334 		tgt_set->ip = 0;
    335 		tgt_set->nsip = zbits;
    336 		break;
    337 	default:
    338 		INSIST(0);
    339 		ISC_UNREACHABLE();
    340 	}
    341 }
    342 
    343 static void
    344 make_nm_set(dns_rpz_nm_zbits_t *tgt_set,
    345 	    dns_rpz_num_t rpz_num, dns_rpz_type_t type)
    346 {
    347 	switch (type) {
    348 	case DNS_RPZ_TYPE_QNAME:
    349 		tgt_set->qname = DNS_RPZ_ZBIT(rpz_num);
    350 		tgt_set->ns = 0;
    351 		break;
    352 	case DNS_RPZ_TYPE_NSDNAME:
    353 		tgt_set->qname = 0;
    354 		tgt_set->ns = DNS_RPZ_ZBIT(rpz_num);
    355 		break;
    356 	default:
    357 		INSIST(0);
    358 		ISC_UNREACHABLE();
    359 	}
    360 }
    361 
    362 /*
    363  * Mark a node and all of its parents as having client-IP, IP, or NSIP data
    364  */
    365 static void
    366 set_sum_pair(dns_rpz_cidr_node_t *cnode) {
    367 	dns_rpz_cidr_node_t *child;
    368 	dns_rpz_addr_zbits_t sum;
    369 
    370 	do {
    371 		sum = cnode->set;
    372 
    373 		child = cnode->child[0];
    374 		if (child != NULL) {
    375 			sum.client_ip |= child->sum.client_ip;
    376 			sum.ip |= child->sum.ip;
    377 			sum.nsip |= child->sum.nsip;
    378 		}
    379 
    380 		child = cnode->child[1];
    381 		if (child != NULL) {
    382 			sum.client_ip |= child->sum.client_ip;
    383 			sum.ip |= child->sum.ip;
    384 			sum.nsip |= child->sum.nsip;
    385 		}
    386 
    387 		if (cnode->sum.client_ip == sum.client_ip &&
    388 		    cnode->sum.ip == sum.ip &&
    389 		    cnode->sum.nsip == sum.nsip)
    390 			break;
    391 		cnode->sum = sum;
    392 		cnode = cnode->parent;
    393 	} while (cnode != NULL);
    394 }
    395 
    396 /* Caller must hold rpzs->maint_lock */
    397 static void
    398 fix_qname_skip_recurse(dns_rpz_zones_t *rpzs) {
    399 	dns_rpz_zbits_t mask;
    400 
    401 	/*
    402 	 * qname_wait_recurse and qname_skip_recurse are used to
    403 	 * implement the "qname-wait-recurse" config option.
    404 	 *
    405 	 * When "qname-wait-recurse" is yes, no processing happens without
    406 	 * recursion. In this case, qname_wait_recurse is true, and
    407 	 * qname_skip_recurse (a bit field indicating which policy zones
    408 	 * can be processed without recursion) is set to all 0's by
    409 	 * fix_qname_skip_recurse().
    410 	 *
    411 	 * When "qname-wait-recurse" is no, qname_skip_recurse may be
    412 	 * set to a non-zero value by fix_qname_skip_recurse(). The mask
    413 	 * has to have bits set for the policy zones for which
    414 	 * processing may continue without recursion, and bits cleared
    415 	 * for the rest.
    416 	 *
    417 	 * (1) The ARM says:
    418 	 *
    419 	 *   The "qname-wait-recurse no" option overrides that default
    420 	 *   behavior when recursion cannot change a non-error
    421 	 *   response. The option does not affect QNAME or client-IP
    422 	 *   triggers in policy zones listed after other zones
    423 	 *   containing IP, NSIP and NSDNAME triggers, because those may
    424 	 *   depend on the A, AAAA, and NS records that would be found
    425 	 *   during recursive resolution.
    426 	 *
    427 	 * Let's consider the following:
    428 	 *
    429 	 *     zbits_req = (rpzs->have.ipv4 | rpzs->have.ipv6 |
    430 	 *		    rpzs->have.nsdname |
    431 	 *		    rpzs->have.nsipv4 | rpzs->have.nsipv6);
    432 	 *
    433 	 * zbits_req now contains bits set for zones which require
    434 	 * recursion.
    435 	 *
    436 	 * But going by the description in the ARM, if the first policy
    437 	 * zone requires recursion, then all zones after that (higher
    438 	 * order bits) have to wait as well.  If the Nth zone requires
    439 	 * recursion, then (N+1)th zone onwards all need to wait.
    440 	 *
    441 	 * So mapping this, examples:
    442 	 *
    443 	 * zbits_req = 0b000  mask = 0xffffffff (no zones have to wait for
    444 	 *					 recursion)
    445 	 * zbits_req = 0b001  mask = 0x00000000 (all zones have to wait)
    446 	 * zbits_req = 0b010  mask = 0x00000001 (the first zone doesn't have to
    447 	 *					 wait, second zone onwards need
    448 	 *					 to wait)
    449 	 * zbits_req = 0b011  mask = 0x00000000 (all zones have to wait)
    450 	 * zbits_req = 0b100  mask = 0x00000011 (the 1st and 2nd zones don't
    451 	 *					 have to wait, third zone
    452 	 *					 onwards need to wait)
    453 	 *
    454 	 * More generally, we have to count the number of trailing 0
    455 	 * bits in zbits_req and only these can be processed without
    456 	 * recursion. All the rest need to wait.
    457 	 *
    458 	 * (2) The ARM says that "qname-wait-recurse no" option
    459 	 * overrides the default behavior when recursion cannot change a
    460 	 * non-error response. So, in the order of listing of policy
    461 	 * zones, within the first policy zone where recursion may be
    462 	 * required, we should first allow CLIENT-IP and QNAME policy
    463 	 * records to be attempted without recursion.
    464 	 */
    465 
    466 	/*
    467 	 * Get a mask covering all policy zones that are not subordinate to
    468 	 * other policy zones containing triggers that require that the
    469 	 * qname be resolved before they can be checked.
    470 	 */
    471 	rpzs->have.client_ip = rpzs->have.client_ipv4 | rpzs->have.client_ipv6;
    472 	rpzs->have.ip = rpzs->have.ipv4 | rpzs->have.ipv6;
    473 	rpzs->have.nsip = rpzs->have.nsipv4 | rpzs->have.nsipv6;
    474 
    475 	if (rpzs->p.qname_wait_recurse) {
    476 		mask = 0;
    477 	} else {
    478 		dns_rpz_zbits_t zbits_req;
    479 		dns_rpz_zbits_t zbits_notreq;
    480 		dns_rpz_zbits_t mask2;
    481 		dns_rpz_zbits_t req_mask;
    482 
    483 		/*
    484 		 * Get the masks of zones with policies that
    485 		 * do/don't require recursion
    486 		 */
    487 
    488 		zbits_req = (rpzs->have.ipv4 | rpzs->have.ipv6 |
    489 			     rpzs->have.nsdname |
    490 			     rpzs->have.nsipv4 | rpzs->have.nsipv6);
    491 		zbits_notreq = (rpzs->have.client_ip | rpzs->have.qname);
    492 
    493 		if (zbits_req == 0) {
    494 			mask = DNS_RPZ_ALL_ZBITS;
    495 			goto set;
    496 		}
    497 
    498 		/*
    499 		 * req_mask is a mask covering used bits in
    500 		 * zbits_req. (For instance, 0b1 => 0b1, 0b101 => 0b111,
    501 		 * 0b11010101 => 0b11111111).
    502 		 */
    503 		req_mask = zbits_req;
    504 		req_mask |= req_mask >> 1;
    505 		req_mask |= req_mask >> 2;
    506 		req_mask |= req_mask >> 4;
    507 		req_mask |= req_mask >> 8;
    508 		req_mask |= req_mask >> 16;
    509 		req_mask |= req_mask >> 32;
    510 
    511 		/*
    512 		 * There's no point in skipping recursion for a later
    513 		 * zone if it is required in a previous zone.
    514 		 */
    515 		if ((zbits_notreq & req_mask) == 0) {
    516 			mask = 0;
    517 			goto set;
    518 		}
    519 
    520 		/*
    521 		 * This bit arithmetic creates a mask of zones in which
    522 		 * it is okay to skip recursion. After the first zone
    523 		 * that has to wait for recursion, all the others have
    524 		 * to wait as well, so we want to create a mask in which
    525 		 * all the trailing zeroes in zbits_req are are 1, and
    526 		 * more significant bits are 0. (For instance,
    527 		 * 0x0700 => 0x00ff, 0x0007 => 0x0000)
    528 		 */
    529 		mask = ~(zbits_req | ((~zbits_req) + 1));
    530 
    531 		/*
    532 		 * As mentioned in (2) above, the zone corresponding to
    533 		 * the least significant zero could have its CLIENT-IP
    534 		 * and QNAME policies checked before recursion, if it
    535 		 * has any of those policies.  So if it does, we
    536 		 * can set its 0 to 1.
    537 		 *
    538 		 * Locate the least significant 0 bit in the mask (for
    539 		 * instance, 0xff => 0x100)...
    540 		 */
    541 		mask2 = (mask << 1) & ~mask;
    542 
    543 		/*
    544 		 * Also set the bit for zone 0, because if it's in
    545 		 * zbits_notreq then it's definitely okay to attempt to
    546 		 * skip recursion for zone 0...
    547 		 */
    548 		mask2 |= 1;
    549 
    550 		/* Clear any bits *not* in zbits_notreq... */
    551 		mask2 &= zbits_notreq;
    552 
    553 		/* And merge the result into the skip-recursion mask */
    554 		mask |= mask2;
    555 	}
    556 
    557  set:
    558 	isc_log_write(dns_lctx, DNS_LOGCATEGORY_RPZ, DNS_LOGMODULE_RBTDB,
    559 		      DNS_RPZ_DEBUG_QUIET,
    560 		      "computed RPZ qname_skip_recurse mask=0x%" PRIx64,
    561 		      (uint64_t) mask);
    562 	rpzs->have.qname_skip_recurse = mask;
    563 }
    564 
    565 static void
    566 adj_trigger_cnt(dns_rpz_zones_t *rpzs, dns_rpz_num_t rpz_num,
    567 		dns_rpz_type_t rpz_type,
    568 		const dns_rpz_cidr_key_t *tgt_ip, dns_rpz_prefix_t tgt_prefix,
    569 		bool inc)
    570 {
    571 	dns_rpz_trigger_counter_t *cnt = NULL;
    572 	dns_rpz_zbits_t *have = NULL;
    573 
    574 	switch (rpz_type) {
    575 	case DNS_RPZ_TYPE_CLIENT_IP:
    576 		REQUIRE(tgt_ip != NULL);
    577 		if (KEY_IS_IPV4(tgt_prefix, tgt_ip)) {
    578 			cnt = &rpzs->triggers[rpz_num].client_ipv4;
    579 			have = &rpzs->have.client_ipv4;
    580 		} else {
    581 			cnt = &rpzs->triggers[rpz_num].client_ipv6;
    582 			have = &rpzs->have.client_ipv6;
    583 		}
    584 		break;
    585 	case DNS_RPZ_TYPE_QNAME:
    586 		cnt = &rpzs->triggers[rpz_num].qname;
    587 		have = &rpzs->have.qname;
    588 		break;
    589 	case DNS_RPZ_TYPE_IP:
    590 		REQUIRE(tgt_ip != NULL);
    591 		if (KEY_IS_IPV4(tgt_prefix, tgt_ip)) {
    592 			cnt = &rpzs->triggers[rpz_num].ipv4;
    593 			have = &rpzs->have.ipv4;
    594 		} else {
    595 			cnt = &rpzs->triggers[rpz_num].ipv6;
    596 			have = &rpzs->have.ipv6;
    597 		}
    598 		break;
    599 	case DNS_RPZ_TYPE_NSDNAME:
    600 		cnt = &rpzs->triggers[rpz_num].nsdname;
    601 		have = &rpzs->have.nsdname;
    602 		break;
    603 	case DNS_RPZ_TYPE_NSIP:
    604 		REQUIRE(tgt_ip != NULL);
    605 		if (KEY_IS_IPV4(tgt_prefix, tgt_ip)) {
    606 			cnt = &rpzs->triggers[rpz_num].nsipv4;
    607 			have = &rpzs->have.nsipv4;
    608 		} else {
    609 			cnt = &rpzs->triggers[rpz_num].nsipv6;
    610 			have = &rpzs->have.nsipv6;
    611 		}
    612 		break;
    613 	default:
    614 		INSIST(0);
    615 		ISC_UNREACHABLE();
    616 	}
    617 
    618 	if (inc) {
    619 		if (++*cnt == 1U) {
    620 			*have |= DNS_RPZ_ZBIT(rpz_num);
    621 			fix_qname_skip_recurse(rpzs);
    622 		}
    623 	} else {
    624 		REQUIRE(*cnt != 0U);
    625 		if (--*cnt == 0U) {
    626 			*have &= ~DNS_RPZ_ZBIT(rpz_num);
    627 			fix_qname_skip_recurse(rpzs);
    628 		}
    629 	}
    630 }
    631 
    632 static dns_rpz_cidr_node_t *
    633 new_node(dns_rpz_zones_t *rpzs,
    634 	 const dns_rpz_cidr_key_t *ip, dns_rpz_prefix_t prefix,
    635 	 const dns_rpz_cidr_node_t *child)
    636 {
    637 	dns_rpz_cidr_node_t *node;
    638 	int i, words, wlen;
    639 
    640 	node = isc_mem_get(rpzs->mctx, sizeof(*node));
    641 	if (node == NULL)
    642 		return (NULL);
    643 	memset(node, 0, sizeof(*node));
    644 
    645 	if (child != NULL)
    646 		node->sum = child->sum;
    647 
    648 	node->prefix = prefix;
    649 	words = prefix / DNS_RPZ_CIDR_WORD_BITS;
    650 	wlen = prefix % DNS_RPZ_CIDR_WORD_BITS;
    651 	i = 0;
    652 	while (i < words) {
    653 		node->ip.w[i] = ip->w[i];
    654 		++i;
    655 	}
    656 	if (wlen != 0) {
    657 		node->ip.w[i] = ip->w[i] & DNS_RPZ_WORD_MASK(wlen);
    658 		++i;
    659 	}
    660 	while (i < DNS_RPZ_CIDR_WORDS)
    661 		node->ip.w[i++] = 0;
    662 
    663 	return (node);
    664 }
    665 
    666 static void
    667 badname(int level, const dns_name_t *name, const char *str1, const char *str2) {
    668 	char namebuf[DNS_NAME_FORMATSIZE];
    669 
    670 	/*
    671 	 * bin/tests/system/rpz/tests.sh looks for "invalid rpz".
    672 	 */
    673 	if (level < DNS_RPZ_DEBUG_QUIET &&
    674 	    isc_log_wouldlog(dns_lctx, level)) {
    675 		dns_name_format(name, namebuf, sizeof(namebuf));
    676 		isc_log_write(dns_lctx, DNS_LOGCATEGORY_RPZ,
    677 			      DNS_LOGMODULE_RBTDB, level,
    678 			      "invalid rpz IP address \"%s\"%s%s",
    679 			      namebuf, str1, str2);
    680 	}
    681 }
    682 
    683 /*
    684  * Convert an IP address from radix tree binary (host byte order) to
    685  * to its canonical response policy domain name without the origin of the
    686  * policy zone.
    687  *
    688  * Generate a name for an IPv6 address that fits RFC 5952, except that our
    689  * reversed format requires that when the length of the consecutive 16-bit
    690  * 0 fields are equal (e.g., 1.0.0.1.0.0.db8.2001 corresponding to
    691  * 2001:db8:0:0:1:0:0:1), we shorted the last instead of the first
    692  * (e.g., 1.0.0.1.zz.db8.2001 corresponding to 2001:db8::1:0:0:1).
    693  */
    694 static isc_result_t
    695 ip2name(const dns_rpz_cidr_key_t *tgt_ip, dns_rpz_prefix_t tgt_prefix,
    696 	const dns_name_t *base_name, dns_name_t *ip_name)
    697 {
    698 #ifndef INET6_ADDRSTRLEN
    699 #define INET6_ADDRSTRLEN 46
    700 #endif
    701 	int w[DNS_RPZ_CIDR_WORDS*2];
    702 	char str[1+8+1+INET6_ADDRSTRLEN+1];
    703 	isc_buffer_t buffer;
    704 	isc_result_t result;
    705 	int best_first, best_len, cur_first, cur_len;
    706 	int i, n, len;
    707 
    708 	if (KEY_IS_IPV4(tgt_prefix, tgt_ip)) {
    709 		len = snprintf(str, sizeof(str), "%u.%u.%u.%u.%u",
    710 			       tgt_prefix - 96U,
    711 			       tgt_ip->w[3] & 0xffU,
    712 			       (tgt_ip->w[3]>>8) & 0xffU,
    713 			       (tgt_ip->w[3]>>16) & 0xffU,
    714 			       (tgt_ip->w[3]>>24) & 0xffU);
    715 		if (len < 0 || len > (int)sizeof(str)) {
    716 			return (ISC_R_FAILURE);
    717 		}
    718 	} else {
    719 		len = snprintf(str, sizeof(str), "%d", tgt_prefix);
    720 		if (len == -1) {
    721 			return (ISC_R_FAILURE);
    722 		}
    723 
    724 		for (i = 0; i < DNS_RPZ_CIDR_WORDS; i++) {
    725 			w[i*2+1] = ((tgt_ip->w[DNS_RPZ_CIDR_WORDS-1-i] >> 16)
    726 				    & 0xffff);
    727 			w[i*2] = tgt_ip->w[DNS_RPZ_CIDR_WORDS-1-i] & 0xffff;
    728 		}
    729 		/*
    730 		 * Find the start and length of the first longest sequence
    731 		 * of zeros in the address.
    732 		 */
    733 		best_first = -1;
    734 		best_len = 0;
    735 		cur_first = -1;
    736 		cur_len = 0;
    737 		for (n = 0; n <=7; ++n) {
    738 			if (w[n] != 0) {
    739 				cur_len = 0;
    740 				cur_first = -1;
    741 			} else {
    742 				++cur_len;
    743 				if (cur_first < 0) {
    744 					cur_first = n;
    745 				} else if (cur_len >= best_len) {
    746 					best_first = cur_first;
    747 					best_len = cur_len;
    748 				}
    749 			}
    750 		}
    751 
    752 		for (n = 0; n <= 7; ++n) {
    753 			INSIST(len < (int)sizeof(str));
    754 			if (n == best_first) {
    755 				len += snprintf(str + len, sizeof(str) - len,
    756 						".zz");
    757 				n += best_len - 1;
    758 			} else {
    759 				len += snprintf(str + len, sizeof(str) - len,
    760 						".%x", w[n]);
    761 			}
    762 		}
    763 	}
    764 
    765 	isc_buffer_init(&buffer, str, sizeof(str));
    766 	isc_buffer_add(&buffer, len);
    767 	result = dns_name_fromtext(ip_name, &buffer, base_name, 0, NULL);
    768 	return (result);
    769 }
    770 
    771 /*
    772  * Determine the type of a name in a response policy zone.
    773  */
    774 static dns_rpz_type_t
    775 type_from_name(const dns_rpz_zones_t *rpzs,
    776 	       dns_rpz_zone_t *rpz, const dns_name_t *name)
    777 {
    778 	if (dns_name_issubdomain(name, &rpz->ip)) {
    779 		return (DNS_RPZ_TYPE_IP);
    780 	}
    781 
    782 	if (dns_name_issubdomain(name, &rpz->client_ip)) {
    783 		return (DNS_RPZ_TYPE_CLIENT_IP);
    784 	}
    785 
    786 	if ((rpzs->p.nsip_on & DNS_RPZ_ZBIT(rpz->num)) != 0 &&
    787 	    dns_name_issubdomain(name, &rpz->nsip))
    788 	{
    789 		return (DNS_RPZ_TYPE_NSIP);
    790 	}
    791 
    792 	if ((rpzs->p.nsdname_on & DNS_RPZ_ZBIT(rpz->num)) != 0 &&
    793 	    dns_name_issubdomain(name, &rpz->nsdname))
    794 	{
    795 		return (DNS_RPZ_TYPE_NSDNAME);
    796 	}
    797 
    798 	return (DNS_RPZ_TYPE_QNAME);
    799 }
    800 
    801 /*
    802  * Convert an IP address from canonical response policy domain name form
    803  * to radix tree binary (host byte order) for adding or deleting IP or NSIP
    804  * data.
    805  */
    806 static isc_result_t
    807 name2ipkey(int log_level,
    808 	   const dns_rpz_zones_t *rpzs, dns_rpz_num_t rpz_num,
    809 	   dns_rpz_type_t rpz_type, const dns_name_t *src_name,
    810 	   dns_rpz_cidr_key_t *tgt_ip, dns_rpz_prefix_t *tgt_prefix,
    811 	   dns_rpz_addr_zbits_t *new_set)
    812 {
    813 	dns_rpz_zone_t *rpz;
    814 	char ip_str[DNS_NAME_FORMATSIZE], ip2_str[DNS_NAME_FORMATSIZE];
    815 	dns_offsets_t ip_name_offsets;
    816 	dns_fixedname_t ip_name2f;
    817 	dns_name_t ip_name, *ip_name2;
    818 	const char *prefix_str, *cp, *end;
    819 	char *cp2;
    820 	int ip_labels;
    821 	dns_rpz_prefix_t prefix;
    822 	unsigned long prefix_num, l;
    823 	isc_result_t result;
    824 	int i;
    825 
    826 	REQUIRE(rpzs != NULL && rpz_num < rpzs->p.num_zones);
    827 	rpz = rpzs->zones[rpz_num];
    828 	REQUIRE(rpz != NULL);
    829 
    830 	make_addr_set(new_set, DNS_RPZ_ZBIT(rpz_num), rpz_type);
    831 
    832 	ip_labels = dns_name_countlabels(src_name);
    833 	if (rpz_type == DNS_RPZ_TYPE_QNAME)
    834 		ip_labels -= dns_name_countlabels(&rpz->origin);
    835 	else
    836 		ip_labels -= dns_name_countlabels(&rpz->nsdname);
    837 	if (ip_labels < 2) {
    838 		badname(log_level, src_name, "; too short", "");
    839 		return (ISC_R_FAILURE);
    840 	}
    841 	dns_name_init(&ip_name, ip_name_offsets);
    842 	dns_name_getlabelsequence(src_name, 0, ip_labels, &ip_name);
    843 
    844 	/*
    845 	 * Get text for the IP address
    846 	 */
    847 	dns_name_format(&ip_name, ip_str, sizeof(ip_str));
    848 	end = &ip_str[strlen(ip_str)+1];
    849 	prefix_str = ip_str;
    850 
    851 	prefix_num = strtoul(prefix_str, &cp2, 10);
    852 	if (*cp2 != '.') {
    853 		badname(log_level, src_name,
    854 			"; invalid leading prefix length", "");
    855 		return (ISC_R_FAILURE);
    856 	}
    857 	/*
    858 	 * Patch in trailing nul character to print just the length
    859 	 * label (for various cases below).
    860 	 */
    861 	*cp2 = '\0';
    862 	if (prefix_num < 1U || prefix_num > 128U) {
    863 		badname(log_level, src_name,
    864 			"; invalid prefix length of ", prefix_str);
    865 		return (ISC_R_FAILURE);
    866 	}
    867 	cp = cp2+1;
    868 
    869 	if (--ip_labels == 4 && !strchr(cp, 'z')) {
    870 		/*
    871 		 * Convert an IPv4 address
    872 		 * from the form "prefix.z.y.x.w"
    873 		 */
    874 		if (prefix_num > 32U) {
    875 			badname(log_level, src_name,
    876 				"; invalid IPv4 prefix length of ", prefix_str);
    877 			return (ISC_R_FAILURE);
    878 		}
    879 		prefix_num += 96;
    880 		*tgt_prefix = (dns_rpz_prefix_t)prefix_num;
    881 		tgt_ip->w[0] = 0;
    882 		tgt_ip->w[1] = 0;
    883 		tgt_ip->w[2] = ADDR_V4MAPPED;
    884 		tgt_ip->w[3] = 0;
    885 		for (i = 0; i < 32; i += 8) {
    886 			l = strtoul(cp, &cp2, 10);
    887 			if (l > 255U || (*cp2 != '.' && *cp2 != '\0')) {
    888 				if (*cp2 == '.')
    889 					*cp2 = '\0';
    890 				badname(log_level, src_name,
    891 					"; invalid IPv4 octet ", cp);
    892 				return (ISC_R_FAILURE);
    893 			}
    894 			tgt_ip->w[3] |= l << i;
    895 			cp = cp2 + 1;
    896 		}
    897 	} else {
    898 		/*
    899 		 * Convert a text IPv6 address.
    900 		 */
    901 		*tgt_prefix = (dns_rpz_prefix_t)prefix_num;
    902 		for (i = 0;
    903 		     ip_labels > 0 && i < DNS_RPZ_CIDR_WORDS * 2;
    904 		     ip_labels--) {
    905 			if (cp[0] == 'z' && cp[1] == 'z' &&
    906 			    (cp[2] == '.' || cp[2] == '\0') &&
    907 			    i <= 6) {
    908 				do {
    909 					if ((i & 1) == 0)
    910 					    tgt_ip->w[3-i/2] = 0;
    911 					++i;
    912 				} while (ip_labels + i <= 8);
    913 				cp += 3;
    914 			} else {
    915 				l = strtoul(cp, &cp2, 16);
    916 				if (l > 0xffffu ||
    917 				    (*cp2 != '.' && *cp2 != '\0')) {
    918 					if (*cp2 == '.')
    919 					    *cp2 = '\0';
    920 					badname(log_level, src_name,
    921 						"; invalid IPv6 word ", cp);
    922 					return (ISC_R_FAILURE);
    923 				}
    924 				if ((i & 1) == 0)
    925 					tgt_ip->w[3-i/2] = l;
    926 				else
    927 					tgt_ip->w[3-i/2] |= l << 16;
    928 				i++;
    929 				cp = cp2 + 1;
    930 			}
    931 		}
    932 	}
    933 	if (cp != end) {
    934 		badname(log_level, src_name, "", "");
    935 		return (ISC_R_FAILURE);
    936 	}
    937 
    938 	/*
    939 	 * Check for 1s after the prefix length.
    940 	 */
    941 	prefix = (dns_rpz_prefix_t)prefix_num;
    942 	while (prefix < DNS_RPZ_CIDR_KEY_BITS) {
    943 		dns_rpz_cidr_word_t aword;
    944 
    945 		i = prefix % DNS_RPZ_CIDR_WORD_BITS;
    946 		aword = tgt_ip->w[prefix / DNS_RPZ_CIDR_WORD_BITS];
    947 		if ((aword & ~DNS_RPZ_WORD_MASK(i)) != 0) {
    948 			badname(log_level, src_name,
    949 				"; too small prefix length of ", prefix_str);
    950 			return (ISC_R_FAILURE);
    951 		}
    952 		prefix -= i;
    953 		prefix += DNS_RPZ_CIDR_WORD_BITS;
    954 	}
    955 
    956 	/*
    957 	 * Complain about bad names but be generous and accept them.
    958 	 */
    959 	if (log_level < DNS_RPZ_DEBUG_QUIET &&
    960 	    isc_log_wouldlog(dns_lctx, log_level)) {
    961 		/*
    962 		 * Convert the address back to a canonical domain name
    963 		 * to ensure that the original name is in canonical form.
    964 		 */
    965 		ip_name2 = dns_fixedname_initname(&ip_name2f);
    966 		result = ip2name(tgt_ip, (dns_rpz_prefix_t)prefix_num,
    967 				 NULL, ip_name2);
    968 		if (result != ISC_R_SUCCESS ||
    969 		    !dns_name_equal(&ip_name, ip_name2)) {
    970 			dns_name_format(ip_name2, ip2_str, sizeof(ip2_str));
    971 			isc_log_write(dns_lctx, DNS_LOGCATEGORY_RPZ,
    972 				      DNS_LOGMODULE_RBTDB, log_level,
    973 				      "rpz IP address \"%s\""
    974 				      " is not the canonical \"%s\"",
    975 				      ip_str, ip2_str);
    976 		}
    977 	}
    978 
    979 	return (ISC_R_SUCCESS);
    980 }
    981 
    982 /*
    983  * Get trigger name and data bits for adding or deleting summary NSDNAME
    984  * or QNAME data.
    985  */
    986 static void
    987 name2data(dns_rpz_zones_t *rpzs, dns_rpz_num_t rpz_num,
    988 	  dns_rpz_type_t rpz_type, const dns_name_t *src_name,
    989 	  dns_name_t *trig_name, dns_rpz_nm_data_t *new_data)
    990 {
    991 	dns_rpz_zone_t *rpz;
    992 	dns_offsets_t tmp_name_offsets;
    993 	dns_name_t tmp_name;
    994 	unsigned int prefix_len, n;
    995 
    996 	REQUIRE(rpzs != NULL && rpz_num < rpzs->p.num_zones);
    997 	rpz = rpzs->zones[rpz_num];
    998 	REQUIRE(rpz != NULL);
    999 
   1000 	/*
   1001 	 * Handle wildcards by putting only the parent into the
   1002 	 * summary RBT.  The summary database only causes a check of the
   1003 	 * real policy zone where wildcards will be handled.
   1004 	 */
   1005 	if (dns_name_iswildcard(src_name)) {
   1006 		prefix_len = 1;
   1007 		memset(&new_data->set, 0, sizeof(new_data->set));
   1008 		make_nm_set(&new_data->wild, rpz_num, rpz_type);
   1009 	} else {
   1010 		prefix_len = 0;
   1011 		make_nm_set(&new_data->set, rpz_num, rpz_type);
   1012 		memset(&new_data->wild, 0, sizeof(new_data->wild));
   1013 	}
   1014 
   1015 	dns_name_init(&tmp_name, tmp_name_offsets);
   1016 	n = dns_name_countlabels(src_name);
   1017 	n -= prefix_len;
   1018 	if (rpz_type == DNS_RPZ_TYPE_QNAME)
   1019 		n -= dns_name_countlabels(&rpz->origin);
   1020 	else
   1021 		n -= dns_name_countlabels(&rpz->nsdname);
   1022 	dns_name_getlabelsequence(src_name, prefix_len, n, &tmp_name);
   1023 	(void)dns_name_concatenate(&tmp_name, dns_rootname, trig_name, NULL);
   1024 }
   1025 
   1026 #ifndef HAVE_BUILTIN_CLZ
   1027 /**
   1028  * \brief Count Leading Zeros: Find the location of the left-most set
   1029  * bit.
   1030  */
   1031 static inline unsigned int
   1032 clz(dns_rpz_cidr_word_t w) {
   1033 	unsigned int bit;
   1034 
   1035 	bit = DNS_RPZ_CIDR_WORD_BITS-1;
   1036 
   1037 	if ((w & 0xffff0000) != 0) {
   1038 		w >>= 16;
   1039 		bit -= 16;
   1040 	}
   1041 
   1042 	if ((w & 0xff00) != 0) {
   1043 		w >>= 8;
   1044 		bit -= 8;
   1045 	}
   1046 
   1047 	if ((w & 0xf0) != 0) {
   1048 		w >>= 4;
   1049 		bit -= 4;
   1050 	}
   1051 
   1052 	if ((w & 0xc) != 0) {
   1053 		w >>= 2;
   1054 		bit -= 2;
   1055 	}
   1056 
   1057 	if ((w & 2) != 0)
   1058 		--bit;
   1059 
   1060 	return (bit);
   1061 }
   1062 #endif
   1063 
   1064 /*
   1065  * Find the first differing bit in two keys (IP addresses).
   1066  */
   1067 static int
   1068 diff_keys(const dns_rpz_cidr_key_t *key1, dns_rpz_prefix_t prefix1,
   1069 	  const dns_rpz_cidr_key_t *key2, dns_rpz_prefix_t prefix2)
   1070 {
   1071 	dns_rpz_cidr_word_t delta;
   1072 	dns_rpz_prefix_t maxbit, bit;
   1073 	int i;
   1074 
   1075 	bit = 0;
   1076 	maxbit = ISC_MIN(prefix1, prefix2);
   1077 
   1078 	/*
   1079 	 * find the first differing words
   1080 	 */
   1081 	for (i = 0; bit < maxbit; i++, bit += DNS_RPZ_CIDR_WORD_BITS) {
   1082 		delta = key1->w[i] ^ key2->w[i];
   1083 		if (ISC_UNLIKELY(delta != 0)) {
   1084 #ifdef HAVE_BUILTIN_CLZ
   1085 			bit += __builtin_clz(delta);
   1086 #else
   1087 			bit += clz(delta);
   1088 #endif
   1089 			break;
   1090 		}
   1091 	}
   1092 	return (ISC_MIN(bit, maxbit));
   1093 }
   1094 
   1095 /*
   1096  * Given a hit while searching the radix trees,
   1097  * clear all bits for higher numbered zones.
   1098  */
   1099 static inline dns_rpz_zbits_t
   1100 trim_zbits(dns_rpz_zbits_t zbits, dns_rpz_zbits_t found) {
   1101 	dns_rpz_zbits_t x;
   1102 
   1103 	/*
   1104 	 * Isolate the first or smallest numbered hit bit.
   1105 	 * Make a mask of that bit and all smaller numbered bits.
   1106 	 */
   1107 	x = zbits & found;
   1108 	x &= (~x + 1);
   1109 	x = (x << 1) - 1;
   1110 	return (zbits &= x);
   1111 }
   1112 
   1113 /*
   1114  * Search a radix tree for an IP address for ordinary lookup
   1115  *	or for a CIDR block adding or deleting an entry
   1116  *
   1117  * Return ISC_R_SUCCESS, DNS_R_PARTIALMATCH, ISC_R_NOTFOUND,
   1118  *	    and *found=longest match node
   1119  *	or with create==true, ISC_R_EXISTS or ISC_R_NOMEMORY
   1120  */
   1121 static isc_result_t
   1122 search(dns_rpz_zones_t *rpzs,
   1123        const dns_rpz_cidr_key_t *tgt_ip, dns_rpz_prefix_t tgt_prefix,
   1124        const dns_rpz_addr_zbits_t *tgt_set, bool create,
   1125        dns_rpz_cidr_node_t **found)
   1126 {
   1127 	dns_rpz_cidr_node_t *cur, *parent, *child, *new_parent, *sibling;
   1128 	dns_rpz_addr_zbits_t set;
   1129 	int cur_num, child_num;
   1130 	dns_rpz_prefix_t dbit;
   1131 	isc_result_t find_result;
   1132 
   1133 	set = *tgt_set;
   1134 	find_result = ISC_R_NOTFOUND;
   1135 	*found = NULL;
   1136 	cur = rpzs->cidr;
   1137 	parent = NULL;
   1138 	cur_num = 0;
   1139 	for (;;) {
   1140 		if (cur == NULL) {
   1141 			/*
   1142 			 * No child so we cannot go down.
   1143 			 * Quit with whatever we already found
   1144 			 * or add the target as a child of the current parent.
   1145 			 */
   1146 			if (!create)
   1147 				return (find_result);
   1148 			child = new_node(rpzs, tgt_ip, tgt_prefix, NULL);
   1149 			if (child == NULL)
   1150 				return (ISC_R_NOMEMORY);
   1151 			if (parent == NULL)
   1152 				rpzs->cidr = child;
   1153 			else
   1154 				parent->child[cur_num] = child;
   1155 			child->parent = parent;
   1156 			child->set.client_ip |= tgt_set->client_ip;
   1157 			child->set.ip |= tgt_set->ip;
   1158 			child->set.nsip |= tgt_set->nsip;
   1159 			set_sum_pair(child);
   1160 			*found = child;
   1161 			return (ISC_R_SUCCESS);
   1162 		}
   1163 
   1164 		if ((cur->sum.client_ip & set.client_ip) == 0 &&
   1165 		    (cur->sum.ip & set.ip) == 0 &&
   1166 		    (cur->sum.nsip & set.nsip) == 0) {
   1167 			/*
   1168 			 * This node has no relevant data
   1169 			 * and is in none of the target trees.
   1170 			 * Pretend it does not exist if we are not adding.
   1171 			 *
   1172 			 * If we are adding, continue down to eventually add
   1173 			 * a node and mark/put this node in the correct tree.
   1174 			 */
   1175 			if (!create)
   1176 				return (find_result);
   1177 		}
   1178 
   1179 		dbit = diff_keys(tgt_ip, tgt_prefix, &cur->ip, cur->prefix);
   1180 		/*
   1181 		 * dbit <= tgt_prefix and dbit <= cur->prefix always.
   1182 		 * We are finished searching if we matched all of the target.
   1183 		 */
   1184 		if (dbit == tgt_prefix) {
   1185 			if (tgt_prefix == cur->prefix) {
   1186 				/*
   1187 				 * The node's key matches the target exactly.
   1188 				 */
   1189 				if ((cur->set.client_ip & set.client_ip) != 0 ||
   1190 				    (cur->set.ip & set.ip) != 0 ||
   1191 				    (cur->set.nsip & set.nsip) != 0) {
   1192 					/*
   1193 					 * It is the answer if it has data.
   1194 					 */
   1195 					*found = cur;
   1196 					if (create) {
   1197 					    find_result = ISC_R_EXISTS;
   1198 					} else {
   1199 					    find_result = ISC_R_SUCCESS;
   1200 					}
   1201 				} else if (create) {
   1202 					/*
   1203 					 * The node lacked relevant data,
   1204 					 * but will have it now.
   1205 					 */
   1206 					cur->set.client_ip |=
   1207 						tgt_set->client_ip;
   1208 					cur->set.ip |= tgt_set->ip;
   1209 					cur->set.nsip |= tgt_set->nsip;
   1210 					set_sum_pair(cur);
   1211 					*found = cur;
   1212 					find_result = ISC_R_SUCCESS;
   1213 				}
   1214 				return (find_result);
   1215 			}
   1216 
   1217 			/*
   1218 			 * We know tgt_prefix < cur->prefix which means that
   1219 			 * the target is shorter than the current node.
   1220 			 * Add the target as the current node's parent.
   1221 			 */
   1222 			if (!create)
   1223 				return (find_result);
   1224 
   1225 			new_parent = new_node(rpzs, tgt_ip, tgt_prefix, cur);
   1226 			if (new_parent == NULL)
   1227 				return (ISC_R_NOMEMORY);
   1228 			new_parent->parent = parent;
   1229 			if (parent == NULL)
   1230 				rpzs->cidr = new_parent;
   1231 			else
   1232 				parent->child[cur_num] = new_parent;
   1233 			child_num = DNS_RPZ_IP_BIT(&cur->ip, tgt_prefix);
   1234 			new_parent->child[child_num] = cur;
   1235 			cur->parent = new_parent;
   1236 			new_parent->set = *tgt_set;
   1237 			set_sum_pair(new_parent);
   1238 			*found = new_parent;
   1239 			return (ISC_R_SUCCESS);
   1240 		}
   1241 
   1242 		if (dbit == cur->prefix) {
   1243 			if ((cur->set.client_ip & set.client_ip) != 0 ||
   1244 			    (cur->set.ip & set.ip) != 0 ||
   1245 			    (cur->set.nsip & set.nsip) != 0) {
   1246 				/*
   1247 				 * We have a partial match between of all of the
   1248 				 * current node but only part of the target.
   1249 				 * Continue searching for other hits in the
   1250 				 * same or lower numbered trees.
   1251 				 */
   1252 				find_result = DNS_R_PARTIALMATCH;
   1253 				*found = cur;
   1254 				set.client_ip = trim_zbits(set.client_ip,
   1255 							   cur->set.client_ip);
   1256 				set.ip = trim_zbits(set.ip,
   1257 						    cur->set.ip);
   1258 				set.nsip = trim_zbits(set.nsip,
   1259 						      cur->set.nsip);
   1260 			}
   1261 			parent = cur;
   1262 			cur_num = DNS_RPZ_IP_BIT(tgt_ip, dbit);
   1263 			cur = cur->child[cur_num];
   1264 			continue;
   1265 		}
   1266 
   1267 
   1268 		/*
   1269 		 * dbit < tgt_prefix and dbit < cur->prefix,
   1270 		 * so we failed to match both the target and the current node.
   1271 		 * Insert a fork of a parent above the current node and
   1272 		 * add the target as a sibling of the current node
   1273 		 */
   1274 		if (!create)
   1275 			return (find_result);
   1276 
   1277 		sibling = new_node(rpzs, tgt_ip, tgt_prefix, NULL);
   1278 		if (sibling == NULL)
   1279 			return (ISC_R_NOMEMORY);
   1280 		new_parent = new_node(rpzs, tgt_ip, dbit, cur);
   1281 		if (new_parent == NULL) {
   1282 			isc_mem_put(rpzs->mctx, sibling, sizeof(*sibling));
   1283 			return (ISC_R_NOMEMORY);
   1284 		}
   1285 		new_parent->parent = parent;
   1286 		if (parent == NULL)
   1287 			rpzs->cidr = new_parent;
   1288 		else
   1289 			parent->child[cur_num] = new_parent;
   1290 		child_num = DNS_RPZ_IP_BIT(tgt_ip, dbit);
   1291 		new_parent->child[child_num] = sibling;
   1292 		new_parent->child[1-child_num] = cur;
   1293 		cur->parent = new_parent;
   1294 		sibling->parent = new_parent;
   1295 		sibling->set = *tgt_set;
   1296 		set_sum_pair(sibling);
   1297 		*found = sibling;
   1298 		return (ISC_R_SUCCESS);
   1299 	}
   1300 }
   1301 
   1302 /*
   1303  * Add an IP address to the radix tree.
   1304  */
   1305 static isc_result_t
   1306 add_cidr(dns_rpz_zones_t *rpzs, dns_rpz_num_t rpz_num,
   1307 	 dns_rpz_type_t rpz_type, const dns_name_t *src_name)
   1308 {
   1309 	dns_rpz_cidr_key_t tgt_ip;
   1310 	dns_rpz_prefix_t tgt_prefix;
   1311 	dns_rpz_addr_zbits_t set;
   1312 	dns_rpz_cidr_node_t *found;
   1313 	isc_result_t result;
   1314 
   1315 	result = name2ipkey(DNS_RPZ_ERROR_LEVEL, rpzs, rpz_num, rpz_type,
   1316 			    src_name, &tgt_ip, &tgt_prefix, &set);
   1317 	/*
   1318 	 * Log complaints about bad owner names but let the zone load.
   1319 	 */
   1320 	if (result != ISC_R_SUCCESS)
   1321 		return (ISC_R_SUCCESS);
   1322 
   1323 	result = search(rpzs, &tgt_ip, tgt_prefix, &set, true, &found);
   1324 	if (result != ISC_R_SUCCESS) {
   1325 		char namebuf[DNS_NAME_FORMATSIZE];
   1326 
   1327 		/*
   1328 		 * Do not worry if the radix tree already exists,
   1329 		 * because diff_apply() likes to add nodes before deleting.
   1330 		 */
   1331 		if (result == ISC_R_EXISTS)
   1332 			return (ISC_R_SUCCESS);
   1333 
   1334 		/*
   1335 		 * bin/tests/system/rpz/tests.sh looks for "rpz.*failed".
   1336 		 */
   1337 		dns_name_format(src_name, namebuf, sizeof(namebuf));
   1338 		isc_log_write(dns_lctx, DNS_LOGCATEGORY_RPZ,
   1339 			      DNS_LOGMODULE_RBTDB, DNS_RPZ_ERROR_LEVEL,
   1340 			      "rpz add_cidr(%s) failed: %s",
   1341 			      namebuf, isc_result_totext(result));
   1342 		return (result);
   1343 	}
   1344 
   1345 	adj_trigger_cnt(rpzs, rpz_num, rpz_type, &tgt_ip, tgt_prefix, true);
   1346 	return (result);
   1347 }
   1348 
   1349 static isc_result_t
   1350 add_nm(dns_rpz_zones_t *rpzs, dns_name_t *trig_name,
   1351 	 const dns_rpz_nm_data_t *new_data)
   1352 {
   1353 	dns_rbtnode_t *nmnode;
   1354 	dns_rpz_nm_data_t *nm_data;
   1355 	isc_result_t result;
   1356 
   1357 	nmnode = NULL;
   1358 	result = dns_rbt_addnode(rpzs->rbt, trig_name, &nmnode);
   1359 	switch (result) {
   1360 	case ISC_R_SUCCESS:
   1361 	case ISC_R_EXISTS:
   1362 		nm_data = nmnode->data;
   1363 		if (nm_data == NULL) {
   1364 			nm_data = isc_mem_get(rpzs->mctx, sizeof(*nm_data));
   1365 			if (nm_data == NULL)
   1366 				return (ISC_R_NOMEMORY);
   1367 			*nm_data = *new_data;
   1368 			nmnode->data = nm_data;
   1369 			return (ISC_R_SUCCESS);
   1370 		}
   1371 		break;
   1372 	default:
   1373 		return (result);
   1374 	}
   1375 
   1376 	/*
   1377 	 * Do not count bits that are already present
   1378 	 */
   1379 	if ((nm_data->set.qname & new_data->set.qname) != 0 ||
   1380 	    (nm_data->set.ns & new_data->set.ns) != 0 ||
   1381 	    (nm_data->wild.qname & new_data->wild.qname) != 0 ||
   1382 	    (nm_data->wild.ns & new_data->wild.ns) != 0)
   1383 		return (ISC_R_EXISTS);
   1384 
   1385 	nm_data->set.qname |= new_data->set.qname;
   1386 	nm_data->set.ns |= new_data->set.ns;
   1387 	nm_data->wild.qname |= new_data->wild.qname;
   1388 	nm_data->wild.ns |= new_data->wild.ns;
   1389 	return (ISC_R_SUCCESS);
   1390 }
   1391 
   1392 static isc_result_t
   1393 add_name(dns_rpz_zones_t *rpzs, dns_rpz_num_t rpz_num,
   1394 	 dns_rpz_type_t rpz_type, const dns_name_t *src_name)
   1395 {
   1396 	dns_rpz_nm_data_t new_data;
   1397 	dns_fixedname_t trig_namef;
   1398 	dns_name_t *trig_name;
   1399 	isc_result_t result;
   1400 
   1401 	/*
   1402 	 * We need a summary database of names even with 1 policy zone,
   1403 	 * because wildcard triggers are handled differently.
   1404 	 */
   1405 
   1406 	trig_name = dns_fixedname_initname(&trig_namef);
   1407 	name2data(rpzs, rpz_num, rpz_type, src_name, trig_name, &new_data);
   1408 
   1409 	result = add_nm(rpzs, trig_name, &new_data);
   1410 
   1411 	/*
   1412 	 * Do not worry if the node already exists,
   1413 	 * because diff_apply() likes to add nodes before deleting.
   1414 	 */
   1415 	if (result == ISC_R_EXISTS)
   1416 		return (ISC_R_SUCCESS);
   1417 	if (result == ISC_R_SUCCESS)
   1418 		adj_trigger_cnt(rpzs, rpz_num, rpz_type, NULL, 0, true);
   1419 	return (result);
   1420 }
   1421 
   1422 /*
   1423  * Callback to free the data for a node in the summary RBT database.
   1424  */
   1425 static void
   1426 rpz_node_deleter(void *nm_data, void *mctx) {
   1427 	isc_mem_put(mctx, nm_data, sizeof(dns_rpz_nm_data_t));
   1428 }
   1429 
   1430 /*
   1431  * Get ready for a new set of policy zones for a view.
   1432  */
   1433 isc_result_t
   1434 dns_rpz_new_zones(dns_rpz_zones_t **rpzsp, char *rps_cstr,
   1435 		  size_t rps_cstr_size, isc_mem_t *mctx,
   1436 		  isc_taskmgr_t *taskmgr, isc_timermgr_t *timermgr)
   1437 {
   1438 	dns_rpz_zones_t *zones;
   1439 	isc_result_t result;
   1440 
   1441 	REQUIRE(rpzsp != NULL && *rpzsp == NULL);
   1442 
   1443 	zones = isc_mem_get(mctx, sizeof(*zones));
   1444 	if (zones == NULL)
   1445 		return (ISC_R_NOMEMORY);
   1446 	memset(zones, 0, sizeof(*zones));
   1447 
   1448 	result = isc_rwlock_init(&zones->search_lock, 0, 0);
   1449 	if (result != ISC_R_SUCCESS)
   1450 		goto cleanup_rwlock;
   1451 
   1452 	isc_mutex_init(&zones->maint_lock);
   1453 	isc_refcount_init(&zones->refs, 1);
   1454 
   1455 	zones->rps_cstr = rps_cstr;
   1456 	zones->rps_cstr_size = rps_cstr_size;
   1457 #ifdef USE_DNSRPS
   1458 	if (rps_cstr != NULL) {
   1459 		result = dns_dnsrps_view_init(zones, rps_cstr);
   1460 	}
   1461 #else
   1462 	INSIST(!zones->p.dnsrps_enabled);
   1463 #endif
   1464 	if (result == ISC_R_SUCCESS && !zones->p.dnsrps_enabled) {
   1465 		result = dns_rbt_create(mctx, rpz_node_deleter,
   1466 					mctx, &zones->rbt);
   1467 	}
   1468 
   1469 	if (result != ISC_R_SUCCESS)
   1470 		goto cleanup_rbt;
   1471 
   1472 	result = isc_task_create(taskmgr, 0, &zones->updater);
   1473 	if (result != ISC_R_SUCCESS)
   1474 		goto cleanup_task;
   1475 
   1476 	isc_mem_attach(mctx, &zones->mctx);
   1477 	zones->timermgr = timermgr;
   1478 	zones->taskmgr = taskmgr;
   1479 
   1480 	*rpzsp = zones;
   1481 	return (ISC_R_SUCCESS);
   1482 
   1483 cleanup_task:
   1484 	dns_rbt_destroy(&zones->rbt);
   1485 
   1486 cleanup_rbt:
   1487 	INSIST(isc_refcount_decrement(&zones->refs) > 0);
   1488 	isc_refcount_destroy(&zones->refs);
   1489 
   1490 	isc_mutex_destroy(&zones->maint_lock);
   1491 
   1492 	isc_rwlock_destroy(&zones->search_lock);
   1493 
   1494 cleanup_rwlock:
   1495 	isc_mem_put(mctx, zones, sizeof(*zones));
   1496 
   1497 	return (result);
   1498 }
   1499 
   1500 isc_result_t
   1501 dns_rpz_new_zone(dns_rpz_zones_t *rpzs, dns_rpz_zone_t **rpzp) {
   1502 	dns_rpz_zone_t *zone;
   1503 	isc_result_t result;
   1504 
   1505 	REQUIRE(rpzp != NULL && *rpzp == NULL);
   1506 	REQUIRE(rpzs != NULL);
   1507 	if (rpzs->p.num_zones >= DNS_RPZ_MAX_ZONES) {
   1508 		return (ISC_R_NOSPACE);
   1509 	}
   1510 
   1511 	zone = isc_mem_get(rpzs->mctx, sizeof(*zone));
   1512 	if (zone == NULL) {
   1513 		return (ISC_R_NOMEMORY);
   1514 	}
   1515 
   1516 	memset(zone, 0, sizeof(*zone));
   1517 	isc_refcount_init(&zone->refs, 1);
   1518 
   1519 	result = isc_timer_create(rpzs->timermgr, isc_timertype_inactive,
   1520 				  NULL, NULL, rpzs->updater,
   1521 				  dns_rpz_update_taskaction,
   1522 				  zone, &zone->updatetimer);
   1523 	if (result != ISC_R_SUCCESS)
   1524 		goto cleanup_timer;
   1525 
   1526 	/*
   1527 	 * This will never be used, but costs us nothing and
   1528 	 * simplifies update_from_db
   1529 	 */
   1530 
   1531 	result = isc_ht_init(&zone->nodes, rpzs->mctx, 1);
   1532 	if (result != ISC_R_SUCCESS)
   1533 		goto cleanup_ht;
   1534 
   1535 	dns_name_init(&zone->origin, NULL);
   1536 	dns_name_init(&zone->client_ip, NULL);
   1537 	dns_name_init(&zone->ip, NULL);
   1538 	dns_name_init(&zone->nsdname, NULL);
   1539 	dns_name_init(&zone->nsip, NULL);
   1540 	dns_name_init(&zone->passthru, NULL);
   1541 	dns_name_init(&zone->drop, NULL);
   1542 	dns_name_init(&zone->tcp_only, NULL);
   1543 	dns_name_init(&zone->cname, NULL);
   1544 
   1545 	isc_time_settoepoch(&zone->lastupdated);
   1546 	zone->updatepending = false;
   1547 	zone->updaterunning = false;
   1548 	zone->db = NULL;
   1549 	zone->dbversion = NULL;
   1550 	zone->updb = NULL;
   1551 	zone->updbversion = NULL;
   1552 	zone->updbit = NULL;
   1553 	zone->rpzs = rpzs;
   1554 	zone->db_registered = false;
   1555 	ISC_EVENT_INIT(&zone->updateevent, sizeof(zone->updateevent),
   1556 		       0, NULL, 0, NULL, NULL, NULL, NULL, NULL);
   1557 
   1558 	zone->num = rpzs->p.num_zones++;
   1559 	rpzs->zones[zone->num] = zone;
   1560 
   1561 	*rpzp = zone;
   1562 
   1563 	return (ISC_R_SUCCESS);
   1564 
   1565 cleanup_ht:
   1566 	isc_timer_detach(&zone->updatetimer);
   1567 
   1568 cleanup_timer:
   1569 	INSIST(isc_refcount_decrement(&zone->refs) > 0);
   1570 	isc_refcount_destroy(&zone->refs);
   1571 
   1572 	isc_mem_put(zone->rpzs->mctx, zone, sizeof(*zone));
   1573 
   1574 	return (result);
   1575 }
   1576 
   1577 isc_result_t
   1578 dns_rpz_dbupdate_callback(dns_db_t *db, void *fn_arg) {
   1579 	dns_rpz_zone_t *zone = (dns_rpz_zone_t *) fn_arg;
   1580 	isc_time_t now;
   1581 	uint64_t tdiff;
   1582 	isc_result_t result = ISC_R_SUCCESS;
   1583 	char dname[DNS_NAME_FORMATSIZE];
   1584 
   1585 	REQUIRE(DNS_DB_VALID(db));
   1586 	REQUIRE(zone != NULL);
   1587 
   1588 	LOCK(&zone->rpzs->maint_lock);
   1589 	REQUIRE(zone->db_registered);
   1590 
   1591 
   1592 	/* New zone came as AXFR */
   1593 	if (zone->db != NULL && zone->db != db) {
   1594 		/* We need to clean up the old DB */
   1595 		if (zone->dbversion != NULL)
   1596 			dns_db_closeversion(zone->db, &zone->dbversion,
   1597 					    false);
   1598 		dns_db_updatenotify_unregister(zone->db,
   1599 					       dns_rpz_dbupdate_callback,
   1600 					       zone);
   1601 		dns_db_detach(&zone->db);
   1602 	}
   1603 
   1604 	if (zone->db == NULL) {
   1605 		RUNTIME_CHECK(zone->dbversion == NULL);
   1606 		dns_db_attach(db, &zone->db);
   1607 	}
   1608 
   1609 	if (!zone->updatepending && !zone->updaterunning) {
   1610 		zone->updatepending = true;
   1611 		isc_time_now(&now);
   1612 		tdiff = isc_time_microdiff(&now, &zone->lastupdated) / 1000000;
   1613 		if (tdiff < zone->min_update_interval) {
   1614 			uint64_t defer = zone->min_update_interval - tdiff;
   1615 			isc_interval_t interval;
   1616 			dns_name_format(&zone->origin, dname,
   1617 					DNS_NAME_FORMATSIZE);
   1618 			isc_log_write(dns_lctx, DNS_LOGCATEGORY_GENERAL,
   1619 				      DNS_LOGMODULE_MASTER, ISC_LOG_INFO,
   1620 				      "rpz: %s: new zone version came "
   1621 				      "too soon, deferring update for "
   1622 				      "%" PRIu64 " seconds", dname, defer);
   1623 			isc_interval_set(&interval, (unsigned int)defer, 0);
   1624 			dns_db_currentversion(zone->db, &zone->dbversion);
   1625 			result = isc_timer_reset(zone->updatetimer,
   1626 						 isc_timertype_once,
   1627 						 NULL, &interval, true);
   1628 			if (result != ISC_R_SUCCESS)
   1629 				goto cleanup;
   1630 		} else {
   1631 			isc_event_t *event;
   1632 
   1633 			dns_db_currentversion(zone->db, &zone->dbversion);
   1634 			INSIST(!ISC_LINK_LINKED(&zone->updateevent, ev_link));
   1635 			ISC_EVENT_INIT(&zone->updateevent,
   1636 				       sizeof(zone->updateevent), 0, NULL,
   1637 				       DNS_EVENT_RPZUPDATED,
   1638 				       dns_rpz_update_taskaction,
   1639 				       zone, zone, NULL, NULL);
   1640 			event = &zone->updateevent;
   1641 			isc_task_send(zone->rpzs->updater, &event);
   1642 		}
   1643 	} else {
   1644 		zone->updatepending = true;
   1645 		dns_name_format(&zone->origin, dname, DNS_NAME_FORMATSIZE);
   1646 		isc_log_write(dns_lctx, DNS_LOGCATEGORY_GENERAL,
   1647 			      DNS_LOGMODULE_MASTER, ISC_LOG_DEBUG(3),
   1648 			      "rpz: %s: update already queued or running", dname);
   1649 		if (zone->dbversion != NULL)
   1650 			dns_db_closeversion(zone->db, &zone->dbversion,
   1651 					    false);
   1652 		dns_db_currentversion(zone->db, &zone->dbversion);
   1653 	}
   1654 
   1655   cleanup:
   1656 	UNLOCK(&zone->rpzs->maint_lock);
   1657 
   1658 	return (result);
   1659 }
   1660 
   1661 static void
   1662 dns_rpz_update_taskaction(isc_task_t *task, isc_event_t *event) {
   1663 	isc_result_t result;
   1664 	dns_rpz_zone_t *zone;
   1665 
   1666 	REQUIRE(event != NULL);
   1667 	REQUIRE(event->ev_arg != NULL);
   1668 
   1669 	UNUSED(task);
   1670 	zone = (dns_rpz_zone_t *) event->ev_arg;
   1671 	isc_event_free(&event);
   1672 	LOCK(&zone->rpzs->maint_lock);
   1673 	zone->updatepending = false;
   1674 	zone->updaterunning = true;
   1675 	dns_rpz_update_from_db(zone);
   1676 	result = isc_timer_reset(zone->updatetimer, isc_timertype_inactive,
   1677 				 NULL, NULL, true);
   1678 	RUNTIME_CHECK(result == ISC_R_SUCCESS);
   1679 	result = isc_time_now(&zone->lastupdated);
   1680 	RUNTIME_CHECK(result == ISC_R_SUCCESS);
   1681 	UNLOCK(&zone->rpzs->maint_lock);
   1682 }
   1683 
   1684 static isc_result_t
   1685 setup_update(dns_rpz_zone_t *rpz) {
   1686 	isc_result_t result;
   1687 	char domain[DNS_NAME_FORMATSIZE];
   1688 	unsigned int nodecount;
   1689 	uint32_t hashsize;
   1690 
   1691 	dns_name_format(&rpz->origin, domain, DNS_NAME_FORMATSIZE);
   1692 	isc_log_write(dns_lctx, DNS_LOGCATEGORY_GENERAL,
   1693 		      DNS_LOGMODULE_MASTER, ISC_LOG_INFO,
   1694 		      "rpz: %s: reload start", domain);
   1695 
   1696 	nodecount = dns_db_nodecount(rpz->updb);
   1697 	hashsize = 1;
   1698 	while (nodecount != 0 &&
   1699 	       hashsize <= (DNS_RPZ_HTSIZE_MAX + DNS_RPZ_HTSIZE_DIV))
   1700 	{
   1701 		hashsize++;
   1702 		nodecount >>=1;
   1703 	}
   1704 
   1705 	if (hashsize > DNS_RPZ_HTSIZE_DIV)
   1706 		hashsize -= DNS_RPZ_HTSIZE_DIV;
   1707 
   1708 	isc_log_write(dns_lctx, DNS_LOGCATEGORY_GENERAL,
   1709 			      DNS_LOGMODULE_MASTER, ISC_LOG_DEBUG(1),
   1710 			      "rpz: %s: using hashtable size %d",
   1711 			      domain, hashsize);
   1712 
   1713 	result = isc_ht_init(&rpz->newnodes, rpz->rpzs->mctx, hashsize);
   1714 	if (result != ISC_R_SUCCESS) {
   1715 		isc_log_write(dns_lctx, DNS_LOGCATEGORY_GENERAL,
   1716 			      DNS_LOGMODULE_MASTER, ISC_LOG_ERROR,
   1717 			      "rpz: %s: failed to initialize hashtable - %s",
   1718 			      domain, isc_result_totext(result));
   1719 		goto cleanup;
   1720 	}
   1721 
   1722 	result = dns_db_createiterator(rpz->updb, DNS_DB_NONSEC3, &rpz->updbit);
   1723 	if (result != ISC_R_SUCCESS) {
   1724 		isc_log_write(dns_lctx, DNS_LOGCATEGORY_GENERAL,
   1725 			      DNS_LOGMODULE_MASTER, ISC_LOG_ERROR,
   1726 			      "rpz: %s: failed to create DB iterator - %s",
   1727 			      domain, isc_result_totext(result));
   1728 		goto cleanup;
   1729 	}
   1730 
   1731 	result = dns_dbiterator_first(rpz->updbit);
   1732 	if (result != ISC_R_SUCCESS) {
   1733 		isc_log_write(dns_lctx, DNS_LOGCATEGORY_GENERAL,
   1734 			      DNS_LOGMODULE_MASTER, ISC_LOG_ERROR,
   1735 			      "rpz: %s: failed to get db iterator - %s",
   1736 			      domain, isc_result_totext(result));
   1737 		goto cleanup;
   1738 	}
   1739 
   1740  cleanup:
   1741 	if (result != ISC_R_SUCCESS) {
   1742 		if (rpz->updbit != NULL)
   1743 			dns_dbiterator_destroy(&rpz->updbit);
   1744 		if (rpz->newnodes != NULL)
   1745 			isc_ht_destroy(&rpz->newnodes);
   1746 		dns_db_closeversion(rpz->updb, &rpz->updbversion, false);
   1747 	}
   1748 
   1749 	return (result);
   1750 }
   1751 
   1752 static void
   1753 finish_update(dns_rpz_zone_t *rpz) {
   1754 	isc_result_t result;
   1755 	isc_ht_t *tmpht = NULL;
   1756 	isc_ht_iter_t *iter = NULL;
   1757 	dns_fixedname_t fname;
   1758 	char dname[DNS_NAME_FORMATSIZE];
   1759 	dns_name_t *name;
   1760 
   1761 	/*
   1762 	 * Iterate over old ht with existing nodes deleted to delete
   1763 	 * deleted nodes from RPZ
   1764 	 */
   1765 	result = isc_ht_iter_create(rpz->nodes, &iter);
   1766 	if (result != ISC_R_SUCCESS) {
   1767 		char domain[DNS_NAME_FORMATSIZE];
   1768 
   1769 		dns_name_format(&rpz->origin, domain, DNS_NAME_FORMATSIZE);
   1770 		isc_log_write(dns_lctx, DNS_LOGCATEGORY_GENERAL,
   1771 			      DNS_LOGMODULE_MASTER, ISC_LOG_ERROR,
   1772 			      "rpz: %s: failed to create HT iterator - %s",
   1773 			      domain, isc_result_totext(result));
   1774 		goto cleanup;
   1775 	}
   1776 
   1777 	name = dns_fixedname_initname(&fname);
   1778 
   1779 	for (result = isc_ht_iter_first(iter);
   1780 	     result == ISC_R_SUCCESS;
   1781 	     result = isc_ht_iter_delcurrent_next(iter))
   1782 	{
   1783 		isc_region_t region;
   1784 		unsigned char *key = NULL;
   1785 		size_t keysize;
   1786 
   1787 		isc_ht_iter_currentkey(iter, &key, &keysize);
   1788 		region.base = key;
   1789 		region.length = (unsigned int)keysize;
   1790 		dns_name_fromregion(name, &region);
   1791 		dns_rpz_delete(rpz->rpzs, rpz->num, name);
   1792 	}
   1793 
   1794 	tmpht = rpz->nodes;
   1795 	rpz->nodes = rpz->newnodes;
   1796 	rpz->newnodes = tmpht;
   1797 
   1798 	LOCK(&rpz->rpzs->maint_lock);
   1799 	rpz->updaterunning = false;
   1800 	/*
   1801 	 * If there's an update pending schedule it
   1802 	 */
   1803 	if (rpz->updatepending == true) {
   1804 		if (rpz->min_update_interval > 0) {
   1805 			uint64_t defer = rpz->min_update_interval;
   1806 			isc_interval_t interval;
   1807 			dns_name_format(&rpz->origin, dname,
   1808 					DNS_NAME_FORMATSIZE);
   1809 			isc_log_write(dns_lctx, DNS_LOGCATEGORY_GENERAL,
   1810 				      DNS_LOGMODULE_MASTER, ISC_LOG_INFO,
   1811 				      "rpz: %s: new zone version came "
   1812 				      "too soon, deferring update for "
   1813 				      "%" PRIu64 " seconds", dname, defer);
   1814 			isc_interval_set(&interval, (unsigned int)defer, 0);
   1815 			isc_timer_reset(rpz->updatetimer, isc_timertype_once,
   1816 					NULL, &interval, true);
   1817 		} else {
   1818 			isc_event_t *event;
   1819 			INSIST(!ISC_LINK_LINKED(&rpz->updateevent, ev_link));
   1820 			ISC_EVENT_INIT(&rpz->updateevent,
   1821 				       sizeof(rpz->updateevent), 0, NULL,
   1822 				       DNS_EVENT_RPZUPDATED,
   1823 				       dns_rpz_update_taskaction,
   1824 				       rpz, rpz, NULL, NULL);
   1825 			event = &rpz->updateevent;
   1826 			isc_task_send(rpz->rpzs->updater, &event);
   1827 		}
   1828 	}
   1829 	UNLOCK(&rpz->rpzs->maint_lock);
   1830 
   1831 cleanup:
   1832 	if (iter != NULL)
   1833 		isc_ht_iter_destroy(&iter);
   1834 }
   1835 
   1836 static void
   1837 update_quantum(isc_task_t *task, isc_event_t *event) {
   1838 	isc_result_t result = ISC_R_SUCCESS;
   1839 	dns_dbnode_t *node = NULL;
   1840 	dns_rpz_zone_t *rpz;
   1841 	char domain[DNS_NAME_FORMATSIZE];
   1842 	dns_fixedname_t fixname;
   1843 	dns_name_t *name;
   1844 	int count = 0;
   1845 
   1846 	UNUSED(task);
   1847 
   1848 	REQUIRE(event != NULL);
   1849 	REQUIRE(event->ev_arg != NULL);
   1850 
   1851 	rpz = (dns_rpz_zone_t *) event->ev_arg;
   1852 	isc_event_free(&event);
   1853 
   1854 	REQUIRE(rpz->updbit != NULL);
   1855 	REQUIRE(rpz->newnodes != NULL);
   1856 
   1857 	name = dns_fixedname_initname(&fixname);
   1858 
   1859 	dns_name_format(&rpz->origin, domain, DNS_NAME_FORMATSIZE);
   1860 
   1861 	while (result == ISC_R_SUCCESS && count++ < DNS_RPZ_QUANTUM) {
   1862 		char namebuf[DNS_NAME_FORMATSIZE];
   1863 		dns_rdatasetiter_t *rdsiter = NULL;
   1864 
   1865 		result = dns_dbiterator_current(rpz->updbit, &node, name);
   1866 		if (result != ISC_R_SUCCESS) {
   1867 			isc_log_write(dns_lctx, DNS_LOGCATEGORY_GENERAL,
   1868 				      DNS_LOGMODULE_MASTER, ISC_LOG_ERROR,
   1869 				      "rpz: %s: failed to get dbiterator - %s",
   1870 				      domain, isc_result_totext(result));
   1871 			dns_db_detachnode(rpz->updb, &node);
   1872 			break;
   1873 		}
   1874 
   1875 		result = dns_db_allrdatasets(rpz->updb, node, rpz->updbversion,
   1876 					     0, &rdsiter);
   1877 		if (result != ISC_R_SUCCESS) {
   1878 			isc_log_write(dns_lctx, DNS_LOGCATEGORY_GENERAL,
   1879 				      DNS_LOGMODULE_MASTER, ISC_LOG_ERROR,
   1880 				      "rpz: %s: failed to fetch "
   1881 				      "rrdatasets - %s",
   1882 				      domain, isc_result_totext(result));
   1883 			dns_db_detachnode(rpz->updb, &node);
   1884 			break;
   1885 		}
   1886 
   1887 		result = dns_rdatasetiter_first(rdsiter);
   1888 		dns_rdatasetiter_destroy(&rdsiter);
   1889 		if (result != ISC_R_SUCCESS) { /* empty non-terminal */
   1890 			if (result != ISC_R_NOMORE)
   1891 				isc_log_write(dns_lctx, DNS_LOGCATEGORY_GENERAL,
   1892 				      DNS_LOGMODULE_MASTER, ISC_LOG_ERROR,
   1893 				      "rpz: %s: error %s while creating "
   1894 				      "rdatasetiter",
   1895 				      domain, isc_result_totext(result));
   1896 			dns_db_detachnode(rpz->updb, &node);
   1897 			result = dns_dbiterator_next(rpz->updbit);
   1898 			continue;
   1899 		}
   1900 
   1901 		result = isc_ht_add(rpz->newnodes, name->ndata,
   1902 				    name->length, rpz);
   1903 		if (result != ISC_R_SUCCESS) {
   1904 			dns_name_format(name, namebuf, sizeof(namebuf));
   1905 			isc_log_write(dns_lctx, DNS_LOGCATEGORY_GENERAL,
   1906 				      DNS_LOGMODULE_MASTER, ISC_LOG_ERROR,
   1907 				      "rpz: %s, adding node %s to HT error %s",
   1908 				      domain, namebuf,
   1909 				      isc_result_totext(result));
   1910 			dns_db_detachnode(rpz->updb, &node);
   1911 			result = dns_dbiterator_next(rpz->updbit);
   1912 			continue;
   1913 		}
   1914 
   1915 		result = isc_ht_find(rpz->nodes, name->ndata,
   1916 				     name->length, NULL);
   1917 		if (result == ISC_R_SUCCESS) {
   1918 			isc_ht_delete(rpz->nodes, name->ndata, name->length);
   1919 		} else { /* not found */
   1920 			result = dns_rpz_add(rpz->rpzs, rpz->num, name);
   1921 			if (result != ISC_R_SUCCESS) {
   1922 				dns_name_format(name, namebuf, sizeof(namebuf));
   1923 				isc_log_write(dns_lctx,
   1924 					      DNS_LOGCATEGORY_GENERAL,
   1925 					      DNS_LOGMODULE_MASTER,
   1926 					      ISC_LOG_ERROR,
   1927 					      "rpz: %s: adding node %s "
   1928 					      "to RPZ error %s",
   1929 					      domain, namebuf,
   1930 					      isc_result_totext(result));
   1931 			} else {
   1932 				dns_name_format(name, namebuf, sizeof(namebuf));
   1933 				isc_log_write(dns_lctx,
   1934 					      DNS_LOGCATEGORY_GENERAL,
   1935 					      DNS_LOGMODULE_MASTER,
   1936 					      ISC_LOG_DEBUG(3),
   1937 					      "rpz: %s: adding node %s",
   1938 					      domain, namebuf);
   1939 			}
   1940 		}
   1941 
   1942 		dns_db_detachnode(rpz->updb, &node);
   1943 		result = dns_dbiterator_next(rpz->updbit);
   1944 	}
   1945 
   1946 	if (result == ISC_R_SUCCESS) {
   1947 		isc_event_t *nevent;
   1948 		/*
   1949 		 * Pause the iterator so that the DB is not locked
   1950 		 */
   1951 		dns_dbiterator_pause(rpz->updbit);
   1952 		/*
   1953 		 * We finished a quantum; trigger the next one and return
   1954 		 */
   1955 		INSIST(!ISC_LINK_LINKED(&rpz->updateevent, ev_link));
   1956 		ISC_EVENT_INIT(&rpz->updateevent,
   1957 			       sizeof(rpz->updateevent), 0, NULL,
   1958 			       DNS_EVENT_RPZUPDATED,
   1959 			       update_quantum,
   1960 			       rpz, rpz, NULL, NULL);
   1961 		nevent = &rpz->updateevent;
   1962 		isc_task_send(rpz->rpzs->updater, &nevent);
   1963 		return;
   1964 	} else if (result == ISC_R_NOMORE) {
   1965 		/*
   1966 		 * All done.
   1967 		 */
   1968 		finish_update(rpz);
   1969 		isc_log_write(dns_lctx, DNS_LOGCATEGORY_GENERAL,
   1970 			      DNS_LOGMODULE_MASTER, ISC_LOG_INFO,
   1971 			      "rpz: %s: reload done", domain);
   1972 	}
   1973 
   1974 	/*
   1975 	 * If we're here, we've either finished or something went wrong,
   1976 	 * so clean up.
   1977 	 */
   1978 	if (rpz->updbit != NULL)
   1979 		dns_dbiterator_destroy(&rpz->updbit);
   1980 	if (rpz->newnodes != NULL)
   1981 		isc_ht_destroy(&rpz->newnodes);
   1982 	dns_db_closeversion(rpz->updb, &rpz->updbversion, false);
   1983 	dns_db_detach(&rpz->updb);
   1984 }
   1985 
   1986 static void
   1987 dns_rpz_update_from_db(dns_rpz_zone_t *rpz) {
   1988 	isc_result_t result;
   1989 	isc_event_t *event;
   1990 
   1991 	REQUIRE(rpz != NULL);
   1992 	REQUIRE(DNS_DB_VALID(rpz->db));
   1993 	REQUIRE(rpz->updb == NULL);
   1994 	REQUIRE(rpz->updbversion == NULL);
   1995 	REQUIRE(rpz->updbit == NULL);
   1996 	REQUIRE(rpz->newnodes == NULL);
   1997 
   1998 	dns_db_attach(rpz->db, &rpz->updb);
   1999 	rpz->updbversion = rpz->dbversion;
   2000 	rpz->dbversion = NULL;
   2001 
   2002 	result = setup_update(rpz);
   2003 	if (result != ISC_R_SUCCESS) {
   2004 		goto cleanup;
   2005 	}
   2006 
   2007 	event = &rpz->updateevent;
   2008 	INSIST(!ISC_LINK_LINKED(&rpz->updateevent, ev_link));
   2009 	ISC_EVENT_INIT(&rpz->updateevent, sizeof(rpz->updateevent),
   2010 		       0, NULL, DNS_EVENT_RPZUPDATED,
   2011 		       update_quantum, rpz, rpz, NULL, NULL);
   2012 	isc_task_send(rpz->rpzs->updater, &event);
   2013 	return;
   2014 
   2015  cleanup:
   2016 	if (rpz->updbit != NULL)
   2017 		dns_dbiterator_destroy(&rpz->updbit);
   2018 	if (rpz->newnodes != NULL)
   2019 		isc_ht_destroy(&rpz->newnodes);
   2020 	dns_db_closeversion(rpz->updb, &rpz->updbversion, false);
   2021 	dns_db_detach(&rpz->updb);
   2022 }
   2023 
   2024 /*
   2025  * Free the radix tree of a response policy database.
   2026  */
   2027 static void
   2028 cidr_free(dns_rpz_zones_t *rpzs) {
   2029 	dns_rpz_cidr_node_t *cur, *child, *parent;
   2030 
   2031 	cur = rpzs->cidr;
   2032 	while (cur != NULL) {
   2033 		/* Depth first. */
   2034 		child = cur->child[0];
   2035 		if (child != NULL) {
   2036 			cur = child;
   2037 			continue;
   2038 		}
   2039 		child = cur->child[1];
   2040 		if (child != NULL) {
   2041 			cur = child;
   2042 			continue;
   2043 		}
   2044 
   2045 		/* Delete this leaf and go up. */
   2046 		parent = cur->parent;
   2047 		if (parent == NULL)
   2048 			rpzs->cidr = NULL;
   2049 		else
   2050 			parent->child[parent->child[1] == cur] = NULL;
   2051 		isc_mem_put(rpzs->mctx, cur, sizeof(*cur));
   2052 		cur = parent;
   2053 	}
   2054 }
   2055 
   2056 /*
   2057  * Discard a response policy zone blob
   2058  * before discarding the overall rpz structure.
   2059  */
   2060 static void
   2061 rpz_detach(dns_rpz_zone_t **rpzp, dns_rpz_zones_t *rpzs) {
   2062 	dns_rpz_zone_t *rpz;
   2063 
   2064 	REQUIRE(rpzp != NULL && *rpzp != NULL);
   2065 
   2066 	rpz = *rpzp;
   2067 	*rpzp = NULL;
   2068 
   2069 	if (isc_refcount_decrement(&rpz->refs) != 1) {
   2070 		return;
   2071 	}
   2072 
   2073 	isc_refcount_destroy(&rpz->refs);
   2074 
   2075 	if (dns_name_dynamic(&rpz->origin)) {
   2076 		dns_name_free(&rpz->origin, rpzs->mctx);
   2077 	}
   2078 	if (dns_name_dynamic(&rpz->client_ip)) {
   2079 		dns_name_free(&rpz->client_ip, rpzs->mctx);
   2080 	}
   2081 	if (dns_name_dynamic(&rpz->ip)) {
   2082 		dns_name_free(&rpz->ip, rpzs->mctx);
   2083 	}
   2084 	if (dns_name_dynamic(&rpz->nsdname)) {
   2085 		dns_name_free(&rpz->nsdname, rpzs->mctx);
   2086 	}
   2087 	if (dns_name_dynamic(&rpz->nsip)) {
   2088 		dns_name_free(&rpz->nsip, rpzs->mctx);
   2089 	}
   2090 	if (dns_name_dynamic(&rpz->passthru)) {
   2091 		dns_name_free(&rpz->passthru, rpzs->mctx);
   2092 	}
   2093 	if (dns_name_dynamic(&rpz->drop)) {
   2094 		dns_name_free(&rpz->drop, rpzs->mctx);
   2095 	}
   2096 	if (dns_name_dynamic(&rpz->tcp_only)) {
   2097 		dns_name_free(&rpz->tcp_only, rpzs->mctx);
   2098 	}
   2099 	if (dns_name_dynamic(&rpz->cname)) {
   2100 		dns_name_free(&rpz->cname, rpzs->mctx);
   2101 	}
   2102 	if (rpz->db_registered) {
   2103 		dns_db_updatenotify_unregister(rpz->db,
   2104 					       dns_rpz_dbupdate_callback, rpz);
   2105 	}
   2106 	if (rpz->dbversion != NULL) {
   2107 		dns_db_closeversion(rpz->db, &rpz->dbversion, false);
   2108 	}
   2109 	if (rpz->db != NULL) {
   2110 		dns_db_detach(&rpz->db);
   2111 	}
   2112 	if (rpz->updaterunning) {
   2113 		isc_task_purgeevent(rpz->rpzs->updater, &rpz->updateevent);
   2114 		if (rpz->updbit != NULL) {
   2115 			dns_dbiterator_destroy(&rpz->updbit);
   2116 		}
   2117 		if (rpz->newnodes != NULL) {
   2118 			isc_ht_destroy(&rpz->newnodes);
   2119 		}
   2120 		dns_db_closeversion(rpz->updb, &rpz->updbversion, false);
   2121 		dns_db_detach(&rpz->updb);
   2122 	}
   2123 
   2124 	isc_timer_reset(rpz->updatetimer, isc_timertype_inactive,
   2125 			NULL, NULL, true);
   2126 	isc_timer_detach(&rpz->updatetimer);
   2127 
   2128 	isc_ht_destroy(&rpz->nodes);
   2129 	isc_mem_put(rpzs->mctx, rpz, sizeof(*rpz));
   2130 }
   2131 
   2132 void
   2133 dns_rpz_attach_rpzs(dns_rpz_zones_t *rpzs, dns_rpz_zones_t **rpzsp) {
   2134 	REQUIRE(rpzsp != NULL && *rpzsp == NULL);
   2135 	isc_refcount_increment(&rpzs->refs);
   2136 	*rpzsp = rpzs;
   2137 }
   2138 
   2139 /*
   2140  * Forget a view's policy zones.
   2141  */
   2142 void
   2143 dns_rpz_detach_rpzs(dns_rpz_zones_t **rpzsp) {
   2144 	REQUIRE(rpzsp != NULL && *rpzsp != NULL);
   2145 	dns_rpz_zones_t *rpzs = *rpzsp;
   2146 	*rpzsp = NULL;
   2147 
   2148 	if (isc_refcount_decrement(&rpzs->refs) == 1) {
   2149 		/*
   2150 		 * Destroy the task first, so that nothing runs
   2151 		 * in the background that might race with us.
   2152 		 */
   2153 		isc_task_destroy(&rpzs->updater);
   2154 
   2155 		/*
   2156 		 * Forget the last of view's rpz machinery after
   2157 		 * the last reference.
   2158 		 */
   2159 		for (dns_rpz_num_t rpz_num = 0;
   2160 		     rpz_num < DNS_RPZ_MAX_ZONES;
   2161 		     ++rpz_num)
   2162 		{
   2163 			dns_rpz_zone_t *rpz = rpzs->zones[rpz_num];
   2164 			rpzs->zones[rpz_num] = NULL;
   2165 			if (rpz != NULL) {
   2166 				rpz_detach(&rpz, rpzs);
   2167 			}
   2168 		}
   2169 
   2170 		if (rpzs->rps_cstr_size != 0) {
   2171 #ifdef USE_DNSRPS
   2172 			librpz->client_detach(&rpzs->rps_client);
   2173 #endif
   2174 			isc_mem_put(rpzs->mctx, rpzs->rps_cstr,
   2175 				    rpzs->rps_cstr_size);
   2176 		}
   2177 
   2178 		cidr_free(rpzs);
   2179 		if (rpzs->rbt != NULL) {
   2180 			dns_rbt_destroy(&rpzs->rbt);
   2181 		}
   2182 		isc_mutex_destroy(&rpzs->maint_lock);
   2183 		isc_rwlock_destroy(&rpzs->search_lock);
   2184 		isc_refcount_destroy(&rpzs->refs);
   2185 		isc_mem_putanddetach(&rpzs->mctx, rpzs, sizeof(*rpzs));
   2186 	}
   2187 }
   2188 
   2189 /*
   2190  * Deprecated and removed.
   2191  */
   2192 isc_result_t
   2193 dns_rpz_beginload(dns_rpz_zones_t **load_rpzsp,
   2194 		  dns_rpz_zones_t *rpzs, dns_rpz_num_t rpz_num)
   2195 {
   2196 	UNUSED(load_rpzsp);
   2197 	UNUSED(rpzs);
   2198 	UNUSED(rpz_num);
   2199 
   2200 	return (ISC_R_NOTIMPLEMENTED);
   2201 }
   2202 
   2203 /*
   2204  * Deprecated and removed.
   2205  */
   2206 isc_result_t
   2207 dns_rpz_ready(dns_rpz_zones_t *rpzs,
   2208 	      dns_rpz_zones_t **load_rpzsp, dns_rpz_num_t rpz_num)
   2209 {
   2210 	UNUSED(rpzs);
   2211 	UNUSED(load_rpzsp);
   2212 	UNUSED(rpz_num);
   2213 
   2214 	return (ISC_R_NOTIMPLEMENTED);
   2215 }
   2216 
   2217 /*
   2218  * Add an IP address to the radix tree or a name to the summary database.
   2219  */
   2220 isc_result_t
   2221 dns_rpz_add(dns_rpz_zones_t *rpzs, dns_rpz_num_t rpz_num,
   2222 	    const dns_name_t *src_name)
   2223 {
   2224 	dns_rpz_zone_t *rpz;
   2225 	dns_rpz_type_t rpz_type;
   2226 	isc_result_t result = ISC_R_FAILURE;
   2227 
   2228 	REQUIRE(rpzs != NULL && rpz_num < rpzs->p.num_zones);
   2229 	rpz = rpzs->zones[rpz_num];
   2230 	REQUIRE(rpz != NULL);
   2231 	RWLOCK(&rpzs->search_lock, isc_rwlocktype_write);
   2232 
   2233 	rpz_type = type_from_name(rpzs, rpz, src_name);
   2234 
   2235 
   2236 	switch (rpz_type) {
   2237 	case DNS_RPZ_TYPE_QNAME:
   2238 	case DNS_RPZ_TYPE_NSDNAME:
   2239 		result = add_name(rpzs, rpz_num, rpz_type, src_name);
   2240 		break;
   2241 	case DNS_RPZ_TYPE_CLIENT_IP:
   2242 	case DNS_RPZ_TYPE_IP:
   2243 	case DNS_RPZ_TYPE_NSIP:
   2244 		result = add_cidr(rpzs, rpz_num, rpz_type, src_name);
   2245 		break;
   2246 	case DNS_RPZ_TYPE_BAD:
   2247 		break;
   2248 	}
   2249 	RWUNLOCK(&rpzs->search_lock, isc_rwlocktype_write);
   2250 
   2251 	return (result);
   2252 }
   2253 
   2254 /*
   2255  * Remove an IP address from the radix tree.
   2256  */
   2257 static void
   2258 del_cidr(dns_rpz_zones_t *rpzs, dns_rpz_num_t rpz_num,
   2259 	 dns_rpz_type_t rpz_type, const dns_name_t *src_name)
   2260 {
   2261 	isc_result_t result;
   2262 	dns_rpz_cidr_key_t tgt_ip;
   2263 	dns_rpz_prefix_t tgt_prefix;
   2264 	dns_rpz_addr_zbits_t tgt_set;
   2265 	dns_rpz_cidr_node_t *tgt, *parent, *child;
   2266 
   2267 	/*
   2268 	 * Do not worry about invalid rpz IP address names.  If we
   2269 	 * are here, then something relevant was added and so was
   2270 	 * valid.  Invalid names here are usually internal RBTDB nodes.
   2271 	 */
   2272 	result = name2ipkey(DNS_RPZ_DEBUG_QUIET, rpzs, rpz_num, rpz_type,
   2273 			    src_name, &tgt_ip, &tgt_prefix, &tgt_set);
   2274 	if (result != ISC_R_SUCCESS)
   2275 		return;
   2276 
   2277 	result = search(rpzs, &tgt_ip, tgt_prefix, &tgt_set, false, &tgt);
   2278 	if (result != ISC_R_SUCCESS) {
   2279 		INSIST(result == ISC_R_NOTFOUND ||
   2280 		       result == DNS_R_PARTIALMATCH);
   2281 		/*
   2282 		 * Do not worry about missing summary RBT nodes that probably
   2283 		 * correspond to RBTDB nodes that were implicit RBT nodes
   2284 		 * that were later added for (often empty) wildcards
   2285 		 * and then to the RBTDB deferred cleanup list.
   2286 		 */
   2287 		return;
   2288 	}
   2289 
   2290 	/*
   2291 	 * Mark the node and its parents to reflect the deleted IP address.
   2292 	 * Do not count bits that are already clear for internal RBTDB nodes.
   2293 	 */
   2294 	tgt_set.client_ip &= tgt->set.client_ip;
   2295 	tgt_set.ip &= tgt->set.ip;
   2296 	tgt_set.nsip &= tgt->set.nsip;
   2297 	tgt->set.client_ip &= ~tgt_set.client_ip;
   2298 	tgt->set.ip &= ~tgt_set.ip;
   2299 	tgt->set.nsip &= ~tgt_set.nsip;
   2300 	set_sum_pair(tgt);
   2301 
   2302 	adj_trigger_cnt(rpzs, rpz_num, rpz_type, &tgt_ip, tgt_prefix,
   2303 			false);
   2304 
   2305 	/*
   2306 	 * We might need to delete 2 nodes.
   2307 	 */
   2308 	do {
   2309 		/*
   2310 		 * The node is now useless if it has no data of its own
   2311 		 * and 0 or 1 children.  We are finished if it is not useless.
   2312 		 */
   2313 		if ((child = tgt->child[0]) != NULL) {
   2314 			if (tgt->child[1] != NULL)
   2315 				break;
   2316 		} else {
   2317 			child = tgt->child[1];
   2318 		}
   2319 		if (tgt->set.client_ip != 0 ||
   2320 		    tgt->set.ip != 0 ||
   2321 		    tgt->set.nsip != 0)
   2322 			break;
   2323 
   2324 		/*
   2325 		 * Replace the pointer to this node in the parent with
   2326 		 * the remaining child or NULL.
   2327 		 */
   2328 		parent = tgt->parent;
   2329 		if (parent == NULL) {
   2330 			rpzs->cidr = child;
   2331 		} else {
   2332 			parent->child[parent->child[1] == tgt] = child;
   2333 		}
   2334 		/*
   2335 		 * If the child exists fix up its parent pointer.
   2336 		 */
   2337 		if (child != NULL)
   2338 			child->parent = parent;
   2339 		isc_mem_put(rpzs->mctx, tgt, sizeof(*tgt));
   2340 
   2341 		tgt = parent;
   2342 	} while (tgt != NULL);
   2343 }
   2344 
   2345 static void
   2346 del_name(dns_rpz_zones_t *rpzs, dns_rpz_num_t rpz_num,
   2347 	 dns_rpz_type_t rpz_type, const dns_name_t *src_name)
   2348 {
   2349 	char namebuf[DNS_NAME_FORMATSIZE];
   2350 	dns_fixedname_t trig_namef;
   2351 	dns_name_t *trig_name;
   2352 	dns_rbtnode_t *nmnode;
   2353 	dns_rpz_nm_data_t *nm_data, del_data;
   2354 	isc_result_t result;
   2355 	bool exists;
   2356 
   2357 	/*
   2358 	 * We need a summary database of names even with 1 policy zone,
   2359 	 * because wildcard triggers are handled differently.
   2360 	 */
   2361 
   2362 	trig_name = dns_fixedname_initname(&trig_namef);
   2363 	name2data(rpzs, rpz_num, rpz_type, src_name, trig_name, &del_data);
   2364 
   2365 	nmnode = NULL;
   2366 	result = dns_rbt_findnode(rpzs->rbt, trig_name, NULL, &nmnode, NULL, 0,
   2367 				  NULL, NULL);
   2368 	if (result != ISC_R_SUCCESS) {
   2369 		/*
   2370 		 * Do not worry about missing summary RBT nodes that probably
   2371 		 * correspond to RBTDB nodes that were implicit RBT nodes
   2372 		 * that were later added for (often empty) wildcards
   2373 		 * and then to the RBTDB deferred cleanup list.
   2374 		 */
   2375 		if (result == ISC_R_NOTFOUND ||
   2376 		    result == DNS_R_PARTIALMATCH)
   2377 			return;
   2378 		dns_name_format(src_name, namebuf, sizeof(namebuf));
   2379 		isc_log_write(dns_lctx, DNS_LOGCATEGORY_RPZ,
   2380 			      DNS_LOGMODULE_RBTDB, DNS_RPZ_ERROR_LEVEL,
   2381 			      "rpz del_name(%s) node search failed: %s",
   2382 			      namebuf, isc_result_totext(result));
   2383 		return;
   2384 	}
   2385 
   2386 	nm_data = nmnode->data;
   2387 	INSIST(nm_data != NULL);
   2388 
   2389 	/*
   2390 	 * Do not count bits that next existed for RBT nodes that would we
   2391 	 * would not have found in a summary for a single RBTDB tree.
   2392 	 */
   2393 	del_data.set.qname &= nm_data->set.qname;
   2394 	del_data.set.ns &= nm_data->set.ns;
   2395 	del_data.wild.qname &= nm_data->wild.qname;
   2396 	del_data.wild.ns &= nm_data->wild.ns;
   2397 
   2398 	exists = (del_data.set.qname != 0 || del_data.set.ns != 0 ||
   2399 		  del_data.wild.qname != 0 || del_data.wild.ns != 0);
   2400 
   2401 	nm_data->set.qname &= ~del_data.set.qname;
   2402 	nm_data->set.ns &= ~del_data.set.ns;
   2403 	nm_data->wild.qname &= ~del_data.wild.qname;
   2404 	nm_data->wild.ns &= ~del_data.wild.ns;
   2405 
   2406 	if (nm_data->set.qname == 0 && nm_data->set.ns == 0 &&
   2407 	    nm_data->wild.qname == 0 && nm_data->wild.ns == 0) {
   2408 		result = dns_rbt_deletenode(rpzs->rbt, nmnode, false);
   2409 		if (result != ISC_R_SUCCESS) {
   2410 			/*
   2411 			 * bin/tests/system/rpz/tests.sh looks for
   2412 			 * "rpz.*failed".
   2413 			 */
   2414 			dns_name_format(src_name, namebuf, sizeof(namebuf));
   2415 			isc_log_write(dns_lctx, DNS_LOGCATEGORY_RPZ,
   2416 				      DNS_LOGMODULE_RBTDB, DNS_RPZ_ERROR_LEVEL,
   2417 				      "rpz del_name(%s) node delete failed: %s",
   2418 				      namebuf, isc_result_totext(result));
   2419 		}
   2420 	}
   2421 
   2422 	if (exists)
   2423 		adj_trigger_cnt(rpzs, rpz_num, rpz_type, NULL, 0, false);
   2424 }
   2425 
   2426 /*
   2427  * Remove an IP address from the radix tree or a name from the summary database.
   2428  */
   2429 void
   2430 dns_rpz_delete(dns_rpz_zones_t *rpzs, dns_rpz_num_t rpz_num,
   2431 	       const dns_name_t *src_name)
   2432 {
   2433 	dns_rpz_zone_t *rpz;
   2434 	dns_rpz_type_t rpz_type;
   2435 
   2436 	REQUIRE(rpzs != NULL && rpz_num < rpzs->p.num_zones);
   2437 	rpz = rpzs->zones[rpz_num];
   2438 	REQUIRE(rpz != NULL);
   2439 
   2440 	RWLOCK(&rpzs->search_lock, isc_rwlocktype_write);
   2441 
   2442 	rpz_type = type_from_name(rpzs, rpz, src_name);
   2443 
   2444 	switch (rpz_type) {
   2445 	case DNS_RPZ_TYPE_QNAME:
   2446 	case DNS_RPZ_TYPE_NSDNAME:
   2447 		del_name(rpzs, rpz_num, rpz_type, src_name);
   2448 		break;
   2449 	case DNS_RPZ_TYPE_CLIENT_IP:
   2450 	case DNS_RPZ_TYPE_IP:
   2451 	case DNS_RPZ_TYPE_NSIP:
   2452 		del_cidr(rpzs, rpz_num, rpz_type, src_name);
   2453 		break;
   2454 	case DNS_RPZ_TYPE_BAD:
   2455 		break;
   2456 	}
   2457 
   2458 	RWUNLOCK(&rpzs->search_lock, isc_rwlocktype_write);
   2459 }
   2460 
   2461 /*
   2462  * Search the summary radix tree to get a relative owner name in a
   2463  * policy zone relevant to a triggering IP address.
   2464  *	rpz_type and zbits limit the search for IP address netaddr
   2465  *	return the policy zone's number or DNS_RPZ_INVALID_NUM
   2466  *	ip_name is the relative owner name found and
   2467  *	*prefixp is its prefix length.
   2468  */
   2469 dns_rpz_num_t
   2470 dns_rpz_find_ip(dns_rpz_zones_t *rpzs, dns_rpz_type_t rpz_type,
   2471 		dns_rpz_zbits_t zbits, const isc_netaddr_t *netaddr,
   2472 		dns_name_t *ip_name, dns_rpz_prefix_t *prefixp)
   2473 {
   2474 	dns_rpz_cidr_key_t tgt_ip;
   2475 	dns_rpz_addr_zbits_t tgt_set;
   2476 	dns_rpz_cidr_node_t *found;
   2477 	isc_result_t result;
   2478 	dns_rpz_num_t rpz_num = 0;
   2479 	dns_rpz_have_t have;
   2480 	int i;
   2481 
   2482 	RWLOCK(&rpzs->search_lock, isc_rwlocktype_read);
   2483 	have = rpzs->have;
   2484 	RWUNLOCK(&rpzs->search_lock, isc_rwlocktype_read);
   2485 
   2486 	/*
   2487 	 * Convert IP address to CIDR tree key.
   2488 	 */
   2489 	if (netaddr->family == AF_INET) {
   2490 		tgt_ip.w[0] = 0;
   2491 		tgt_ip.w[1] = 0;
   2492 		tgt_ip.w[2] = ADDR_V4MAPPED;
   2493 		tgt_ip.w[3] = ntohl(netaddr->type.in.s_addr);
   2494 		switch (rpz_type) {
   2495 		case DNS_RPZ_TYPE_CLIENT_IP:
   2496 			zbits &= have.client_ipv4;
   2497 			break;
   2498 		case DNS_RPZ_TYPE_IP:
   2499 			zbits &= have.ipv4;
   2500 			break;
   2501 		case DNS_RPZ_TYPE_NSIP:
   2502 			zbits &= have.nsipv4;
   2503 			break;
   2504 		default:
   2505 			INSIST(0);
   2506 			break;
   2507 		}
   2508 	} else if (netaddr->family == AF_INET6) {
   2509 		dns_rpz_cidr_key_t src_ip6;
   2510 
   2511 		/*
   2512 		 * Given the int aligned struct in_addr member of netaddr->type
   2513 		 * one could cast netaddr->type.in6 to dns_rpz_cidr_key_t *,
   2514 		 * but some people object.
   2515 		 */
   2516 		memmove(src_ip6.w, &netaddr->type.in6, sizeof(src_ip6.w));
   2517 		for (i = 0; i < 4; i++) {
   2518 			tgt_ip.w[i] = ntohl(src_ip6.w[i]);
   2519 		}
   2520 		switch (rpz_type) {
   2521 		case DNS_RPZ_TYPE_CLIENT_IP:
   2522 			zbits &= have.client_ipv6;
   2523 			break;
   2524 		case DNS_RPZ_TYPE_IP:
   2525 			zbits &= have.ipv6;
   2526 			break;
   2527 		case DNS_RPZ_TYPE_NSIP:
   2528 			zbits &= have.nsipv6;
   2529 			break;
   2530 		default:
   2531 			INSIST(0);
   2532 			break;
   2533 		}
   2534 	} else {
   2535 		return (DNS_RPZ_INVALID_NUM);
   2536 	}
   2537 
   2538 	if (zbits == 0)
   2539 		return (DNS_RPZ_INVALID_NUM);
   2540 	make_addr_set(&tgt_set, zbits, rpz_type);
   2541 
   2542 	RWLOCK(&rpzs->search_lock, isc_rwlocktype_read);
   2543 	result = search(rpzs, &tgt_ip, 128, &tgt_set, false, &found);
   2544 	if (result == ISC_R_NOTFOUND) {
   2545 		/*
   2546 		 * There are no eligible zones for this IP address.
   2547 		 */
   2548 		RWUNLOCK(&rpzs->search_lock, isc_rwlocktype_read);
   2549 		return (DNS_RPZ_INVALID_NUM);
   2550 	}
   2551 
   2552 	/*
   2553 	 * Construct the trigger name for the longest matching trigger
   2554 	 * in the first eligible zone with a match.
   2555 	 */
   2556 	*prefixp = found->prefix;
   2557 	switch (rpz_type) {
   2558 	case DNS_RPZ_TYPE_CLIENT_IP:
   2559 		rpz_num = zbit_to_num(found->set.client_ip & tgt_set.client_ip);
   2560 		break;
   2561 	case DNS_RPZ_TYPE_IP:
   2562 		rpz_num = zbit_to_num(found->set.ip & tgt_set.ip);
   2563 		break;
   2564 	case DNS_RPZ_TYPE_NSIP:
   2565 		rpz_num = zbit_to_num(found->set.nsip & tgt_set.nsip);
   2566 		break;
   2567 	default:
   2568 		INSIST(0);
   2569 		ISC_UNREACHABLE();
   2570 	}
   2571 	result = ip2name(&found->ip, found->prefix, dns_rootname, ip_name);
   2572 	RWUNLOCK(&rpzs->search_lock, isc_rwlocktype_read);
   2573 	if (result != ISC_R_SUCCESS) {
   2574 		/*
   2575 		 * bin/tests/system/rpz/tests.sh looks for "rpz.*failed".
   2576 		 */
   2577 		isc_log_write(dns_lctx, DNS_LOGCATEGORY_RPZ,
   2578 			      DNS_LOGMODULE_RBTDB, DNS_RPZ_ERROR_LEVEL,
   2579 			      "rpz ip2name() failed: %s",
   2580 			      isc_result_totext(result));
   2581 		return (DNS_RPZ_INVALID_NUM);
   2582 	}
   2583 	return (rpz_num);
   2584 }
   2585 
   2586 /*
   2587  * Search the summary radix tree for policy zones with triggers matching
   2588  * a name.
   2589  */
   2590 dns_rpz_zbits_t
   2591 dns_rpz_find_name(dns_rpz_zones_t *rpzs, dns_rpz_type_t rpz_type,
   2592 		  dns_rpz_zbits_t zbits, dns_name_t *trig_name)
   2593 {
   2594 	char namebuf[DNS_NAME_FORMATSIZE];
   2595 	dns_rbtnode_t *nmnode;
   2596 	const dns_rpz_nm_data_t *nm_data;
   2597 	dns_rpz_zbits_t found_zbits;
   2598 	isc_result_t result;
   2599 
   2600 	if (zbits == 0)
   2601 		return (0);
   2602 
   2603 	found_zbits = 0;
   2604 
   2605 	RWLOCK(&rpzs->search_lock, isc_rwlocktype_read);
   2606 
   2607 	nmnode = NULL;
   2608 	result = dns_rbt_findnode(rpzs->rbt, trig_name, NULL, &nmnode, NULL,
   2609 				  DNS_RBTFIND_EMPTYDATA, NULL, NULL);
   2610 	switch (result) {
   2611 	case ISC_R_SUCCESS:
   2612 		nm_data = nmnode->data;
   2613 		if (nm_data != NULL) {
   2614 			if (rpz_type == DNS_RPZ_TYPE_QNAME)
   2615 				found_zbits = nm_data->set.qname;
   2616 			else
   2617 				found_zbits = nm_data->set.ns;
   2618 		}
   2619 		nmnode = nmnode->parent;
   2620 		/* fall thru */
   2621 	case DNS_R_PARTIALMATCH:
   2622 		while (nmnode != NULL) {
   2623 			nm_data = nmnode->data;
   2624 			if (nm_data != NULL) {
   2625 				if (rpz_type == DNS_RPZ_TYPE_QNAME)
   2626 					found_zbits |= nm_data->wild.qname;
   2627 				else
   2628 					found_zbits |= nm_data->wild.ns;
   2629 			}
   2630 			nmnode = nmnode->parent;
   2631 		}
   2632 		break;
   2633 
   2634 	case ISC_R_NOTFOUND:
   2635 		break;
   2636 
   2637 	default:
   2638 		/*
   2639 		 * bin/tests/system/rpz/tests.sh looks for "rpz.*failed".
   2640 		 */
   2641 		dns_name_format(trig_name, namebuf, sizeof(namebuf));
   2642 		isc_log_write(dns_lctx, DNS_LOGCATEGORY_RPZ,
   2643 			      DNS_LOGMODULE_RBTDB, DNS_RPZ_ERROR_LEVEL,
   2644 			      "dns_rpz_find_name(%s) failed: %s",
   2645 			      namebuf, isc_result_totext(result));
   2646 		break;
   2647 	}
   2648 
   2649 	RWUNLOCK(&rpzs->search_lock, isc_rwlocktype_read);
   2650 	return (zbits & found_zbits);
   2651 }
   2652 
   2653 /*
   2654  * Translate CNAME rdata to a QNAME response policy action.
   2655  */
   2656 dns_rpz_policy_t
   2657 dns_rpz_decode_cname(dns_rpz_zone_t *rpz, dns_rdataset_t *rdataset,
   2658 		     dns_name_t *selfname)
   2659 {
   2660 	dns_rdata_t rdata = DNS_RDATA_INIT;
   2661 	dns_rdata_cname_t cname;
   2662 	isc_result_t result;
   2663 
   2664 	result = dns_rdataset_first(rdataset);
   2665 	INSIST(result == ISC_R_SUCCESS);
   2666 	dns_rdataset_current(rdataset, &rdata);
   2667 	result = dns_rdata_tostruct(&rdata, &cname, NULL);
   2668 	INSIST(result == ISC_R_SUCCESS);
   2669 	dns_rdata_reset(&rdata);
   2670 
   2671 	/*
   2672 	 * CNAME . means NXDOMAIN
   2673 	 */
   2674 	if (dns_name_equal(&cname.cname, dns_rootname))
   2675 		return (DNS_RPZ_POLICY_NXDOMAIN);
   2676 
   2677 	if (dns_name_iswildcard(&cname.cname)) {
   2678 		/*
   2679 		 * CNAME *. means NODATA
   2680 		 */
   2681 		if (dns_name_countlabels(&cname.cname) == 2)
   2682 			return (DNS_RPZ_POLICY_NODATA);
   2683 
   2684 		/*
   2685 		 * A qname of www.evil.com and a policy of
   2686 		 *	*.evil.com    CNAME   *.garden.net
   2687 		 * gives a result of
   2688 		 *	evil.com    CNAME   evil.com.garden.net
   2689 		 */
   2690 		if (dns_name_countlabels(&cname.cname) > 2)
   2691 			return (DNS_RPZ_POLICY_WILDCNAME);
   2692 	}
   2693 
   2694 	/*
   2695 	 * CNAME rpz-tcp-only. means "send truncated UDP responses."
   2696 	 */
   2697 	if (dns_name_equal(&cname.cname, &rpz->tcp_only))
   2698 		return (DNS_RPZ_POLICY_TCP_ONLY);
   2699 
   2700 	/*
   2701 	 * CNAME rpz-drop. means "do not respond."
   2702 	 */
   2703 	if (dns_name_equal(&cname.cname, &rpz->drop))
   2704 		return (DNS_RPZ_POLICY_DROP);
   2705 
   2706 	/*
   2707 	 * CNAME rpz-passthru. means "do not rewrite."
   2708 	 */
   2709 	if (dns_name_equal(&cname.cname, &rpz->passthru))
   2710 		return (DNS_RPZ_POLICY_PASSTHRU);
   2711 
   2712 	/*
   2713 	 * 128.1.0.127.rpz-ip CNAME  128.1.0.0.127. is obsolete PASSTHRU
   2714 	 */
   2715 	if (selfname != NULL && dns_name_equal(&cname.cname, selfname))
   2716 		return (DNS_RPZ_POLICY_PASSTHRU);
   2717 
   2718 	/*
   2719 	 * Any other rdata gives a response consisting of the rdata.
   2720 	 */
   2721 	return (DNS_RPZ_POLICY_RECORD);
   2722 }
   2723