24f315
diff --git a/lib/dns/resolver.c b/lib/dns/resolver.c
24f315
index 252a02f..bfffb8a 100644
24f315
--- a/lib/dns/resolver.c
24f315
+++ b/lib/dns/resolver.c
24f315
@@ -5957,6 +5957,7 @@ is_answertarget_allowed(fetchctx_t *fctx, dns_name_t *qname, dns_name_t *rname,
24f315
 	unsigned int nlabels;
24f315
 	dns_fixedname_t fixed;
24f315
 	dns_name_t prefix;
24f315
+	int order;
24f315
 
24f315
 	REQUIRE(rdataset != NULL);
24f315
 	REQUIRE(rdataset->type == dns_rdatatype_cname ||
24f315
@@ -5979,18 +5980,26 @@ is_answertarget_allowed(fetchctx_t *fctx, dns_name_t *qname, dns_name_t *rname,
24f315
 		tname = &cname.cname;
24f315
 		break;
24f315
 	case dns_rdatatype_dname:
24f315
+		if (dns_name_fullcompare(qname, rname, &order, &nlabels) !=
24f315
+		    dns_namereln_subdomain)
24f315
+		{
24f315
+			return (ISC_TRUE);
24f315
+		}
24f315
 		result = dns_rdata_tostruct(&rdata, &dname, NULL);
24f315
 		RUNTIME_CHECK(result == ISC_R_SUCCESS);
24f315
 		dns_name_init(&prefix, NULL);
24f315
 		dns_fixedname_init(&fixed);
24f315
 		tname = dns_fixedname_name(&fixed);
24f315
-		nlabels = dns_name_countlabels(qname) -
24f315
-			  dns_name_countlabels(rname);
24f315
+		nlabels = dns_name_countlabels(rname);
24f315
 		dns_name_split(qname, nlabels, &prefix, NULL);
24f315
 		result = dns_name_concatenate(&prefix, &dname.dname, tname,
24f315
 					      NULL);
24f315
-		if (result == DNS_R_NAMETOOLONG)
24f315
+		if (result == DNS_R_NAMETOOLONG) {
24f315
+			if (chainingp != NULL) {
24f315
+				*chainingp = ISC_TRUE;
24f315
+			}
24f315
 			return (ISC_TRUE);
24f315
+		}
24f315
 		RUNTIME_CHECK(result == ISC_R_SUCCESS);
24f315
 		break;
24f315
 	default:
24f315
@@ -6719,7 +6728,9 @@ answer_response(fetchctx_t *fctx) {
24f315
 		}
24f315
 		if ((ardataset->type == dns_rdatatype_cname ||
24f315
 		     ardataset->type == dns_rdatatype_dname) &&
24f315
-		     !is_answertarget_allowed(fctx, qname, aname, ardataset,
24f315
+		    type != ardataset->type &&
24f315
+		    type != dns_rdatatype_any &&
24f315
+		    !is_answertarget_allowed(fctx, qname, aname, ardataset,
24f315
 					      NULL))
24f315
 		{
24f315
 			return (DNS_R_SERVFAIL);