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