74b53c
From 2bdcb7159b1ac097355e95864e979b4f68bc1a4e Mon Sep 17 00:00:00 2001
854458
From: =?UTF-8?q?Petr=20Men=C5=A1=C3=ADk?= <pemensik@redhat.com>
854458
Date: Thu, 7 Nov 2019 14:31:03 +0100
854458
Subject: [PATCH] Implement serve-stale in 9.11
854458
MIME-Version: 1.0
854458
Content-Type: text/plain; charset=UTF-8
854458
Content-Transfer-Encoding: 8bit
854458
854458
Squashed commit of the following:
854458
854458
commit 32f47f36e545223b2a4757588d7bd4af8c5f5760
854458
Author: Petr Menšík <pemensik@redhat.com>
854458
Date:   Tue Sep 3 18:45:54 2019 +0200
854458
854458
    convert serve_stale to db_test
854458
854458
    Manual checkout from commit e8f61dd315c5d1c88915bb79361182241e42e47a.
854458
    Use test modified for cmocka, including serve-stale tests.
854458
854458
commit 071eb1fb0786f6d614955813d99c3caabff33383
854458
Author: Michał Kępień <michal@isc.org>
854458
Date:   Fri Apr 27 09:13:26 2018 +0200
854458
854458
    Detect recursion loops during query processing
854458
854458
    Interrupt query processing when query_recurse() attempts to ask the same
854458
    name servers for the same QNAME/QTYPE tuple for two times in a row as
854458
    this indicates that query processing may be stuck for an indeterminate
854458
    period of time, e.g. due to interactions between features able to
854458
    restart query_lookup().
854458
854458
    (cherry picked from commit 46bb4dd124ed031d4c219d1e37a3c6322092e30c)
854458
854458
commit c12090bc361c7fa4522ace73899e778e44e9b295
854458
Author: Petr Menšík <pemensik@redhat.com>
854458
Date:   Mon Sep 2 11:12:32 2019 +0200
854458
854458
    Fix test name used in whole test-suite
854458
854458
    Correct name is serve-stale
854458
854458
commit ff4d826f295d268a248ca06941d65c903e1b405c
854458
Author: Petr Menšík <pemensik@redhat.com>
854458
Date:   Fri Aug 30 17:43:28 2019 +0200
854458
854458
    Clean files in more generic rules
854458
854458
commit 8d81ed15eda9a2a11e1433d1fdddacfc772708b6
854458
Author: Petr Menšík <pemensik@redhat.com>
854458
Date:   Thu Aug 29 21:27:57 2019 +0200
854458
854458
    [rt46602] Pass port numbers to tests via environment variables
854458
854458
    Manually applied commit f5d8f079008b648d2e343543e66dd728054c6101
854458
854458
commit 94fafa477891576286def8c4041ad127734af2d1
854458
Author: Tony Finch <dot@dotat.at>
854458
Date:   Tue Apr 10 16:17:57 2018 +0100
854458
854458
    Move serve-stale logging to its own category, so that its verbosity can be curtailed.
854458
854458
    (cherry picked from commit 4b442c309dfb2c8880b19af4133047655bb734df)
854458
854458
commit e0c884bee98c3d2533dfaa667f58c6a80d8a3a00
854458
Author: Michał Kępień <michal@isc.org>
854458
Date:   Fri Apr 27 09:13:26 2018 +0200
854458
854458
    Prevent check_stale_header() from leaking rdataset headers
854458
854458
    check_stale_header() fails to update the pointer to the previous header
854458
    while processing rdataset headers eligible for serve-stale, thus
854458
    enabling rdataset headers to be leaked (i.e. disassociated from a node
854458
    and left on the relevant TTL heap) while iterating through a node.  This
854458
    can lead to several different assertion failures.  Add the missing
854458
    pointer update.
854458
854458
    (cherry picked from commit 391fac1fc8d2e470287b5cc4344b3adb90c6f54a)
854458
854458
commit d724cc1d80ee8d46113eaf82549d49636739b67c
854458
Author: Matthijs Mekking <matthijs@isc.org>
854458
Date:   Thu Jan 24 10:24:44 2019 +0100
854458
854458
    Print in dump-file stale ttl
854458
854458
    This change makes rndc dumpdb correctly print the "; stale" line.
854458
    It also provides extra information on how long this data may still
854458
    be served to clients (in other words how long the stale RRset may
854458
    still be used).
854458
854458
    (cherry picked from commit 924ebc605db798e2a383ee5eaaebad739e7c789c)
854458
854458
commit 625da4bd4590ac6108bb30eddd23ceffb245ae49
854458
Author: Michał Kępień <michal@isc.org>
854458
Date:   Mon Oct 22 15:26:45 2018 +0200
854458
854458
    Check serve-stale behavior with a cold cache
854458
854458
    Ensure that serve-stale works as expected when returning stale answers
854458
    is enabled, the authoritative server does not respond, and there is no
854458
    cached answer available.
854458
854458
    (cherry picked from commit 27cfe83a388147edfa0451b28c06c746912ea684)
854458
854458
commit d67ae10461c409fdafdbbe64f857db2552b71059
854458
Author: Michał Kępień <michal@isc.org>
854458
Date:   Mon Oct 22 15:26:45 2018 +0200
854458
854458
    Check TTL of stale answers
854458
854458
    Make sure that stale answers returned when the serve-stale feature is
854458
    enabled have a TTL matching the value of the stale-answer-ttl setting.
854458
854458
    (cherry picked from commit 893ab37ce78c658215bd3a019f25afe795b37d5a)
854458
854458
commit 50459107805e68e4a63a8e497bf58ef3ce013ddb
854458
Author: Michał Kępień <michal@isc.org>
854458
Date:   Mon Jul 9 14:35:12 2018 +0200
854458
854458
    Do not use Net::DNS::Nameserver in the "serve-stale" system test
854458
854458
    Net::DNS versions older than 0.67 respond to queries sent to a
854458
    Net::DNS::Nameserver even if its ReplyHandler returns undef.  This makes
854458
    the "serve-stale" system test fail as it takes advantage of the newer
854458
    behavior.  Since the latest Net::DNS version available with stock
854458
    RHEL/CentOS 6 packages is 0.65 and we officially support that operating
854458
    system, bin/tests/system/serve-stale/ans2/ans.pl should behave
854458
    consistently for various Net::DNS versions.  Ensure that by reworking it
854458
    so that it does not use Net::DNS::Nameserver.
854458
854458
    (cherry picked from commit c4209418a50c09142375f7edadca731c526f3d3a)
854458
854458
commit 4b5befc714bb386bd245b1c14ce3bce5ae6fb5fa
854458
Author: Petr Menšík <pemensik@redhat.com>
854458
Date:   Tue Jun 5 21:38:29 2018 +0200
854458
854458
    Fix server-stale requirement, skip without Time::HiRes
854458
854458
    (cherry picked from commit 7a0c7bf9c8e6a724e52635eed213ad25b9504e66)
854458
854458
commit 5ce51a3a7e5ef3087c4d022e3fca42fb2fd0c996
854458
Author: Ondřej Surý <ondrej@sury.org>
854458
Date:   Wed Oct 18 13:01:14 2017 +0200
854458
854458
    [rt46602] Update server-stale test to run on port passed from run.sh script
854458
854458
    (cherry picked from commit f83ebd34b9555a5a834c58146035173bcbd01dda)
854458
854458
commit 3954a9bf3437f6fab050294a7f2f954a23d161ec
854458
Author: Ondřej Surý <ondrej@sury.org>
854458
Date:   Wed Oct 18 14:18:59 2017 +0200
854458
854458
    [rt46602] Add serve-stale working files to .gitignore
854458
854458
    (cherry picked from commit cba162e70e7fac43435a606106841a69ce468526)
854458
854458
commit 112aa21f5fa875494820e4d1eb70e41e10e1aae7
854458
Author: Mark Andrews <marka@isc.org>
854458
Date:   Thu Oct 12 15:33:47 2017 +1100
854458
854458
    test for Net::DNS::Nameserver
854458
854458
    (cherry picked from commit 5b60d0608ac2852753180b762d1917163f9dc315)
854458
854458
commit 9d610e46af8a636f44914cee4cf8b2016054db1e
854458
Author: Mark Andrews <marka@isc.org>
854458
Date:   Thu Oct 12 15:19:45 2017 +1100
854458
854458
    add Net::DNS prerequiste test
854458
854458
    (cherry picked from commit fa644181f51559da3e3913acd72dbc3f6d916e71)
854458
854458
commit e4ea7ba88d9a9a0c79579400c68a5dabe03e8572
854458
Author: Mark Andrews <marka@isc.org>
854458
Date:   Wed Sep 6 19:26:10 2017 +1000
854458
854458
    add quotes arount $send_response
854458
854458
    (cherry picked from commit 023ab19634b287543169e9b7b5259f3126cd60ff)
854458
854458
commit 0af0c5d33c2de34da164571288b650282c6be10a
854458
Author: Mark Andrews <marka@isc.org>
854458
Date:   Thu Nov 23 16:11:49 2017 +1100
854458
854458
    initalise serve_stale_ttl
854458
854458
    (cherry picked from commit 2f4e0e5a81278f59037bf06ae99ff52245cd57e9)
854458
854458
commit fbadd90ee81863d617c4c319d5f0079b877fe102
854458
Author: Evan Hunt <each@isc.org>
854458
Date:   Thu Sep 14 11:48:21 2017 -0700
854458
854458
    [master] add thanks to APNIC and add missing note for serve-stale
854458
854458
commit deb8adaa59955970b9d2f2fe58060a3cbf08312b
854458
Author: Mark Andrews <marka@isc.org>
854458
Date:   Wed Sep 6 12:16:10 2017 +1000
854458
854458
    silence 'staleanswersok' may be used uninitialized in this function warning. [RT #14147
854458
854458
commit 0e2d03823768dc545015e6ce309777210f4a9f85
854458
Author: Petr Menšík <pemensik@redhat.com>
854458
Date:   Thu Aug 29 19:57:58 2019 +0200
854458
854458
    More fixes to merge
854458
854458
commit 360e25ffe7623ea0a2eec49395001f4940967776
854458
Author: Mark Andrews <marka@isc.org>
854458
Date:   Wed Sep 6 09:58:29 2017 +1000
854458
854458
    4700.   [func]          Serving of stale answers is now supported. This
854458
                            allows named to provide stale cached answers when
854458
                            the authoritative server is under attack.
854458
                            See max-stale-ttl, stale-answer-enable,
854458
                            stale-answer-ttl. [RT #44790]
854458
854458
Signed-off-by: Petr Menšík <pemensik@redhat.com>
854458
---
854458
 bin/named/config.c                            |   9 +-
854458
 bin/named/control.c                           |   2 +
854458
 bin/named/include/named/control.h             |   1 +
854458
 bin/named/include/named/log.h                 |   1 +
854458
 bin/named/include/named/query.h               |  15 +
854458
 bin/named/include/named/server.h              |  13 +-
854458
 bin/named/log.c                               |   1 +
854458
 bin/named/query.c                             | 164 +++++-
854458
 bin/named/server.c                            | 177 +++++-
854458
 bin/named/statschannel.c                      |   6 +
854458
 bin/rndc/rndc.c                               |   2 +
854458
 bin/rndc/rndc.docbook                         |  19 +
854458
 bin/tests/system/chain/prereq.sh              |   7 +
854458
 bin/tests/system/conf.sh.in                   |   2 +-
854458
 bin/tests/system/dyndb/driver/db.c            |   2 +
854458
 bin/tests/system/serve-stale/.gitignore       |  11 +
854458
 bin/tests/system/serve-stale/ans2/ans.pl.in   | 178 ++++++
854458
 bin/tests/system/serve-stale/clean.sh         |  15 +
854458
 .../system/serve-stale/ns1/named1.conf.in     |  35 ++
854458
 .../system/serve-stale/ns1/named2.conf.in     |  35 ++
854458
 bin/tests/system/serve-stale/ns1/root.db      |   5 +
854458
 .../system/serve-stale/ns3/named.conf.in      |  35 ++
854458
 bin/tests/system/serve-stale/prereq.sh        |  38 ++
854458
 bin/tests/system/serve-stale/setup.sh         |  13 +
854458
 bin/tests/system/serve-stale/tests.sh         | 536 ++++++++++++++++++
854458
 doc/arm/Bv9ARM-book.xml                       |  69 ++-
854458
 doc/arm/logging-categories.xml                |  11 +
854458
 doc/arm/notes-rh-changes.xml                  |  14 +-
854458
 doc/misc/options                              |  10 +
854458
 lib/bind9/check.c                             |  78 ++-
854458
 lib/dns/cache.c                               |  38 +-
854458
 lib/dns/db.c                                  |  22 +
854458
 lib/dns/ecdb.c                                |   4 +-
854458
 lib/dns/include/dns/cache.h                   |  21 +
854458
 lib/dns/include/dns/db.h                      |  35 ++
854458
 lib/dns/include/dns/rdataset.h                |  11 +
854458
 lib/dns/include/dns/resolver.h                |  43 +-
854458
 lib/dns/include/dns/types.h                   |   6 +
854458
 lib/dns/include/dns/view.h                    |   3 +
854458
 lib/dns/master.c                              |  14 +-
854458
 lib/dns/masterdump.c                          |  23 +
854458
 lib/dns/rbtdb.c                               | 207 ++++++-
854458
 lib/dns/resolver.c                            |  78 ++-
854458
 lib/dns/sdb.c                                 |   4 +-
854458
 lib/dns/sdlz.c                                |   4 +-
854458
 lib/dns/tests/db_test.c                       | 198 ++++++-
854458
 lib/dns/view.c                                |   3 +
854458
 lib/isccfg/namedconf.c                        |   5 +
854458
 48 files changed, 2121 insertions(+), 102 deletions(-)
854458
 create mode 100644 bin/tests/system/serve-stale/.gitignore
854458
 create mode 100644 bin/tests/system/serve-stale/ans2/ans.pl.in
854458
 create mode 100644 bin/tests/system/serve-stale/clean.sh
854458
 create mode 100644 bin/tests/system/serve-stale/ns1/named1.conf.in
854458
 create mode 100644 bin/tests/system/serve-stale/ns1/named2.conf.in
854458
 create mode 100644 bin/tests/system/serve-stale/ns1/root.db
854458
 create mode 100644 bin/tests/system/serve-stale/ns3/named.conf.in
854458
 create mode 100644 bin/tests/system/serve-stale/prereq.sh
854458
 create mode 100644 bin/tests/system/serve-stale/setup.sh
854458
 create mode 100755 bin/tests/system/serve-stale/tests.sh
854458
854458
diff --git a/bin/named/config.c b/bin/named/config.c
74b53c
index 63da4b0..b598f9b 100644
854458
--- a/bin/named/config.c
854458
+++ b/bin/named/config.c
854458
@@ -182,13 +182,14 @@ options {\n\
854458
 #ifdef HAVE_LMDB
854458
 "	lmdb-mapsize 32M;\n"
854458
 #endif
854458
-"	max-acache-size 16M;\n\
854458
-	max-cache-size 90%;\n\
854458
+"	max-cache-size 90%;\n\
854458
+	max-acache-size 16M;\n\
854458
 	max-cache-ttl 604800; /* 1 week */\n\
854458
 	max-clients-per-query 100;\n\
854458
 	max-ncache-ttl 10800; /* 3 hours */\n\
854458
 	max-recursion-depth 7;\n\
854458
 	max-recursion-queries 75;\n\
854458
+	max-stale-ttl 604800; /* 1 week */\n\
854458
 	message-compression yes;\n\
854458
 #	min-roots <obsolete>;\n\
854458
 	minimal-any false;\n\
854458
@@ -203,10 +204,14 @@ options {\n\
854458
 	request-expire true;\n\
854458
 	request-ixfr true;\n\
854458
 	require-server-cookie no;\n\
854458
+	resolver-nonbackoff-tries 3;\n\
854458
+	resolver-retry-interval 800; /* in milliseconds */\n\
854458
 #	rfc2308-type1 <obsolete>;\n\
854458
 	root-key-sentinel yes;\n\
854458
 	servfail-ttl 1;\n\
854458
 #	sortlist <none>\n\
854458
+	stale-answer-enable false;\n\
854458
+	stale-answer-ttl 1; /* 1 second */\n\
854458
 #	topology <none>\n\
854458
 	transfer-format many-answers;\n\
854458
 	v6-bias 50;\n\
854458
diff --git a/bin/named/control.c b/bin/named/control.c
74b53c
index df23c26..8b79850 100644
854458
--- a/bin/named/control.c
854458
+++ b/bin/named/control.c
854458
@@ -282,6 +282,8 @@ ns_control_docommand(isccc_sexpr_t *message, bool readonly,
854458
 		result = ns_server_validation(ns_g_server, lex, text);
854458
 	} else if (command_compare(command, NS_COMMAND_ZONESTATUS)) {
854458
 		result = ns_server_zonestatus(ns_g_server, lex, text);
854458
+	} else if (command_compare(command, NS_COMMAND_SERVESTALE)) {
854458
+		result = ns_server_servestale(ns_g_server, lex, text);
854458
 	} else {
854458
 		isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
854458
 			      NS_LOGMODULE_CONTROL, ISC_LOG_WARNING,
854458
diff --git a/bin/named/include/named/control.h b/bin/named/include/named/control.h
74b53c
index 8705fdd..1634154 100644
854458
--- a/bin/named/include/named/control.h
854458
+++ b/bin/named/include/named/control.h
854458
@@ -69,6 +69,7 @@
854458
 #define NS_COMMAND_MKEYS	"managed-keys"
854458
 #define NS_COMMAND_DNSTAPREOPEN	"dnstap-reopen"
854458
 #define NS_COMMAND_DNSTAP	"dnstap"
854458
+#define NS_COMMAND_SERVESTALE	"serve-stale"
854458
 
854458
 isc_result_t
854458
 ns_controls_create(ns_server_t *server, ns_controls_t **ctrlsp);
854458
diff --git a/bin/named/include/named/log.h b/bin/named/include/named/log.h
74b53c
index 56bfcd4..cd8db60 100644
854458
--- a/bin/named/include/named/log.h
854458
+++ b/bin/named/include/named/log.h
854458
@@ -32,6 +32,7 @@
854458
 #define NS_LOGCATEGORY_UPDATE_SECURITY	(&ns_g_categories[6])
854458
 #define NS_LOGCATEGORY_QUERY_ERRORS	(&ns_g_categories[7])
854458
 #define NS_LOGCATEGORY_TAT		(&ns_g_categories[8])
854458
+#define NS_LOGCATEGORY_SERVE_STALE	(&ns_g_categories[9])
854458
 
854458
 /*
854458
  * Backwards compatibility.
854458
diff --git a/bin/named/include/named/query.h b/bin/named/include/named/query.h
74b53c
index 9661f56..445b578 100644
854458
--- a/bin/named/include/named/query.h
854458
+++ b/bin/named/include/named/query.h
854458
@@ -35,6 +35,18 @@ typedef struct ns_dbversion {
854458
 	ISC_LINK(struct ns_dbversion)	link;
854458
 } ns_dbversion_t;
854458
 
854458
+/*%
854458
+ * nameserver recursion parameters, to uniquely identify a recursion
854458
+ * query; this is used to detect a recursion loop
854458
+ */
854458
+typedef struct ns_query_recparam {
854458
+	dns_rdatatype_t			qtype;
854458
+	dns_name_t *			qname;
854458
+	dns_fixedname_t			fqname;
854458
+	dns_name_t *			qdomain;
854458
+	dns_fixedname_t			fqdomain;
854458
+} ns_query_recparam_t;
854458
+
854458
 /*% nameserver query structure */
854458
 struct ns_query {
854458
 	unsigned int			attributes;
854458
@@ -63,6 +75,7 @@ struct ns_query {
854458
 	unsigned int			dns64_aaaaoklen;
854458
 	unsigned int			dns64_options;
854458
 	unsigned int			dns64_ttl;
854458
+
854458
 	struct {
854458
 		dns_db_t *      	db;
854458
 		dns_zone_t *      	zone;
854458
@@ -76,6 +89,8 @@ struct ns_query {
854458
 		bool		authoritative;
854458
 		bool		is_zone;
854458
 	} redirect;
854458
+
854458
+	ns_query_recparam_t		recparam;
854458
 	dns_keytag_t root_key_sentinel_keyid;
854458
 	bool root_key_sentinel_is_ta;
854458
 	bool root_key_sentinel_not_ta;
854458
diff --git a/bin/named/include/named/server.h b/bin/named/include/named/server.h
74b53c
index 8982d26..919ac28 100644
854458
--- a/bin/named/include/named/server.h
854458
+++ b/bin/named/include/named/server.h
74b53c
@@ -224,7 +224,10 @@ enum {
854458
 
74b53c
 	dns_nsstatscounter_tcphighwater = 57,
854458
 
74b53c
-	dns_nsstatscounter_max = 58
74b53c
+	dns_nsstatscounter_trystale = 58,
74b53c
+	dns_nsstatscounter_usedstale = 59,
854458
+
74b53c
+	dns_nsstatscounter_max = 60
854458
 };
854458
 
854458
 /*%
74b53c
@@ -763,4 +766,12 @@ ns_server_mkeys(ns_server_t *server, isc_lex_t *lex, isc_buffer_t **text);
854458
 isc_result_t
854458
 ns_server_dnstap(ns_server_t *server, isc_lex_t *lex, isc_buffer_t **text);
854458
 
854458
+
854458
+/*%
854458
+ * Control whether stale answers are served or not when configured in
854458
+ * named.conf.
854458
+ */
854458
+isc_result_t
854458
+ns_server_servestale(ns_server_t *server, isc_lex_t *lex,
854458
+		     isc_buffer_t **text);
854458
 #endif /* NAMED_SERVER_H */
854458
diff --git a/bin/named/log.c b/bin/named/log.c
74b53c
index 3aa25e9..12f178b 100644
854458
--- a/bin/named/log.c
854458
+++ b/bin/named/log.c
854458
@@ -38,6 +38,7 @@ static isc_logcategory_t categories[] = {
854458
 	{ "update-security",		0 },
854458
 	{ "query-errors",		0 },
854458
 	{ "trust-anchor-telemetry",	0 },
854458
+	{ "serve-stale",                0 },
854458
 	{ NULL, 			0 }
854458
 };
854458
 
854458
diff --git a/bin/named/query.c b/bin/named/query.c
74b53c
index 0940714..882d69c 100644
854458
--- a/bin/named/query.c
854458
+++ b/bin/named/query.c
854458
@@ -125,10 +125,14 @@
854458
 #define REDIRECT(c)		(((c)->query.attributes & \
854458
 				  NS_QUERYATTR_REDIRECT) != 0)
854458
 
854458
-/*% No QNAME Proof? */
854458
+/*% Does the rdataset 'r' have an attached 'No QNAME Proof'? */
854458
 #define NOQNAME(r)		(((r)->attributes & \
854458
 				  DNS_RDATASETATTR_NOQNAME) != 0)
854458
 
854458
+/*% Does the rdataset 'r' contain a stale answer? */
854458
+#define STALE(r)		(((r)->attributes & \
854458
+				  DNS_RDATASETATTR_STALE) != 0)
854458
+
854458
 #ifdef WANT_QUERYTRACE
854458
 static inline void
854458
 client_trace(ns_client_t *client, int level, const char *message) {
854458
@@ -217,6 +221,10 @@ static bool
854458
 rpz_ck_dnssec(ns_client_t *client, isc_result_t qresult,
854458
 	      dns_rdataset_t *rdataset, dns_rdataset_t *sigrdataset);
854458
 
854458
+static void
854458
+recparam_update(ns_query_recparam_t *param, dns_rdatatype_t qtype,
854458
+		const dns_name_t *qname, const dns_name_t *qdomain);
854458
+
854458
 /*%
854458
  * Increment query statistics counters.
854458
  */
854458
@@ -470,6 +478,7 @@ query_reset(ns_client_t *client, bool everything) {
854458
 	client->query.isreferral = false;
854458
 	client->query.dns64_options = 0;
854458
 	client->query.dns64_ttl = UINT32_MAX;
854458
+	recparam_update(&client->query.recparam, 0, NULL, NULL);
854458
 	client->query.root_key_sentinel_keyid = 0;
854458
 	client->query.root_key_sentinel_is_ta = false;
854458
 	client->query.root_key_sentinel_not_ta = false;
854458
@@ -4254,6 +4263,54 @@ query_prefetch(ns_client_t *client, dns_name_t *qname,
854458
 	dns_rdataset_clearprefetch(rdataset);
854458
 }
854458
 
854458
+/*%
854458
+ * Check whether the recursion parameters in 'param' match the current query's
854458
+ * recursion parameters provided in 'qtype', 'qname', and 'qdomain'.
854458
+ */
854458
+static bool
854458
+recparam_match(const ns_query_recparam_t *param, dns_rdatatype_t qtype,
854458
+	       const dns_name_t *qname, const dns_name_t *qdomain)
854458
+{
854458
+	REQUIRE(param != NULL);
854458
+
854458
+	return (param->qtype == qtype &&
854458
+	        param->qname != NULL && qname != NULL &&
854458
+	        param->qdomain != NULL && qdomain != NULL &&
854458
+	        dns_name_equal(param->qname, qname) &&
854458
+	        dns_name_equal(param->qdomain, qdomain));
854458
+}
854458
+
854458
+/*%
854458
+ * Update 'param' with current query's recursion parameters provided in
854458
+ * 'qtype', 'qname', and 'qdomain'.
854458
+ */
854458
+static void
854458
+recparam_update(ns_query_recparam_t *param, dns_rdatatype_t qtype,
854458
+		const dns_name_t *qname, const dns_name_t *qdomain)
854458
+{
854458
+	isc_result_t result;
854458
+
854458
+	REQUIRE(param != NULL);
854458
+
854458
+	param->qtype = qtype;
854458
+
854458
+	if (qname == NULL) {
854458
+		param->qname = NULL;
854458
+	} else {
854458
+		param->qname = dns_fixedname_initname(&param->fqname);
854458
+		result = dns_name_copy(qname, param->qname, NULL);
854458
+		RUNTIME_CHECK(result == ISC_R_SUCCESS);
854458
+	}
854458
+
854458
+	if (qdomain == NULL) {
854458
+		param->qdomain = NULL;
854458
+	} else {
854458
+		param->qdomain = dns_fixedname_initname(&param->fqdomain);
854458
+		result = dns_name_copy(qdomain, param->qdomain, NULL);
854458
+		RUNTIME_CHECK(result == ISC_R_SUCCESS);
854458
+	}
854458
+}
854458
+
854458
 static isc_result_t
854458
 query_recurse(ns_client_t *client, dns_rdatatype_t qtype, dns_name_t *qname,
854458
 	      dns_name_t *qdomain, dns_rdataset_t *nameservers,
854458
@@ -4263,6 +4320,19 @@ query_recurse(ns_client_t *client, dns_rdatatype_t qtype, dns_name_t *qname,
854458
 	dns_rdataset_t *rdataset, *sigrdataset;
854458
 	isc_sockaddr_t *peeraddr;
854458
 
854458
+	/*
854458
+	 * Check recursion parameters from the previous query to see if they
854458
+	 * match.  If not, update recursion parameters and proceed.
854458
+	 */
854458
+	if (recparam_match(&client->query.recparam, qtype, qname, qdomain)) {
854458
+		ns_client_log(client, NS_LOGCATEGORY_CLIENT,
854458
+			      NS_LOGMODULE_QUERY, ISC_LOG_INFO,
854458
+			      "recursion loop detected");
854458
+		return (ISC_R_FAILURE);
854458
+	}
854458
+
854458
+	recparam_update(&client->query.recparam, qtype, qname, qdomain);
854458
+
854458
 	if (!resuming)
854458
 		inc_stats(client, dns_nsstatscounter_recursion);
854458
 
854458
@@ -6780,6 +6850,7 @@ query_find(ns_client_t *client, dns_fetchevent_t *event, dns_rdatatype_t qtype)
854458
 	int line = -1;
854458
 	bool dns64_exclude, dns64, rpz;
854458
 	bool nxrewrite = false;
854458
+	bool want_stale = false;
854458
 	bool redirected = false;
854458
 	dns_clientinfomethods_t cm;
854458
 	dns_clientinfo_t ci;
854458
@@ -7089,6 +7160,7 @@ query_find(ns_client_t *client, dns_fetchevent_t *event, dns_rdatatype_t qtype)
854458
 		type = qtype;
854458
 
854458
  restart:
854458
+	// query_start
854458
 	CTRACE(ISC_LOG_DEBUG(3), "query_find: restart");
854458
 	want_restart = false;
854458
 	authoritative = false;
854458
@@ -7233,6 +7305,7 @@ query_find(ns_client_t *client, dns_fetchevent_t *event, dns_rdatatype_t qtype)
854458
 	}
854458
 
854458
  db_find:
854458
+	// query_lookup
854458
 	CTRACE(ISC_LOG_DEBUG(3), "query_find: db_find");
854458
 	/*
854458
 	 * We'll need some resources...
854458
@@ -7290,6 +7363,35 @@ query_find(ns_client_t *client, dns_fetchevent_t *event, dns_rdatatype_t qtype)
854458
 	if (!is_zone)
854458
 		dns_cache_updatestats(client->view->cache, result);
854458
 
854458
+	if (want_stale) {
854458
+		char namebuf[DNS_NAME_FORMATSIZE];
854458
+		bool success;
854458
+
854458
+		client->query.dboptions &= ~DNS_DBFIND_STALEOK;
854458
+		want_stale = false;
854458
+
854458
+		if (dns_rdataset_isassociated(rdataset) &&
854458
+		    dns_rdataset_count(rdataset) > 0 &&
854458
+		    STALE(rdataset)) {
854458
+			rdataset->ttl = client->view->staleanswerttl;
854458
+			success = true;
854458
+		} else {
854458
+			success = false;
854458
+		}
854458
+
854458
+		dns_name_format(client->query.qname,
854458
+				namebuf, sizeof(namebuf));
854458
+		isc_log_write(ns_g_lctx, NS_LOGCATEGORY_SERVE_STALE,
854458
+			      NS_LOGMODULE_QUERY, ISC_LOG_INFO,
854458
+			      "%s resolver failure, stale answer %s",
854458
+			      namebuf, success ? "used" : "unavailable");
854458
+
854458
+		if (!success) {
854458
+			QUERY_ERROR(DNS_R_SERVFAIL);
854458
+			goto cleanup;
854458
+		}
854458
+	}
854458
+
854458
  resume:
854458
 	CTRACE(ISC_LOG_DEBUG(3), "query_find: resume");
854458
 
854458
@@ -7635,6 +7737,7 @@ query_find(ns_client_t *client, dns_fetchevent_t *event, dns_rdatatype_t qtype)
854458
 		 * The cache doesn't even have the root NS.  Get them from
854458
 		 * the hints DB.
854458
 		 */
854458
+		// query_notfound
854458
 		INSIST(!is_zone);
854458
 		if (db != NULL)
854458
 			dns_db_detach(&db);
854458
@@ -7697,12 +7800,14 @@ query_find(ns_client_t *client, dns_fetchevent_t *event, dns_rdatatype_t qtype)
854458
 		 */
854458
 		/* FALLTHROUGH */
854458
 	case DNS_R_DELEGATION:
854458
+		// query_delegation
854458
 		authoritative = false;
854458
 		if (is_zone) {
854458
 			/*
854458
 			 * Look to see if we are authoritative for the
854458
 			 * child zone if the query type is DS.
854458
 			 */
854458
+			// query_zone_delegation
854458
 			if (!RECURSIONOK(client) &&
854458
 			    (options & DNS_GETDB_NOEXACT) != 0 &&
854458
 			    qtype == dns_rdatatype_ds) {
854458
@@ -8089,6 +8194,7 @@ query_find(ns_client_t *client, dns_fetchevent_t *event, dns_rdatatype_t qtype)
854458
 						       false, true);
854458
 			}
854458
 		}
854458
+		// query_nxdomain
854458
 		if (dns_rdataset_isassociated(rdataset)) {
854458
 			/*
854458
 			 * If we've got a NSEC record, we need to save the
854458
@@ -8409,7 +8515,8 @@ query_find(ns_client_t *client, dns_fetchevent_t *event, dns_rdatatype_t qtype)
854458
 		/*
854458
 		 * If we have a zero ttl from the cache refetch it.
854458
 		 */
854458
-		if (!is_zone && !resuming && rdataset->ttl == 0 &&
854458
+		// query_cname
854458
+		if (!is_zone && !resuming && !STALE(rdataset) && rdataset->ttl == 0 &&
854458
 		    RECURSIONOK(client))
854458
 		{
854458
 			if (dns_rdataset_isassociated(rdataset))
854458
@@ -8627,7 +8734,11 @@ query_find(ns_client_t *client, dns_fetchevent_t *event, dns_rdatatype_t qtype)
854458
 			 "query_find: unexpected error after resuming: %s",
854458
 			 isc_result_totext(result));
854458
 		CTRACE(ISC_LOG_ERROR, errmsg);
854458
-		QUERY_ERROR(DNS_R_SERVFAIL);
854458
+		if (resuming) {
854458
+			want_stale = true;
854458
+		} else {
854458
+			QUERY_ERROR(DNS_R_SERVFAIL);
854458
+		}
854458
 		goto cleanup;
854458
 	}
854458
 
854458
@@ -8883,7 +8994,7 @@ query_find(ns_client_t *client, dns_fetchevent_t *event, dns_rdatatype_t qtype)
854458
 		/*
854458
 		 * If we have a zero ttl from the cache refetch it.
854458
 		 */
854458
-		if (!is_zone && !resuming && rdataset->ttl == 0 &&
854458
+		if (!is_zone && !resuming && !STALE(rdataset) && rdataset->ttl == 0 &&
854458
 		    RECURSIONOK(client))
854458
 		{
854458
 			if (dns_rdataset_isassociated(rdataset))
854458
@@ -8894,6 +9005,7 @@ query_find(ns_client_t *client, dns_fetchevent_t *event, dns_rdatatype_t qtype)
854458
 			if (node != NULL)
854458
 				dns_db_detachnode(db, &node);
854458
 
854458
+			// query_respond
854458
 			INSIST(!REDIRECT(client));
854458
 			result = query_recurse(client, qtype,
854458
 					       client->query.qname,
854458
@@ -9174,6 +9286,7 @@ query_find(ns_client_t *client, dns_fetchevent_t *event, dns_rdatatype_t qtype)
854458
 				       dns_fixedname_name(&wildcardname),
854458
 				       true, false);
854458
  cleanup:
854458
+	// query_done
854458
 	CTRACE(ISC_LOG_DEBUG(3), "query_find: cleanup");
854458
 	/*
854458
 	 * General cleanup.
854458
@@ -9230,6 +9343,49 @@ query_find(ns_client_t *client, dns_fetchevent_t *event, dns_rdatatype_t qtype)
854458
 		goto restart;
854458
 	}
854458
 
854458
+	if (want_stale) {
854458
+		dns_ttl_t stale_ttl = 0;
854458
+		isc_result_t result;
854458
+		bool staleanswersok = false;
854458
+
854458
+		/*
854458
+		 * Stale answers only make sense if stale_ttl > 0 but
854458
+		 * we want rndc to be able to control returning stale
854458
+		 * answers if they are configured.
854458
+		 */
854458
+		dns_db_attach(client->view->cachedb, &db);
854458
+		result = dns_db_getservestalettl(db, &stale_ttl);
854458
+		if (result == ISC_R_SUCCESS && stale_ttl > 0)  {
854458
+			switch (client->view->staleanswersok) {
854458
+			case dns_stale_answer_yes:
854458
+				staleanswersok = true;
854458
+				break;
854458
+			case dns_stale_answer_conf:
854458
+				staleanswersok =
854458
+					client->view->staleanswersenable;
854458
+				break;
854458
+			case dns_stale_answer_no:
854458
+				staleanswersok = false;
854458
+				break;
854458
+			}
854458
+		} else {
854458
+			staleanswersok = false;
854458
+		}
854458
+
854458
+		if (staleanswersok) {
854458
+			client->query.dboptions |= DNS_DBFIND_STALEOK;
854458
+			inc_stats(client, dns_nsstatscounter_trystale);
854458
+			if (client->query.fetch != NULL)
854458
+				dns_resolver_destroyfetch(
854458
+						   &client->query.fetch);
854458
+			goto db_find;
854458
+		}
854458
+		dns_db_detach(&db);
854458
+		want_stale = false;
854458
+		QUERY_ERROR(DNS_R_SERVFAIL);
854458
+		goto cleanup;
854458
+	}
854458
+
854458
 	if (eresult != ISC_R_SUCCESS &&
854458
 	    (!PARTIALANSWER(client) || WANTRECURSION(client)
854458
 	     || eresult == DNS_R_DROP)) {
854458
diff --git a/bin/named/server.c b/bin/named/server.c
74b53c
index 0c1f08b..d195bca 100644
854458
--- a/bin/named/server.c
854458
+++ b/bin/named/server.c
854458
@@ -1722,7 +1722,8 @@ static bool
854458
 cache_sharable(dns_view_t *originview, dns_view_t *view,
854458
 	       bool new_zero_no_soattl,
854458
 	       unsigned int new_cleaning_interval,
854458
-	       uint64_t new_max_cache_size)
854458
+	       uint64_t new_max_cache_size,
854458
+	       uint32_t new_stale_ttl)
854458
 {
854458
 	/*
854458
 	 * If the cache cannot even reused for the same view, it cannot be
854458
@@ -1737,6 +1738,7 @@ cache_sharable(dns_view_t *originview, dns_view_t *view,
854458
 	 */
854458
 	if (dns_cache_getcleaninginterval(originview->cache) !=
854458
 	    new_cleaning_interval ||
854458
+	    dns_cache_getservestalettl(originview->cache) != new_stale_ttl ||
854458
 	    dns_cache_getcachesize(originview->cache) != new_max_cache_size) {
854458
 		return (false);
854458
 	}
74b53c
@@ -3292,6 +3294,7 @@ configure_view(dns_view_t *view, dns_viewlist_t *viewlist,
854458
 	size_t max_acache_size;
854458
 	size_t max_adb_size;
854458
 	uint32_t lame_ttl, fail_ttl;
854458
+	uint32_t max_stale_ttl;
854458
 	dns_tsig_keyring_t *ring = NULL;
854458
 	dns_view_t *pview = NULL;	/* Production view */
854458
 	isc_mem_t *cmctx = NULL, *hmctx = NULL;
74b53c
@@ -3320,6 +3323,7 @@ configure_view(dns_view_t *view, dns_viewlist_t *viewlist,
854458
 	bool old_rpz_ok = false;
854458
 	isc_dscp_t dscp4 = -1, dscp6 = -1;
854458
 	dns_dyndbctx_t *dctx = NULL;
854458
+	unsigned int resolver_param;
854458
 
854458
 	REQUIRE(DNS_VIEW_VALID(view));
854458
 
74b53c
@@ -3734,6 +3738,24 @@ configure_view(dns_view_t *view, dns_viewlist_t *viewlist,
854458
 	if (view->maxncachettl > 7 * 24 * 3600)
854458
 		view->maxncachettl = 7 * 24 * 3600;
854458
 
854458
+	obj = NULL;
854458
+	result = ns_config_get(maps, "max-stale-ttl", &obj);
854458
+	INSIST(result == ISC_R_SUCCESS);
854458
+	max_stale_ttl = cfg_obj_asuint32(obj);
854458
+
854458
+	obj = NULL;
854458
+	result = ns_config_get(maps, "stale-answer-enable", &obj);
854458
+	INSIST(result == ISC_R_SUCCESS);
854458
+	view->staleanswersenable = cfg_obj_asboolean(obj);
854458
+
854458
+	result = dns_viewlist_find(&ns_g_server->viewlist, view->name,
854458
+				   view->rdclass, &pview);
854458
+	if (result == ISC_R_SUCCESS) {
854458
+		view->staleanswersok = pview->staleanswersok;
854458
+		dns_view_detach(&pview);
854458
+	} else
854458
+		view->staleanswersok = dns_stale_answer_conf;
854458
+
854458
 	/*
854458
 	 * Configure the view's cache.
854458
 	 *
74b53c
@@ -3767,7 +3789,8 @@ configure_view(dns_view_t *view, dns_viewlist_t *viewlist,
854458
 	nsc = cachelist_find(cachelist, cachename, view->rdclass);
854458
 	if (nsc != NULL) {
854458
 		if (!cache_sharable(nsc->primaryview, view, zero_no_soattl,
854458
-				    cleaning_interval, max_cache_size)) {
854458
+				    cleaning_interval, max_cache_size,
854458
+				    max_stale_ttl)) {
854458
 			isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
854458
 				      NS_LOGMODULE_SERVER, ISC_LOG_ERROR,
854458
 				      "views %s and %s can't share the cache "
74b53c
@@ -3866,9 +3889,15 @@ configure_view(dns_view_t *view, dns_viewlist_t *viewlist,
854458
 
854458
 	dns_cache_setcleaninginterval(cache, cleaning_interval);
854458
 	dns_cache_setcachesize(cache, max_cache_size);
854458
+	dns_cache_setservestalettl(cache, max_stale_ttl);
854458
 
854458
 	dns_cache_detach(&cache);
854458
 
854458
+	obj = NULL;
854458
+	result = ns_config_get(maps, "stale-answer-ttl", &obj);
854458
+	INSIST(result == ISC_R_SUCCESS);
854458
+	view->staleanswerttl = ISC_MAX(cfg_obj_asuint32(obj), 1);
854458
+
854458
 	/*
854458
 	 * Resolver.
854458
 	 *
74b53c
@@ -4057,6 +4086,21 @@ configure_view(dns_view_t *view, dns_viewlist_t *viewlist,
854458
 		maxbits = 4096;
854458
 	view->maxbits = maxbits;
854458
 
854458
+	/*
854458
+	 * Set resolver retry parameters.
854458
+	 */
854458
+	obj = NULL;
854458
+	CHECK(ns_config_get(maps, "resolver-retry-interval", &obj));
854458
+	resolver_param = cfg_obj_asuint32(obj);
854458
+	if (resolver_param > 0)
854458
+		dns_resolver_setretryinterval(view->resolver, resolver_param);
854458
+
854458
+	obj = NULL;
854458
+	CHECK(ns_config_get(maps, "resolver-nonbackoff-tries", &obj));
854458
+	resolver_param = cfg_obj_asuint32(obj);
854458
+	if (resolver_param > 0)
854458
+		dns_resolver_setnonbackofftries(view->resolver, resolver_param);
854458
+
854458
 	/*
854458
 	 * Set supported DNSSEC algorithms.
854458
 	 */
74b53c
@@ -14423,3 +14467,132 @@ ns_server_dnstap(ns_server_t *server, isc_lex_t *lex, isc_buffer_t **text) {
854458
 	return (ISC_R_NOTIMPLEMENTED);
854458
 #endif
854458
 }
854458
+
854458
+isc_result_t
854458
+ns_server_servestale(ns_server_t *server, isc_lex_t *lex,
854458
+		     isc_buffer_t **text)
854458
+{
854458
+	char *ptr, *classtxt, *viewtxt = NULL;
854458
+	char msg[128];
854458
+	dns_rdataclass_t rdclass = dns_rdataclass_in;
854458
+	dns_view_t *view;
854458
+	bool found = false;
854458
+	dns_stale_answer_t staleanswersok = dns_stale_answer_conf;
854458
+	bool wantstatus = false;
854458
+	isc_result_t result = ISC_R_SUCCESS;
854458
+
854458
+	/* Skip the command name. */
854458
+	ptr = next_token(lex, text);
854458
+	if (ptr == NULL)
854458
+		return (ISC_R_UNEXPECTEDEND);
854458
+
854458
+	ptr = next_token(lex, NULL);
854458
+	if (ptr == NULL)
854458
+		return (ISC_R_UNEXPECTEDEND);
854458
+
854458
+	if (strcasecmp(ptr, "on") == 0 || strcasecmp(ptr, "yes") == 0) {
854458
+		staleanswersok = dns_stale_answer_yes;
854458
+	} else if (strcasecmp(ptr, "off") == 0 || strcasecmp(ptr, "no") == 0) {
854458
+		staleanswersok = dns_stale_answer_no;
854458
+	} else if (strcasecmp(ptr, "reset") == 0) {
854458
+		staleanswersok = dns_stale_answer_conf;
854458
+	} else if (strcasecmp(ptr, "status") == 0) {
854458
+		wantstatus = true;
854458
+	} else
854458
+		return (DNS_R_SYNTAX);
854458
+
854458
+	/* Look for the optional class name. */
854458
+	classtxt = next_token(lex, text);
854458
+	if (classtxt != NULL) {
854458
+		/* Look for the optional view name. */
854458
+		viewtxt = next_token(lex, text);
854458
+	}
854458
+
854458
+	if (classtxt != NULL) {
854458
+		isc_textregion_t r;
854458
+
854458
+		r.base = classtxt;
854458
+		r.length = strlen(classtxt);
854458
+		result = dns_rdataclass_fromtext(&rdclass, &r);
854458
+		if (result != ISC_R_SUCCESS) {
854458
+			if (viewtxt == NULL) {
854458
+				viewtxt = classtxt;
854458
+				classtxt = NULL;
854458
+				result = ISC_R_SUCCESS;
854458
+			} else {
854458
+				snprintf(msg, sizeof(msg),
854458
+					 "unknown class '%s'", classtxt);
854458
+				(void) putstr(text, msg);
854458
+				goto cleanup;
854458
+			}
854458
+		}
854458
+	}
854458
+
854458
+	result = isc_task_beginexclusive(server->task);
854458
+	RUNTIME_CHECK(result == ISC_R_SUCCESS);
854458
+
854458
+	for (view = ISC_LIST_HEAD(server->viewlist);
854458
+	     view != NULL;
854458
+	     view = ISC_LIST_NEXT(view, link))
854458
+	{
854458
+		dns_ttl_t stale_ttl = 0;
854458
+		dns_db_t *db = NULL;
854458
+
854458
+		if (classtxt != NULL && rdclass != view->rdclass)
854458
+			continue;
854458
+
854458
+		if (viewtxt != NULL && strcmp(view->name, viewtxt) != 0)
854458
+			continue;
854458
+
854458
+		if (!wantstatus) {
854458
+			view->staleanswersok = staleanswersok;
854458
+			found = true;
854458
+			continue;
854458
+		}
854458
+
854458
+		db = NULL;
854458
+		dns_db_attach(view->cachedb, &db);
854458
+		(void)dns_db_getservestalettl(db, &stale_ttl);
854458
+		dns_db_detach(&db);
854458
+		if (found)
854458
+			CHECK(putstr(text, "\n"));
854458
+		CHECK(putstr(text, view->name));
854458
+		CHECK(putstr(text, ": "));
854458
+		switch (view->staleanswersok) {
854458
+		case dns_stale_answer_yes:
854458
+			if (stale_ttl > 0)
854458
+				CHECK(putstr(text, "on (rndc)"));
854458
+			else
854458
+				CHECK(putstr(text, "off (not-cached)"));
854458
+			break;
854458
+		case dns_stale_answer_no:
854458
+			CHECK(putstr(text, "off (rndc)"));
854458
+			break;
854458
+		case dns_stale_answer_conf:
854458
+			if (view->staleanswersenable && stale_ttl > 0)
854458
+				CHECK(putstr(text, "on"));
854458
+			else if (view->staleanswersenable)
854458
+				CHECK(putstr(text, "off (not-cached)"));
854458
+			else
854458
+				CHECK(putstr(text, "off"));
854458
+			break;
854458
+		}
854458
+		if (stale_ttl > 0) {
854458
+			snprintf(msg, sizeof(msg),
854458
+				 " (stale-answer-ttl=%u max-stale-ttl=%u)",
854458
+				 view->staleanswerttl, stale_ttl);
854458
+			CHECK(putstr(text, msg));
854458
+		}
854458
+		found = true;
854458
+	}
854458
+	isc_task_endexclusive(ns_g_server->task);
854458
+
854458
+	if (!found)
854458
+		result = ISC_R_NOTFOUND;
854458
+
854458
+cleanup:
854458
+	if (isc_buffer_usedlength(*text) > 0)
854458
+		(void) putnull(text);
854458
+
854458
+	return (result);
854458
+}
854458
diff --git a/bin/named/statschannel.c b/bin/named/statschannel.c
74b53c
index 4cdf7d6..5b413e7 100644
854458
--- a/bin/named/statschannel.c
854458
+++ b/bin/named/statschannel.c
74b53c
@@ -297,6 +297,12 @@ init_desc(void) {
854458
 		"QryNXRedirRLookup");
854458
 	SET_NSSTATDESC(badcookie, "sent badcookie response", "QryBADCOOKIE");
854458
 	SET_NSSTATDESC(keytagopt, "Keytag option received", "KeyTagOpt");
854458
+	SET_NSSTATDESC(trystale,
854458
+		       "attempts to use stale cache data after lookup failure",
854458
+		       "QryTryStale");
854458
+	SET_NSSTATDESC(usedstale,
854458
+		       "successful uses of stale cache data after lookup failure",
854458
+		       "QryUsedStale");
854458
 	INSIST(i == dns_nsstatscounter_max);
854458
 
854458
 	/* Initialize resolver statistics */
854458
diff --git a/bin/rndc/rndc.c b/bin/rndc/rndc.c
74b53c
index 8083654..d519983 100644
854458
--- a/bin/rndc/rndc.c
854458
+++ b/bin/rndc/rndc.c
854458
@@ -160,6 +160,8 @@ command is one of the following:\n\
854458
   scan		Scan available network interfaces for changes.\n\
854458
   secroots [view ...]\n\
854458
 		Write security roots to the secroots file.\n\
854458
+  serve-stale	( yes | no | reset ) [class [view]]\n\
854458
+		Control whether stale answers are returned\n\
854458
   showzone zone [class [view]]\n\
854458
 		Print a zone's configuration.\n\
854458
   sign zone [class [view]]\n\
854458
diff --git a/bin/rndc/rndc.docbook b/bin/rndc/rndc.docbook
74b53c
index 06b073a..6ae8e5d 100644
854458
--- a/bin/rndc/rndc.docbook
854458
+++ b/bin/rndc/rndc.docbook
854458
@@ -688,6 +688,25 @@
854458
 	</listitem>
854458
       </varlistentry>
854458
 
854458
+      <varlistentry>
854458
+	<term><userinput>serve-stale ( on | off | reset | status) <optional><replaceable>class</replaceable> <optional><replaceable>view</replaceable></optional></optional></userinput></term>
854458
+	<listitem>
854458
+	  <para>
854458
+	    Enable, disable, or reset the serving of stale answers
854458
+	    as configured in named.conf. Serving of stale answers
854458
+	    will remain disabled across <filename>named.conf</filename>
854458
+	    reloads if disabled via rndc until it is reset via rndc.
854458
+	  </para>
854458
+	  <para>
854458
+	    Status will report whether serving of stale answers is
854458
+	    currently enabled, disabled or not configured for a
854458
+	    view.  If serving of stale records is configured then
854458
+	    the values of stale-answer-ttl and max-stale-ttl are
854458
+	    reported.
854458
+	  </para>
854458
+	</listitem>
854458
+      </varlistentry>
854458
+
854458
       <varlistentry>
854458
 	<term><userinput>secroots <optional>-</optional> <optional><replaceable>view ...</replaceable></optional></userinput></term>
854458
 	<listitem>
854458
diff --git a/bin/tests/system/chain/prereq.sh b/bin/tests/system/chain/prereq.sh
74b53c
index f3f1939..9ff3f07 100644
854458
--- a/bin/tests/system/chain/prereq.sh
854458
+++ b/bin/tests/system/chain/prereq.sh
854458
@@ -48,3 +48,10 @@ else
854458
     echo_i "This test requires the Net::DNS::Nameserver library." >&2
854458
     exit 1
854458
 fi
854458
+if $PERL -e 'use Net::DNS::Nameserver;' 2>/dev/null
854458
+then
854458
+	:
854458
+else
854458
+    echo "I:This test requires the Net::DNS::Nameserver library." >&2
854458
+    exit 1
854458
+fi
854458
diff --git a/bin/tests/system/conf.sh.in b/bin/tests/system/conf.sh.in
74b53c
index f781966..d20a830 100644
854458
--- a/bin/tests/system/conf.sh.in
854458
+++ b/bin/tests/system/conf.sh.in
854458
@@ -125,7 +125,7 @@ PARALLELDIRS="dnssec rpzrecurse \
854458
 	reclimit redirect resolver rndc rootkeysentinel rpz \
854458
 	rrchecker rrl rrsetorder rsabigexponent runtime \
854458
 	sfcache smartsign sortlist \
854458
-	spf staticstub statistics statschannel stub \
854458
+	spf serve-stale staticstub statistics statschannel stub \
854458
 	tcp tsig tsiggss \
854458
 	unknown upforwd verify views wildcard \
854458
 	xfer xferquota zero zonechecks"
854458
diff --git a/bin/tests/system/dyndb/driver/db.c b/bin/tests/system/dyndb/driver/db.c
74b53c
index 02aa6ab..a77c7de 100644
854458
--- a/bin/tests/system/dyndb/driver/db.c
854458
+++ b/bin/tests/system/dyndb/driver/db.c
854458
@@ -629,6 +629,8 @@ static dns_dbmethods_t sampledb_methods = {
854458
 	hashsize,
854458
 	NULL,
854458
 	NULL,
854458
+	NULL,
854458
+	NULL,
854458
 };
854458
 
854458
 /* Auxiliary driver functions. */
854458
diff --git a/bin/tests/system/serve-stale/.gitignore b/bin/tests/system/serve-stale/.gitignore
854458
new file mode 100644
74b53c
index 0000000..2272eef
854458
--- /dev/null
854458
+++ b/bin/tests/system/serve-stale/.gitignore
854458
@@ -0,0 +1,11 @@
854458
+/ans2/ans.pid
854458
+/ans2/ans.pl
854458
+/dig.out*
854458
+/ns1/named.conf
854458
+/ns3/named.conf
854458
+/ns3/root.bk
854458
+/rndc.out*
854458
+named.lock
854458
+named.pid
854458
+named.port
854458
+named.run
854458
diff --git a/bin/tests/system/serve-stale/ans2/ans.pl.in b/bin/tests/system/serve-stale/ans2/ans.pl.in
854458
new file mode 100644
74b53c
index 0000000..2b39eca
854458
--- /dev/null
854458
+++ b/bin/tests/system/serve-stale/ans2/ans.pl.in
854458
@@ -0,0 +1,178 @@
854458
+#!/usr/bin/env perl
854458
+#
854458
+# Copyright (C) 2014-2016  Internet Systems Consortium, Inc. ("ISC")
854458
+#
854458
+# This Source Code Form is subject to the terms of the Mozilla Public
854458
+# License, v. 2.0. If a copy of the MPL was not distributed with this
854458
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
854458
+
854458
+use strict;
854458
+use warnings;
854458
+
854458
+use IO::File;
854458
+use IO::Socket;
854458
+use Getopt::Long;
854458
+use Net::DNS;
854458
+use Time::HiRes qw(usleep nanosleep);
854458
+
854458
+my $pidf = new IO::File "ans.pid", "w" or die "cannot open pid file: $!";
854458
+print $pidf "$$\n" or die "cannot write pid file: $!";
854458
+$pidf->close or die "cannot close pid file: $!";
854458
+sub rmpid { unlink "ans.pid"; exit 1; };
854458
+
854458
+$SIG{INT} = \&rmpid;
854458
+$SIG{TERM} = \&rmpid;
854458
+
854458
+my $send_response = 1;
854458
+
854458
+my $localaddr = "10.53.0.2";
854458
+my $localport = @PORT@;
854458
+my $udpsock = IO::Socket::INET->new(LocalAddr => "$localaddr",
854458
+   LocalPort => $localport, Proto => "udp", Reuse => 1) or die "$!";
854458
+
854458
+#
854458
+# Delegation
854458
+#
854458
+my $SOA = "example 300 IN SOA . . 0 0 0 0 300";
854458
+my $NS = "example 300 IN NS ns.example";
854458
+my $A = "ns.example 300 IN A $localaddr";
854458
+#
854458
+# Records to be TTL stretched
854458
+#
854458
+my $TXT = "data.example 1 IN TXT \"A text record with a 1 second ttl\"";
854458
+my $negSOA = "example 1 IN SOA . . 0 0 0 0 300";
854458
+
854458
+sub reply_handler {
854458
+    my ($qname, $qclass, $qtype) = @_;
854458
+    my ($rcode, @ans, @auth, @add);
854458
+
854458
+    print ("request: $qname/$qtype\n");
854458
+    STDOUT->flush();
854458
+
854458
+    # Control whether we send a response or not.
854458
+    # We always respond to control commands.
854458
+    if ($qname eq "enable" ) {
854458
+	if ($qtype eq "TXT") {
854458
+	    $send_response = 1;
854458
+            my $rr = new Net::DNS::RR("$qname 0 $qclass TXT \"$send_response\"");
854458
+            push @ans, $rr;
854458
+	}
854458
+	$rcode = "NOERROR";
854458
+        return ($rcode, \@ans, \@auth, \@add, { aa => 1 });
854458
+    } elsif ($qname eq "disable" ) {
854458
+	if ($qtype eq "TXT") {
854458
+	    $send_response = 0;
854458
+            my $rr = new Net::DNS::RR("$qname 0 $qclass TXT \"$send_response\"");
854458
+            push @ans, $rr;
854458
+	}
854458
+	$rcode = "NOERROR";
854458
+        return ($rcode, \@ans, \@auth, \@add, { aa => 1 });
854458
+    }
854458
+
854458
+    # If we are not responding to queries we are done.
854458
+    return if (!$send_response);
854458
+
854458
+    # Construct the response and send it.
854458
+    if ($qname eq "ns.example" ) {
854458
+	if ($qtype eq "A") {
854458
+	    my $rr = new Net::DNS::RR($A);
854458
+	    push @ans, $rr;
854458
+	} else {
854458
+	    my $rr = new Net::DNS::RR($SOA);
854458
+	    push @auth, $rr;
854458
+	}
854458
+	$rcode = "NOERROR";
854458
+    } elsif ($qname eq "example") {
854458
+	if ($qtype eq "NS") {
854458
+	    my $rr = new Net::DNS::RR($NS);
854458
+	    push @auth, $rr;
854458
+	    $rr = new Net::DNS::RR($A);
854458
+	    push @add, $rr;
854458
+	} elsif ($qtype eq "SOA") {
854458
+	    my $rr = new Net::DNS::RR($SOA);
854458
+	    push @ans, $rr;
854458
+	} else {
854458
+	    my $rr = new Net::DNS::RR($SOA);
854458
+	    push @auth, $rr;
854458
+	}
854458
+	$rcode = "NOERROR";
854458
+    } elsif ($qname eq "nodata.example") {
854458
+	my $rr = new Net::DNS::RR($negSOA);
854458
+	push @auth, $rr;
854458
+	$rcode = "NOERROR";
854458
+    } elsif ($qname eq "data.example") {
854458
+	if ($qtype eq "TXT") {
854458
+	    my $rr = new Net::DNS::RR($TXT);
854458
+	    push @ans, $rr;
854458
+	} else {
854458
+	    my $rr = new Net::DNS::RR($negSOA);
854458
+	    push @auth, $rr;
854458
+	}
854458
+	$rcode = "NOERROR";
854458
+    } elsif ($qname eq "nxdomain.example") {
854458
+	my $rr = new Net::DNS::RR($negSOA);
854458
+	push @auth, $rr;
854458
+	$rcode = "NXDOMAIN";
854458
+    } else {
854458
+        my $rr = new Net::DNS::RR($SOA);
854458
+	push @auth, $rr;
854458
+	$rcode = "NXDOMAIN";
854458
+    }
854458
+
854458
+    # mark the answer as authoritive (by setting the 'aa' flag
854458
+    return ($rcode, \@ans, \@auth, \@add, { aa => 1 });
854458
+}
854458
+
854458
+GetOptions(
854458
+    'port=i' => \$localport,
854458
+);
854458
+
854458
+my $rin;
854458
+my $rout;
854458
+
854458
+for (;;) {
854458
+	$rin = '';
854458
+	vec($rin, fileno($udpsock), 1) = 1;
854458
+
854458
+	select($rout = $rin, undef, undef, undef);
854458
+
854458
+	if (vec($rout, fileno($udpsock), 1)) {
854458
+		my ($buf, $request, $err);
854458
+		$udpsock->recv($buf, 512);
854458
+
854458
+		if ($Net::DNS::VERSION > 0.68) {
854458
+			$request = new Net::DNS::Packet(\$buf, 0);
854458
+			$@ and die $@;
854458
+		} else {
854458
+			my $err;
854458
+			($request, $err) = new Net::DNS::Packet(\$buf, 0);
854458
+			$err and die $err;
854458
+		}
854458
+
854458
+		my @questions = $request->question;
854458
+		my $qname = $questions[0]->qname;
854458
+		my $qclass = $questions[0]->qclass;
854458
+		my $qtype = $questions[0]->qtype;
854458
+		my $id = $request->header->id;
854458
+
854458
+		my ($rcode, $ans, $auth, $add, $headermask) = reply_handler($qname, $qclass, $qtype);
854458
+
854458
+		if (!defined($rcode)) {
854458
+			print "  Silently ignoring query\n";
854458
+			next;
854458
+		}
854458
+
854458
+		my $reply = Net::DNS::Packet->new();
854458
+		$reply->header->qr(1);
854458
+		$reply->header->aa(1) if $headermask->{'aa'};
854458
+		$reply->header->id($id);
854458
+		$reply->header->rcode($rcode);
854458
+		$reply->push("question",   @questions);
854458
+		$reply->push("answer",     @$ans)  if $ans;
854458
+		$reply->push("authority",  @$auth) if $auth;
854458
+		$reply->push("additional", @$add)  if $add;
854458
+
854458
+		my $num_chars = $udpsock->send($reply->data);
854458
+		print "  Sent $num_chars bytes via UDP\n";
854458
+	}
854458
+}
854458
diff --git a/bin/tests/system/serve-stale/clean.sh b/bin/tests/system/serve-stale/clean.sh
854458
new file mode 100644
74b53c
index 0000000..2397326
854458
--- /dev/null
854458
+++ b/bin/tests/system/serve-stale/clean.sh
854458
@@ -0,0 +1,15 @@
854458
+# Copyright (C) 2017  Internet Systems Consortium, Inc. ("ISC")
854458
+#
854458
+# This Source Code Form is subject to the terms of the Mozilla Public
854458
+# License, v. 2.0. If a copy of the MPL was not distributed with this
854458
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
854458
+
854458
+rm -f test.output
854458
+rm -f dig.out.test*
854458
+rm -f ans2/ans.pl
854458
+rm -f ns3/root.bk
854458
+rm -f rndc.out.test*
854458
+rm -f ns*/named.memstats
854458
+rm -f ns*/managed-keys.bind
854458
+rm -f ns*/named.conf
854458
+rm -f ns*/named.run
854458
diff --git a/bin/tests/system/serve-stale/ns1/named1.conf.in b/bin/tests/system/serve-stale/ns1/named1.conf.in
854458
new file mode 100644
74b53c
index 0000000..8a75a10
854458
--- /dev/null
854458
+++ b/bin/tests/system/serve-stale/ns1/named1.conf.in
854458
@@ -0,0 +1,35 @@
854458
+/*
854458
+ * Copyright (C) 2017  Internet Systems Consortium, Inc. ("ISC")
854458
+ *
854458
+ * This Source Code Form is subject to the terms of the Mozilla Public
854458
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
854458
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
854458
+ */
854458
+
854458
+key rndc_key {
854458
+        secret "1234abcd8765";
854458
+        algorithm hmac-sha256;
854458
+};
854458
+
854458
+controls {
854458
+	inet 10.53.0.1 port @CONTROLPORT@ allow { any; } keys { rndc_key; };
854458
+};
854458
+
854458
+options {
854458
+	query-source address 10.53.0.1;
854458
+	notify-source 10.53.0.1;
854458
+	transfer-source 10.53.0.1;
854458
+	port @PORT@;
854458
+	pid-file "named.pid";
854458
+	listen-on { 10.53.0.1; };
854458
+	listen-on-v6 { none; };
854458
+	recursion yes;
854458
+	max-stale-ttl 3600;
854458
+	stale-answer-ttl 1;
854458
+	stale-answer-enable yes;
854458
+};
854458
+
854458
+zone "." {
854458
+	type master;
854458
+	file "root.db";
854458
+};
854458
diff --git a/bin/tests/system/serve-stale/ns1/named2.conf.in b/bin/tests/system/serve-stale/ns1/named2.conf.in
854458
new file mode 100644
74b53c
index 0000000..072e6ec
854458
--- /dev/null
854458
+++ b/bin/tests/system/serve-stale/ns1/named2.conf.in
854458
@@ -0,0 +1,35 @@
854458
+/*
854458
+ * Copyright (C) 2017  Internet Systems Consortium, Inc. ("ISC")
854458
+ *
854458
+ * This Source Code Form is subject to the terms of the Mozilla Public
854458
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
854458
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
854458
+ */
854458
+
854458
+key rndc_key {
854458
+        secret "1234abcd8765";
854458
+        algorithm hmac-sha256;
854458
+};
854458
+
854458
+controls {
854458
+	inet 10.53.0.1 port @CONTROLPORT@ allow { any; } keys { rndc_key; };
854458
+};
854458
+
854458
+options {
854458
+	query-source address 10.53.0.1;
854458
+	notify-source 10.53.0.1;
854458
+	transfer-source 10.53.0.1;
854458
+	port @PORT@;
854458
+	pid-file "named.pid";
854458
+	listen-on { 10.53.0.1; };
854458
+	listen-on-v6 { none; };
854458
+	recursion yes;
854458
+	max-stale-ttl 7200;
854458
+	stale-answer-ttl 2;
854458
+	stale-answer-enable yes;
854458
+};
854458
+
854458
+zone "." {
854458
+	type master;
854458
+	file "root.db";
854458
+};
854458
diff --git a/bin/tests/system/serve-stale/ns1/root.db b/bin/tests/system/serve-stale/ns1/root.db
854458
new file mode 100644
74b53c
index 0000000..eb9ad3e
854458
--- /dev/null
854458
+++ b/bin/tests/system/serve-stale/ns1/root.db
854458
@@ -0,0 +1,5 @@
854458
+.		300	SOA	. . 0 0 0 0 0
854458
+.		300	NS	ns.nil.
854458
+ns.nil.		300	A	10.53.0.1
854458
+example.	300	NS	ns.example.
854458
+ns.example.	300	A	10.53.0.2
854458
diff --git a/bin/tests/system/serve-stale/ns3/named.conf.in b/bin/tests/system/serve-stale/ns3/named.conf.in
854458
new file mode 100644
74b53c
index 0000000..24a3293
854458
--- /dev/null
854458
+++ b/bin/tests/system/serve-stale/ns3/named.conf.in
854458
@@ -0,0 +1,35 @@
854458
+/*
854458
+ * Copyright (C) 2017  Internet Systems Consortium, Inc. ("ISC")
854458
+ *
854458
+ * This Source Code Form is subject to the terms of the Mozilla Public
854458
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
854458
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
854458
+ */
854458
+
854458
+key rndc_key {
854458
+        secret "1234abcd8765";
854458
+        algorithm hmac-sha256;
854458
+};
854458
+
854458
+controls {
854458
+	inet 10.53.0.3 port @CONTROLPORT@ allow { any; } keys { rndc_key; };
854458
+};
854458
+
854458
+options {
854458
+	query-source address 10.53.0.3;
854458
+	notify-source 10.53.0.3;
854458
+	transfer-source 10.53.0.3;
854458
+	port @PORT@;
854458
+	pid-file "named.pid";
854458
+	listen-on { 10.53.0.3; };
854458
+	listen-on-v6 { none; };
854458
+	recursion yes;
854458
+	// max-stale-ttl 3600;
854458
+	// stale-answer-ttl 3;
854458
+};
854458
+
854458
+zone "." {
854458
+	type slave;
854458
+	masters { 10.53.0.1; };
854458
+	file "root.bk";
854458
+};
854458
diff --git a/bin/tests/system/serve-stale/prereq.sh b/bin/tests/system/serve-stale/prereq.sh
854458
new file mode 100644
74b53c
index 0000000..a3bbef8
854458
--- /dev/null
854458
+++ b/bin/tests/system/serve-stale/prereq.sh
854458
@@ -0,0 +1,38 @@
854458
+#!/bin/sh
854458
+#
854458
+# Copyright (C) 2011, 2012, 2014, 2016  Internet Systems Consortium, Inc. ("ISC")
854458
+#
854458
+# This Source Code Form is subject to the terms of the Mozilla Public
854458
+# License, v. 2.0. If a copy of the MPL was not distributed with this
854458
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
854458
+
854458
+SYSTEMTESTTOP=..
854458
+. $SYSTEMTESTTOP/conf.sh
854458
+
854458
+if $PERL -e 'use Net::DNS;' 2>/dev/null
854458
+then
854458
+    if $PERL -e 'use Net::DNS; die if ($Net::DNS::VERSION >= 0.69 && $Net::DNS::VERSION <= 0.74);' 2>/dev/null
854458
+    then
854458
+        :
854458
+    else
854458
+        echo "I:Net::DNS versions 0.69 to 0.74 have bugs that cause this test to fail: please update." >&2
854458
+        exit 1
854458
+    fi
854458
+else
854458
+    echo "I:This test requires the Net::DNS library." >&2
854458
+    exit 1
854458
+fi
854458
+if $PERL -e 'use Net::DNS::Nameserver;' 2>/dev/null
854458
+then
854458
+	:
854458
+else
854458
+	echo "I:This test requires the Net::DNS::Nameserver library." >&2
854458
+	exit 1
854458
+fi
854458
+if $PERL -e 'use Time::HiRes;' 2>/dev/null
854458
+then
854458
+	:
854458
+else
854458
+	echo "I:This test requires the Time::HiRes library." >&2
854458
+	exit 1
854458
+fi
854458
diff --git a/bin/tests/system/serve-stale/setup.sh b/bin/tests/system/serve-stale/setup.sh
854458
new file mode 100644
74b53c
index 0000000..690f43c
854458
--- /dev/null
854458
+++ b/bin/tests/system/serve-stale/setup.sh
854458
@@ -0,0 +1,13 @@
854458
+#!/bin/sh
854458
+# Copyright (C) 2017  Internet Systems Consortium, Inc. ("ISC")
854458
+#
854458
+# This Source Code Form is subject to the terms of the Mozilla Public
854458
+# License, v. 2.0. If a copy of the MPL was not distributed with this
854458
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
854458
+
854458
+SYSTEMTESTTOP=..
854458
+. $SYSTEMTESTTOP/conf.sh
854458
+
854458
+copy_setports ns1/named1.conf.in ns1/named.conf
854458
+copy_setports ans2/ans.pl.in ans2/ans.pl
854458
+copy_setports ns3/named.conf.in ns3/named.conf
854458
diff --git a/bin/tests/system/serve-stale/tests.sh b/bin/tests/system/serve-stale/tests.sh
854458
new file mode 100755
74b53c
index 0000000..201c996
854458
--- /dev/null
854458
+++ b/bin/tests/system/serve-stale/tests.sh
854458
@@ -0,0 +1,536 @@
854458
+#!/bin/sh
854458
+#
854458
+# Copyright (C) 2000, 2001, 2004, 2007, 2009-2016  Internet Systems Consortium, Inc. ("ISC")
854458
+#
854458
+# This Source Code Form is subject to the terms of the Mozilla Public
854458
+# License, v. 2.0. If a copy of the MPL was not distributed with this
854458
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
854458
+
854458
+SYSTEMTESTTOP=..
854458
+. $SYSTEMTESTTOP/conf.sh
854458
+
854458
+while getopts "p:c:" flag; do
854458
+    case "$flag" in
854458
+	p) port=$OPTARG ;;
854458
+	c) controlport=$OPTARG ;;
854458
+	*) exit 1 ;;
854458
+    esac
854458
+done
854458
+
854458
+RNDCCMD="$RNDC -c $SYSTEMTESTTOP/common/rndc.conf -p ${CONTROLPORT} -s"
854458
+
854458
+echo "RNDCCMD: ${RNDCCMD}"
854458
+
854458
+status=0
854458
+n=0
854458
+
854458
+#echo "I:check ans.pl server ($n)"
854458
+#$DIG -p ${PORT} @10.53.0.2 example NS
854458
+#$DIG -p ${PORT} @10.53.0.2 example SOA
854458
+#$DIG -p ${PORT} @10.53.0.2 ns.example A
854458
+#$DIG -p ${PORT} @10.53.0.2 ns.example AAAA
854458
+#$DIG -p ${PORT} @10.53.0.2 txt enable
854458
+#$DIG -p ${PORT} @10.53.0.2 txt disable
854458
+#$DIG -p ${PORT} @10.53.0.2 ns.example AAAA
854458
+#$DIG -p ${PORT} @10.53.0.2 txt enable
854458
+#$DIG -p ${PORT} @10.53.0.2 ns.example AAAA
854458
+##$DIG -p ${PORT} @10.53.0.2 data.example TXT
854458
+#$DIG -p ${PORT} @10.53.0.2 nodata.example TXT
854458
+#$DIG -p ${PORT} @10.53.0.2 nxdomain.example TXT
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:prime cache data.example ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.1 data.example TXT > dig.out.test$n
854458
+grep "status: NOERROR" dig.out.test$n > /dev/null || ret=1
854458
+grep "ANSWER: 1," dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:prime cache nodata.example ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.1 nodata.example TXT > dig.out.test$n
854458
+grep "status: NOERROR" dig.out.test$n > /dev/null || ret=1
854458
+grep "ANSWER: 0," dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:prime cache nxdomain.example ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.1 nxdomain.example TXT > dig.out.test$n
854458
+grep "status: NXDOMAIN" dig.out.test$n > /dev/null || ret=1
854458
+grep "ANSWER: 0," dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:disable responses from authoritative server ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.2 txt disable  > dig.out.test$n
854458
+grep "ANSWER: 1," dig.out.test$n > /dev/null || ret=1
854458
+grep "TXT.\"0\"" dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+sleep 1
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check 'rndc serve-stale status' ($n)"
854458
+ret=0
854458
+$RNDCCMD 10.53.0.1 serve-stale status > rndc.out.test$n 2>&1 || ret=1
854458
+grep '_default: on (stale-answer-ttl=1 max-stale-ttl=3600)' rndc.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check stale data.example ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.1 data.example TXT > dig.out.test$n
854458
+grep "status: NOERROR" dig.out.test$n > /dev/null || ret=1
854458
+grep "ANSWER: 1," dig.out.test$n > /dev/null || ret=1
854458
+grep "example.*1.*IN" dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check stale nodata.example ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.1 nodata.example TXT > dig.out.test$n
854458
+grep "status: NOERROR" dig.out.test$n > /dev/null || ret=1
854458
+grep "ANSWER: 0," dig.out.test$n > /dev/null || ret=1
854458
+grep "example.*1.*IN" dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check stale nxdomain.example ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.1 nxdomain.example TXT > dig.out.test$n
854458
+grep "status: NXDOMAIN" dig.out.test$n > /dev/null || ret=1
854458
+grep "ANSWER: 0," dig.out.test$n > /dev/null || ret=1
854458
+grep "example.*1.*IN" dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:running 'rndc serve-stale off' ($n)"
854458
+ret=0
854458
+$RNDCCMD 10.53.0.1 serve-stale off || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check 'rndc serve-stale status' ($n)"
854458
+ret=0
854458
+$RNDCCMD 10.53.0.1 serve-stale status > rndc.out.test$n 2>&1 || ret=1
854458
+grep '_default: off (rndc) (stale-answer-ttl=1 max-stale-ttl=3600)' rndc.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check stale data.example (serve-stale off) ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.1 data.example TXT > dig.out.test$n
854458
+grep "status: SERVFAIL" dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check stale nodata.example (serve-stale off) ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.1 nodata.example TXT > dig.out.test$n
854458
+grep "status: SERVFAIL" dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check stale nxdomain.example (serve-stale off) ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.1 nxdomain.example TXT > dig.out.test$n
854458
+grep "status: SERVFAIL" dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:running 'rndc serve-stale on' ($n)"
854458
+ret=0
854458
+$RNDCCMD 10.53.0.1 serve-stale on || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check 'rndc serve-stale status' ($n)"
854458
+ret=0
854458
+$RNDCCMD 10.53.0.1 serve-stale status > rndc.out.test$n 2>&1 || ret=1
854458
+grep '_default: on (rndc) (stale-answer-ttl=1 max-stale-ttl=3600)' rndc.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check stale data.example (serve-stale on) ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.1 data.example TXT > dig.out.test$n
854458
+grep "status: NOERROR" dig.out.test$n > /dev/null || ret=1
854458
+grep "ANSWER: 1," dig.out.test$n > /dev/null || ret=1
854458
+grep "example.*1.*IN" dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check stale nodata.example (serve-stale on) ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.1 nodata.example TXT > dig.out.test$n
854458
+grep "status: NOERROR" dig.out.test$n > /dev/null || ret=1
854458
+grep "ANSWER: 0," dig.out.test$n > /dev/null || ret=1
854458
+grep "example.*1.*IN" dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check stale nxdomain.example (serve-stale on) ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.1 nxdomain.example TXT > dig.out.test$n
854458
+grep "status: NXDOMAIN" dig.out.test$n > /dev/null || ret=1
854458
+grep "ANSWER: 0," dig.out.test$n > /dev/null || ret=1
854458
+grep "example.*1.*IN" dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:running 'rndc serve-stale no' ($n)"
854458
+ret=0
854458
+$RNDCCMD 10.53.0.1 serve-stale no || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check 'rndc serve-stale status' ($n)"
854458
+ret=0
854458
+$RNDCCMD 10.53.0.1 serve-stale status > rndc.out.test$n 2>&1 || ret=1
854458
+grep '_default: off (rndc) (stale-answer-ttl=1 max-stale-ttl=3600)' rndc.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check stale data.example (serve-stale no) ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.1 data.example TXT > dig.out.test$n
854458
+grep "status: SERVFAIL" dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check stale nodata.example (serve-stale no) ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.1 nodata.example TXT > dig.out.test$n
854458
+grep "status: SERVFAIL" dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check stale nxdomain.example (serve-stale no) ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.1 nxdomain.example TXT > dig.out.test$n
854458
+grep "status: SERVFAIL" dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:running 'rndc serve-stale yes' ($n)"
854458
+ret=0
854458
+$RNDCCMD 10.53.0.1 serve-stale yes || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check 'rndc serve-stale status' ($n)"
854458
+ret=0
854458
+$RNDCCMD 10.53.0.1 serve-stale status > rndc.out.test$n 2>&1 || ret=1
854458
+grep '_default: on (rndc) (stale-answer-ttl=1 max-stale-ttl=3600)' rndc.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check stale data.example (serve-stale yes) ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.1 data.example TXT > dig.out.test$n
854458
+grep "status: NOERROR" dig.out.test$n > /dev/null || ret=1
854458
+grep "ANSWER: 1," dig.out.test$n > /dev/null || ret=1
854458
+grep "example.*1.*IN" dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check stale nodata.example (serve-stale yes) ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.1 nodata.example TXT > dig.out.test$n
854458
+grep "status: NOERROR" dig.out.test$n > /dev/null || ret=1
854458
+grep "ANSWER: 0," dig.out.test$n > /dev/null || ret=1
854458
+grep "example.*1.*IN" dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check stale nxdomain.example (serve-stale yes) ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.1 nxdomain.example TXT > dig.out.test$n
854458
+grep "status: NXDOMAIN" dig.out.test$n > /dev/null || ret=1
854458
+grep "ANSWER: 0," dig.out.test$n > /dev/null || ret=1
854458
+grep "example.*1.*IN" dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:running 'rndc serve-stale off' ($n)"
854458
+ret=0
854458
+$RNDCCMD 10.53.0.1 serve-stale off || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:running 'rndc serve-stale reset' ($n)"
854458
+ret=0
854458
+$RNDCCMD 10.53.0.1 serve-stale reset || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check 'rndc serve-stale status' ($n)"
854458
+ret=0
854458
+$RNDCCMD 10.53.0.1 serve-stale status > rndc.out.test$n 2>&1 || ret=1
854458
+grep '_default: on (stale-answer-ttl=1 max-stale-ttl=3600)' rndc.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check stale data.example (serve-stale reset) ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.1 data.example TXT > dig.out.test$n
854458
+grep "status: NOERROR" dig.out.test$n > /dev/null || ret=1
854458
+grep "ANSWER: 1," dig.out.test$n > /dev/null || ret=1
854458
+grep "example.*1.*IN" dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check stale nodata.example (serve-stale reset) ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.1 nodata.example TXT > dig.out.test$n
854458
+grep "status: NOERROR" dig.out.test$n > /dev/null || ret=1
854458
+grep "ANSWER: 0," dig.out.test$n > /dev/null || ret=1
854458
+grep "example.*1.*IN" dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check stale nxdomain.example (serve-stale reset) ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.1 nxdomain.example TXT > dig.out.test$n
854458
+grep "status: NXDOMAIN" dig.out.test$n > /dev/null || ret=1
854458
+grep "ANSWER: 0," dig.out.test$n > /dev/null || ret=1
854458
+grep "example.*1.*IN" dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:running 'rndc serve-stale off' ($n)"
854458
+ret=0
854458
+$RNDCCMD 10.53.0.1 serve-stale off || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check 'rndc serve-stale status' ($n)"
854458
+ret=0
854458
+$RNDCCMD 10.53.0.1 serve-stale status > rndc.out.test$n 2>&1 || ret=1
854458
+grep '_default: off (rndc) (stale-answer-ttl=1 max-stale-ttl=3600)' rndc.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:updating ns1/named.conf ($n)"
854458
+ret=0
854458
+sed -e "s/@PORT@/${PORT}/g;s/@CONTROLPORT@/${CONTROLPORT}/g" < ns1/named2.conf.in > ns1/named.conf
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:running 'rndc reload' ($n)"
854458
+ret=0
854458
+$RNDCCMD 10.53.0.1 reload > rndc.out.test$n 2>&1 || ret=1
854458
+grep "server reload successful" rndc.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check 'rndc serve-stale status' ($n)"
854458
+ret=0
854458
+$RNDCCMD 10.53.0.1 serve-stale status > rndc.out.test$n 2>&1 || ret=1
854458
+grep '_default: off (rndc) (stale-answer-ttl=2 max-stale-ttl=7200)' rndc.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check 'rndc serve-stale' ($n)"
854458
+ret=0
854458
+$RNDCCMD 10.53.0.1 serve-stale > rndc.out.test$n 2>&1 && ret=1
854458
+grep "unexpected end of input" rndc.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check 'rndc serve-stale unknown' ($n)"
854458
+ret=0
854458
+$RNDCCMD 10.53.0.1 serve-stale unknown > rndc.out.test$n 2>&1 && ret=1
854458
+grep "syntax error" rndc.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo_i "flush cache, re-enable serve-stale and query again ($n)"
854458
+ret=0
854458
+$RNDCCMD 10.53.0.1 flushtree example > rndc.out.test$n.1 2>&1 || ret=1
854458
+$RNDCCMD 10.53.0.1 serve-stale on > rndc.out.test$n.2 2>&1 || ret=1
854458
+$DIG -p ${PORT} @10.53.0.1 data.example TXT > dig.out.test$n
854458
+grep "status: SERVFAIL" dig.out.test$n > /dev/null || ret=1
854458
+grep "ANSWER: 0," dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo_i "failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.2 txt enable  > dig.out.test$n
854458
+grep "ANSWER: 1," dig.out.test$n > /dev/null || ret=1
854458
+grep "TXT.\"1\"" dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:prime cache data.example (max-stale-ttl default) ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.3 data.example TXT > dig.out.test$n
854458
+grep "status: NOERROR" dig.out.test$n > /dev/null || ret=1
854458
+grep "ANSWER: 1," dig.out.test$n > /dev/null || ret=1
854458
+grep "example.*1.*IN" dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:prime cache nodata.example (max-stale-ttl default) ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.3 nodata.example TXT > dig.out.test$n
854458
+grep "status: NOERROR" dig.out.test$n > /dev/null || ret=1
854458
+grep "ANSWER: 0," dig.out.test$n > /dev/null || ret=1
854458
+grep "example.*1.*IN" dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:prime cache nxdomain.example (max-stale-ttl default) ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.3 nxdomain.example TXT > dig.out.test$n
854458
+grep "status: NXDOMAIN" dig.out.test$n > /dev/null || ret=1
854458
+grep "ANSWER: 0," dig.out.test$n > /dev/null || ret=1
854458
+grep "example.*1.*IN" dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:disable responses from authoritative server ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.2 txt disable  > dig.out.test$n
854458
+grep "ANSWER: 1," dig.out.test$n > /dev/null || ret=1
854458
+grep "TXT.\"0\"" dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+sleep 1
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check 'rndc serve-stale status' ($n)"
854458
+ret=0
854458
+$RNDCCMD 10.53.0.3 serve-stale status > rndc.out.test$n 2>&1 || ret=1
854458
+grep '_default: off (stale-answer-ttl=1 max-stale-ttl=604800)' rndc.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check fail of data.example (max-stale-ttl default) ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.3 data.example TXT > dig.out.test$n
854458
+grep "status: SERVFAIL" dig.out.test$n > /dev/null || ret=1
854458
+grep "ANSWER: 0," dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check fail of nodata.example (max-stale-ttl default) ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.3 nodata.example TXT > dig.out.test$n
854458
+grep "status: SERVFAIL" dig.out.test$n > /dev/null || ret=1
854458
+grep "ANSWER: 0," dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check fail of nxdomain.example (max-stale-ttl default) ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.3 nxdomain.example TXT > dig.out.test$n
854458
+grep "status: SERVFAIL" dig.out.test$n > /dev/null || ret=1
854458
+grep "ANSWER: 0," dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check 'rndc serve-stale on' ($n)"
854458
+ret=0
854458
+$RNDCCMD 10.53.0.3 serve-stale on > rndc.out.test$n 2>&1 || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check 'rndc serve-stale status' ($n)"
854458
+ret=0
854458
+$RNDCCMD 10.53.0.3 serve-stale status > rndc.out.test$n 2>&1 || ret=1
854458
+grep '_default: on (rndc) (stale-answer-ttl=1 max-stale-ttl=604800)' rndc.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check data.example (max-stale-ttl default) ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.3 data.example TXT > dig.out.test$n
854458
+grep "status: NOERROR" dig.out.test$n > /dev/null || ret=1
854458
+grep "ANSWER: 1," dig.out.test$n > /dev/null || ret=1
854458
+grep "example.*1.*IN" dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check nodata.example (max-stale-ttl default) ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.3 nodata.example TXT > dig.out.test$n
854458
+grep "status: NOERROR" dig.out.test$n > /dev/null || ret=1
854458
+grep "ANSWER: 0," dig.out.test$n > /dev/null || ret=1
854458
+grep "example.*1.*IN" dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+n=`expr $n + 1`
854458
+echo "I:check nxdomain.example (max-stale-ttl default) ($n)"
854458
+ret=0
854458
+$DIG -p ${PORT} @10.53.0.3 nxdomain.example TXT > dig.out.test$n
854458
+grep "status: NXDOMAIN" dig.out.test$n > /dev/null || ret=1
854458
+grep "ANSWER: 0," dig.out.test$n > /dev/null || ret=1
854458
+grep "example.*1.*IN" dig.out.test$n > /dev/null || ret=1
854458
+if [ $ret != 0 ]; then echo "I:failed"; fi
854458
+status=`expr $status + $ret`
854458
+
854458
+echo "I:exit status: $status"
854458
+[ $status -eq 0 ] || exit 1
854458
diff --git a/doc/arm/Bv9ARM-book.xml b/doc/arm/Bv9ARM-book.xml
74b53c
index 539973c..8528649 100644
854458
--- a/doc/arm/Bv9ARM-book.xml
854458
+++ b/doc/arm/Bv9ARM-book.xml
854458
@@ -4376,6 +4376,9 @@ badresp:1,adberr:0,findfail:0,valfail:0]
854458
 	  statement in the <filename>named.conf</filename> file:
854458
 	</para>
854458
 	<xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="options.grammar.xml"/>
854458
+  [ <command>max-stale-ttl</command> <replaceable>number</replaceable> ; ]
854458
+  [ <command>stale-answer-enable</command> <replaceable>yes_or_no</replaceable> ; ]
854458
+  [ <command>stale-answer-ttl</command> <replaceable>number</replaceable> ; ]
854458
       </section>
854458
 
854458
       <section xml:id="options"><info><title><command>options</command> Statement Definition and
854458
@@ -4469,6 +4472,7 @@ badresp:1,adberr:0,findfail:0,valfail:0]
854458
 		  <command>dnssec-validation</command>,
854458
 		  <command>max-cache-ttl</command>,
854458
 		  <command>max-ncache-ttl</command>,
854458
+		  <command>max-stale-ttl</command>,
854458
 		  <command>max-cache-size</command>, and
854458
 		  <command>zero-no-soa-ttl</command>.
854458
 		</para>
854458
@@ -5480,7 +5484,6 @@ options {
854458
 	    </listitem>
854458
 	  </varlistentry>
854458
 
854458
-
854458
 	  <varlistentry>
854458
 	    <term><command>max-zone-ttl</command></term>
854458
 	    <listitem>
854458
@@ -5516,6 +5519,21 @@ options {
854458
 	    </listitem>
854458
 	  </varlistentry>
854458
 
854458
+	  <varlistentry>
854458
+	    <term><command>stale-answer-ttl</command></term>
854458
+	    <listitem>
854458
+	      <para>
854458
+		Specifies the TTL to be returned on stale answers.
854458
+		The default is 1 second. The minimal allowed is
854458
+		also 1 second; a value of 0 will be updated silently
854458
+		to 1 second.  For stale answers to be returned
854458
+		<option>max-stale-ttl</option> must be set to a
854458
+		non zero value and they must not have been disabled
854458
+		by <command>rndc</command>.
854458
+	      </para>
854458
+	    </listitem>
854458
+	  </varlistentry>
854458
+
854458
 	  <varlistentry>
854458
 	    <term><command>serial-update-method</command></term>
854458
 	    <listitem>
74b53c
@@ -6275,6 +6293,22 @@ options {
854458
 	      </listitem>
854458
 	    </varlistentry>
854458
 
854458
+	    <varlistentry>
854458
+	      <term><command>serve-stale-enable</command></term>
854458
+	      <listitem>
854458
+		<para>
854458
+		  Enable the returning of stale answers when the
854458
+		  nameservers for the zone are not answering.  This
854458
+		  is off by default but can be enabled/disabled via
854458
+		  <command>rndc server-stale on</command> and
854458
+		  <command>rndc server-stale off</command> which
854458
+		  override the named.conf setting.  <command>rndc
854458
+		  server-stale reset</command> will restore control
854458
+		  via named.conf.
854458
+		</para>
854458
+	      </listitem>
854458
+	    </varlistentry>
854458
+
854458
 	    <varlistentry>
854458
 	      <term><command>nocookie-udp-size</command></term>
854458
 	      <listitem>
74b53c
@@ -7483,14 +7517,20 @@ options {
854458
 	      <term><command>resolver-query-timeout</command></term>
854458
 	      <listitem>
854458
 		<para>
854458
-		  The amount of time in seconds that the resolver
854458
+		  The amount of time in milliseconds that the resolver
854458
 		  will spend attempting to resolve a recursive
854458
 		  query before failing.  The default and minimum
854458
-		  is <literal>10</literal> and the maximum is
854458
-		  <literal>30</literal>.  Setting it to
854458
+		  is <literal>10000</literal> and the maximum is
854458
+		  <literal>30000</literal>.  Setting it to
854458
 		  <literal>0</literal> will result in the default
854458
 		  being used.
854458
 		</para>
854458
+		<para>
854458
+		  This value was originally specified in seconds.
854458
+		  Values less than or equal to 300 will be be treated
854458
+		  as seconds and converted to milliseconds before
854458
+		  applying the above limits.
854458
+		</para>
854458
 	      </listitem>
854458
 	    </varlistentry>
854458
 	  </variablelist>
74b53c
@@ -8976,6 +9016,27 @@ avoid-v6-udp-ports { 40000; range 50000 60000; };
854458
 	      </listitem>
854458
 	    </varlistentry>
854458
 
854458
+	    <varlistentry>
854458
+	      <term><command>max-stale-ttl</command></term>
854458
+	      <listitem>
854458
+		<para>
854458
+		  Sets the maximum time for which the server will
854458
+		  retain records past their normal expiry to
854458
+		  return them as stale records when the servers
854458
+		  for those records are not reachable.  The default
854458
+		  is to not retain the record.
854458
+		</para>
854458
+		<para>
854458
+		  <command>rndc serve-stale</command> can be used
854458
+		  to disable and re-enable the serving of stale
854458
+		  records at runtime.  Reloading or reconfiguring
854458
+		  <command>named</command> will not re-enable serving
854458
+		  of stale records if they have been disabled via
854458
+		  <command>rndc</command>.
854458
+		</para>
854458
+	      </listitem>
854458
+	    </varlistentry>
854458
+
854458
 	    <varlistentry>
854458
 	      <term><command>min-roots</command></term>
854458
 	      <listitem>
854458
diff --git a/doc/arm/logging-categories.xml b/doc/arm/logging-categories.xml
74b53c
index 181def7..59f6afb 100644
854458
--- a/doc/arm/logging-categories.xml
854458
+++ b/doc/arm/logging-categories.xml
854458
@@ -311,6 +311,17 @@
854458
 	  </para>
854458
 	</entry>
854458
       </row>
854458
+      <row rowsep="0">
854458
+	<entry colname="1">
854458
+	  <para><command>serve-stale</command></para>
854458
+	</entry>
854458
+	<entry colname="2">
854458
+	  <para>
854458
+	    Whether or not a stale answer is used
854458
+	    following a resolver failure.
854458
+	  </para>
854458
+	</entry>
854458
+      </row>
854458
       <row rowsep="0">
854458
 	<entry colname="1">
854458
 	  <para><command>spill</command></para>
854458
diff --git a/doc/arm/notes-rh-changes.xml b/doc/arm/notes-rh-changes.xml
74b53c
index 11c3a7c..ba3c2cc 100644
854458
--- a/doc/arm/notes-rh-changes.xml
854458
+++ b/doc/arm/notes-rh-changes.xml
854458
@@ -13,6 +13,9 @@
854458
 <section xml:id="relnotes_rh_changes"><info><title>Red Hat Specific Changes</title></info>
854458
   <itemizedlist>
854458
      <listitem>
854458
+      <para>
854458
+        This version includes some features not present in releases by ISC.
854458
+      </para>
854458
       <para>
854458
         By default, BIND now uses the random number generation functions
854458
         in the cryptographic library (i.e., OpenSSL or a PKCS#11
854458
@@ -37,7 +40,16 @@
854458
         case <filename>/dev/random</filename> will be the default
854458
         entropy source.  [RT #31459] [RT #46047]
854458
       </para>
854458
-    </listitem>
854458
+      <para>
854458
+        When acting as a recursive resolver, <command>named</command>
854458
+        can now continue returning answers whose TTLs have expired
854458
+        when the authoritative server is under attack and unable to
854458
+        respond. This is controlled by the
854458
+        <command>stale-answer-enable</command>,
854458
+        <command>stale-answer-ttl</command> and
854458
+        <command>max-stale-ttl</command> options. [RT #44790]
854458
+      </para>
854458
+     </listitem>
854458
   </itemizedlist>
854458
 </section>
854458
 
854458
diff --git a/doc/misc/options b/doc/misc/options
74b53c
index e11beed..fde93c7 100644
854458
--- a/doc/misc/options
854458
+++ b/doc/misc/options
854458
@@ -225,6 +225,7 @@ options {
854458
         max-refresh-time <integer>;
854458
         max-retry-time <integer>;
854458
         max-rsa-exponent-size <integer>;
854458
+        max-stale-ttl <ttlval>;
854458
         max-transfer-idle-in <integer>;
854458
         max-transfer-idle-out <integer>;
854458
         max-transfer-time-in <integer>;
854458
@@ -298,7 +299,9 @@ options {
854458
         request-sit <boolean>; // obsolete
854458
         require-server-cookie <boolean>;
854458
         reserved-sockets <integer>;
854458
+        resolver-nonbackoff-tries <integer>;
854458
         resolver-query-timeout <integer>;
854458
+        resolver-retry-interval <integer>;
854458
         response-policy { zone <string> [ log <boolean> ] [ max-policy-ttl
854458
             <integer> ] [ policy ( cname | disabled | drop | given | no-op
854458
             | nodata | nxdomain | passthru | tcp-only <quoted_string> ) ] [
854458
@@ -328,6 +331,8 @@ options {
854458
         sit-secret <string>; // obsolete
854458
         sortlist { <address_match_element>; ... };
854458
         stacksize ( default | unlimited | <sizeval> );
854458
+        stale-answer-enable <boolean>;
854458
+        stale-answer-ttl <ttlval>;
854458
         startup-notify-rate <integer>;
854458
         statistics-file <quoted_string>;
854458
         statistics-interval <integer>; // not yet implemented
854458
@@ -539,6 +544,7 @@ view <string> [ <class> ] {
854458
         max-recursion-queries <integer>;
854458
         max-refresh-time <integer>;
854458
         max-retry-time <integer>;
854458
+        max-stale-ttl <ttlval>;
854458
         max-transfer-idle-in <integer>;
854458
         max-transfer-idle-out <integer>;
854458
         max-transfer-time-in <integer>;
854458
@@ -600,7 +606,9 @@ view <string> [ <class> ] {
854458
         request-nsid <boolean>;
854458
         request-sit <boolean>; // obsolete
854458
         require-server-cookie <boolean>;
854458
+        resolver-nonbackoff-tries <integer>;
854458
         resolver-query-timeout <integer>;
854458
+        resolver-retry-interval <integer>;
854458
         response-policy { zone <string> [ log <boolean> ] [ max-policy-ttl
854458
             <integer> ] [ policy ( cname | disabled | drop | given | no-op
854458
             | nodata | nxdomain | passthru | tcp-only <quoted_string> ) ] [
854458
@@ -655,6 +663,8 @@ view <string> [ <class> ] {
854458
         sig-signing-type <integer>;
854458
         sig-validity-interval <integer> [ <integer> ];
854458
         sortlist { <address_match_element>; ... };
854458
+        stale-answer-enable <boolean>;
854458
+        stale-answer-ttl <ttlval>;
854458
         suppress-initial-notify <boolean>; // not yet implemented
854458
         topology { <address_match_element>; ... }; // not implemented
854458
         transfer-format ( many-answers | one-answer );
854458
diff --git a/lib/bind9/check.c b/lib/bind9/check.c
74b53c
index 5c057a4..7b82618 100644
854458
--- a/lib/bind9/check.c
854458
+++ b/lib/bind9/check.c
854458
@@ -99,7 +99,8 @@ check_orderent(const cfg_obj_t *ent, isc_log_t *logctx) {
854458
 			cfg_obj_log(obj, logctx, ISC_LOG_ERROR,
854458
 				    "rrset-order: invalid class '%s'",
854458
 				    r.base);
854458
-			result = ISC_R_FAILURE;
854458
+			if (result == ISC_R_SUCCESS)
854458
+				result = ISC_R_FAILURE;
854458
 		}
854458
 	}
854458
 
854458
@@ -112,7 +113,8 @@ check_orderent(const cfg_obj_t *ent, isc_log_t *logctx) {
854458
 			cfg_obj_log(obj, logctx, ISC_LOG_ERROR,
854458
 				    "rrset-order: invalid type '%s'",
854458
 				    r.base);
854458
-			result = ISC_R_FAILURE;
854458
+			if (result == ISC_R_SUCCESS)
854458
+				result = ISC_R_FAILURE;
854458
 		}
854458
 	}
854458
 
854458
@@ -126,7 +128,8 @@ check_orderent(const cfg_obj_t *ent, isc_log_t *logctx) {
854458
 		if (tresult != ISC_R_SUCCESS) {
854458
 			cfg_obj_log(obj, logctx, ISC_LOG_ERROR,
854458
 				    "rrset-order: invalid name '%s'", str);
854458
-			result = ISC_R_FAILURE;
854458
+			if (result == ISC_R_SUCCESS)
854458
+				result = ISC_R_FAILURE;
854458
 		}
854458
 	}
854458
 
854458
@@ -135,14 +138,16 @@ check_orderent(const cfg_obj_t *ent, isc_log_t *logctx) {
854458
 	    strcasecmp("order", cfg_obj_asstring(obj)) != 0) {
854458
 		cfg_obj_log(ent, logctx, ISC_LOG_ERROR,
854458
 			    "rrset-order: keyword 'order' missing");
854458
-		result = ISC_R_FAILURE;
854458
+		if (result == ISC_R_SUCCESS)
854458
+			result = ISC_R_FAILURE;
854458
 	}
854458
 
854458
 	obj = cfg_tuple_get(ent, "ordering");
854458
 	if (!cfg_obj_isstring(obj)) {
854458
 	    cfg_obj_log(ent, logctx, ISC_LOG_ERROR,
854458
 			"rrset-order: missing ordering");
854458
-		result = ISC_R_FAILURE;
854458
+		if (result == ISC_R_SUCCESS)
854458
+			result = ISC_R_FAILURE;
854458
 	} else if (strcasecmp(cfg_obj_asstring(obj), "fixed") == 0) {
854458
 #if !DNS_RDATASET_FIXED
854458
 		cfg_obj_log(obj, logctx, ISC_LOG_WARNING,
854458
@@ -154,7 +159,8 @@ check_orderent(const cfg_obj_t *ent, isc_log_t *logctx) {
854458
 		cfg_obj_log(obj, logctx, ISC_LOG_ERROR,
854458
 			    "rrset-order: invalid order '%s'",
854458
 			    cfg_obj_asstring(obj));
854458
-		result = ISC_R_FAILURE;
854458
+		if (result == ISC_R_SUCCESS)
854458
+			result = ISC_R_FAILURE;
854458
 	}
854458
 	return (result);
854458
 }
854458
@@ -174,7 +180,7 @@ check_order(const cfg_obj_t *options, isc_log_t *logctx) {
854458
 	     element = cfg_list_next(element))
854458
 	{
854458
 		tresult = check_orderent(cfg_listelt_value(element), logctx);
854458
-		if (tresult != ISC_R_SUCCESS)
854458
+		if (result == ISC_R_SUCCESS && tresult != ISC_R_SUCCESS)
854458
 			result = tresult;
854458
 	}
854458
 	return (result);
854458
@@ -204,7 +210,8 @@ check_dual_stack(const cfg_obj_t *options, isc_log_t *logctx) {
854458
 		if (val > UINT16_MAX) {
854458
 			cfg_obj_log(obj, logctx, ISC_LOG_ERROR,
854458
 				    "port '%u' out of range", val);
854458
-			result = ISC_R_FAILURE;
854458
+			if (result == ISC_R_SUCCESS)
854458
+				result = ISC_R_RANGE;
854458
 		}
854458
 	}
854458
 	obj = cfg_tuple_get(alternates, "addresses");
854458
@@ -224,7 +231,8 @@ check_dual_stack(const cfg_obj_t *options, isc_log_t *logctx) {
854458
 		if (tresult != ISC_R_SUCCESS) {
854458
 			cfg_obj_log(obj, logctx, ISC_LOG_ERROR,
854458
 				    "bad name '%s'", str);
854458
-			result = ISC_R_FAILURE;
854458
+			if (result == ISC_R_SUCCESS)
854458
+				result = tresult;
854458
 		}
854458
 		obj = cfg_tuple_get(value, "port");
854458
 		if (cfg_obj_isuint32(obj)) {
854458
@@ -232,7 +240,8 @@ check_dual_stack(const cfg_obj_t *options, isc_log_t *logctx) {
854458
 			if (val > UINT16_MAX) {
854458
 				cfg_obj_log(obj, logctx, ISC_LOG_ERROR,
854458
 					    "port '%u' out of range", val);
854458
-				result = ISC_R_FAILURE;
854458
+				if (result == ISC_R_SUCCESS)
854458
+					result = ISC_R_RANGE;
854458
 			}
854458
 		}
854458
 	}
854458
@@ -1267,7 +1276,8 @@ check_options(const cfg_obj_t *options, isc_log_t *logctx, isc_mem_t *mctx,
854458
 			cfg_obj_log(obj, logctx, ISC_LOG_ERROR,
854458
 				    "auto-dnssec may only be activated at the "
854458
 				    "zone level");
854458
-			result = ISC_R_FAILURE;
854458
+			if (result == ISC_R_SUCCESS)
854458
+				result = ISC_R_FAILURE;
854458
 		}
854458
 	}
854458
 
854458
@@ -1287,7 +1297,7 @@ check_options(const cfg_obj_t *options, isc_log_t *logctx, isc_mem_t *mctx,
854458
 		{
854458
 			obj = cfg_listelt_value(element);
854458
 			tresult = mustbesecure(obj, symtab, logctx, mctx);
854458
-			if (tresult != ISC_R_SUCCESS)
854458
+			if (result == ISC_R_SUCCESS && tresult != ISC_R_SUCCESS)
854458
 				result = tresult;
854458
 		}
854458
 		if (symtab != NULL)
854458
@@ -1306,7 +1316,8 @@ check_options(const cfg_obj_t *options, isc_log_t *logctx, isc_mem_t *mctx,
854458
 				cfg_obj_log(obj, logctx, ISC_LOG_ERROR,
854458
 					    "%s: invalid name '%s'",
854458
 					    server_contact[i], str);
854458
-				result = ISC_R_FAILURE;
854458
+				if (result == ISC_R_SUCCESS)
854458
+					result = ISC_R_FAILURE;
854458
 			}
854458
 		}
854458
 	}
854458
@@ -1326,7 +1337,8 @@ check_options(const cfg_obj_t *options, isc_log_t *logctx, isc_mem_t *mctx,
854458
 			cfg_obj_log(obj, logctx, ISC_LOG_ERROR,
854458
 				    "disable-empty-zone: invalid name '%s'",
854458
 				    str);
854458
-			result = ISC_R_FAILURE;
854458
+			if (result == ISC_R_SUCCESS)
854458
+				result = ISC_R_FAILURE;
854458
 		}
854458
 	}
854458
 
854458
@@ -1340,11 +1352,12 @@ check_options(const cfg_obj_t *options, isc_log_t *logctx, isc_mem_t *mctx,
854458
 	    strlen(cfg_obj_asstring(obj)) > 1024U) {
854458
 		cfg_obj_log(obj, logctx, ISC_LOG_ERROR,
854458
 			    "'server-id' too big (>1024 bytes)");
854458
-		result = ISC_R_FAILURE;
854458
+		if (result == ISC_R_SUCCESS)
854458
+			result = ISC_R_FAILURE;
854458
 	}
854458
 
854458
 	tresult = check_dscp(options, logctx);
854458
-	if (tresult != ISC_R_SUCCESS)
854458
+	if (result == ISC_R_SUCCESS && tresult != ISC_R_SUCCESS)
854458
 		result = tresult;
854458
 
854458
 	obj = NULL;
854458
@@ -1354,11 +1367,13 @@ check_options(const cfg_obj_t *options, isc_log_t *logctx, isc_mem_t *mctx,
854458
 		if (lifetime > 604800) {	/* 7 days */
854458
 			cfg_obj_log(obj, logctx, ISC_LOG_ERROR,
854458
 				    "'nta-lifetime' cannot exceed one week");
854458
-			result = ISC_R_RANGE;
854458
+			if (result == ISC_R_SUCCESS)
854458
+				result = ISC_R_RANGE;
854458
 		} else if (lifetime == 0) {
854458
 			cfg_obj_log(obj, logctx, ISC_LOG_ERROR,
854458
 				    "'nta-lifetime' may not be zero");
854458
-			result = ISC_R_RANGE;
854458
+			if (result == ISC_R_SUCCESS)
854458
+				result = ISC_R_RANGE;
854458
 		}
854458
 	}
854458
 
854458
@@ -1369,7 +1384,8 @@ check_options(const cfg_obj_t *options, isc_log_t *logctx, isc_mem_t *mctx,
854458
 		if (recheck > 604800) {		/* 7 days */
854458
 			cfg_obj_log(obj, logctx, ISC_LOG_ERROR,
854458
 				    "'nta-recheck' cannot exceed one week");
854458
-			result = ISC_R_RANGE;
854458
+			if (result == ISC_R_SUCCESS)
854458
+				result = ISC_R_RANGE;
854458
 		}
854458
 
854458
 		if (recheck > lifetime)
854458
@@ -1387,7 +1403,8 @@ check_options(const cfg_obj_t *options, isc_log_t *logctx, isc_mem_t *mctx,
854458
 	if (strcasecmp(ccalg, "aes") == 0) {
854458
 		cfg_obj_log(obj, logctx, ISC_LOG_ERROR,
854458
 			    "cookie-algorithm: '%s' not supported", ccalg);
854458
-		result = ISC_R_NOTIMPLEMENTED;
854458
+		if (result == ISC_R_SUCCESS)
854458
+			result = ISC_R_NOTIMPLEMENTED;
854458
 	}
854458
 #endif
854458
 
854458
@@ -1476,7 +1493,8 @@ check_options(const cfg_obj_t *options, isc_log_t *logctx, isc_mem_t *mctx,
854458
 				cfg_obj_log(obj, logctx, ISC_LOG_ERROR,
854458
 					    "%s out of range (%u < %u)",
854458
 					    fstrm[i].name, value, fstrm[i].min);
854458
-			result = ISC_R_RANGE;
854458
+			if (result == ISC_R_SUCCESS)
854458
+				result = ISC_R_RANGE;
854458
 		}
854458
 
854458
 		if (strcmp(fstrm[i].name, "fstrm-set-input-queue-size") == 0) {
854458
@@ -1490,7 +1508,8 @@ check_options(const cfg_obj_t *options, isc_log_t *logctx, isc_mem_t *mctx,
854458
 					    "%s '%u' not a power-of-2",
854458
 					    fstrm[i].name,
854458
 					    cfg_obj_asuint32(obj));
854458
-				result = ISC_R_RANGE;
854458
+				if (result == ISC_R_SUCCESS)
854458
+					result = ISC_R_RANGE;
854458
 			}
854458
 		}
854458
 	}
74b53c
@@ -1508,7 +1527,8 @@ check_options(const cfg_obj_t *options, isc_log_t *logctx, isc_mem_t *mctx,
854458
 				    "%" PRId64 "' "
854458
 				    "is too small",
854458
 				    mapsize);
854458
-			return (ISC_R_RANGE);
854458
+			if (result == ISC_R_SUCCESS)
854458
+				result = ISC_R_RANGE;
854458
 		} else if (mapsize > (1ULL << 40)) { /* 1 terabyte */
854458
 			cfg_obj_log(obj, logctx,
854458
 				    ISC_LOG_ERROR,
74b53c
@@ -1516,10 +1536,20 @@ check_options(const cfg_obj_t *options, isc_log_t *logctx, isc_mem_t *mctx,
854458
 				    "%" PRId64 "' "
854458
 				    "is too large",
854458
 				    mapsize);
854458
-			return (ISC_R_RANGE);
854458
+			if (result == ISC_R_SUCCESS)
854458
+				result = ISC_R_RANGE;
854458
 		}
854458
 	}
854458
 
854458
+	obj = NULL;
854458
+	(void)cfg_map_get(options, "resolver-nonbackoff-tries", &obj);
854458
+	if (obj != NULL && cfg_obj_asuint32(obj) == 0U) {
854458
+		cfg_obj_log(obj, logctx, ISC_LOG_ERROR,
854458
+			    "'resolver-nonbackoff-tries' must be >= 1");
854458
+		if (result == ISC_R_SUCCESS)
854458
+			result = ISC_R_RANGE;
854458
+	}
854458
+
854458
 	return (result);
854458
 }
854458
 
854458
diff --git a/lib/dns/cache.c b/lib/dns/cache.c
74b53c
index 4701ff8..97e427a 100644
854458
--- a/lib/dns/cache.c
854458
+++ b/lib/dns/cache.c
854458
@@ -138,6 +138,7 @@ struct dns_cache {
854458
 	int			db_argc;
854458
 	char			**db_argv;
854458
 	size_t			size;
854458
+	dns_ttl_t		serve_stale_ttl;
854458
 	isc_stats_t		*stats;
854458
 
854458
 	/* Locked by 'filelock'. */
854458
@@ -167,9 +168,13 @@ overmem_cleaning_action(isc_task_t *task, isc_event_t *event);
854458
 
854458
 static inline isc_result_t
854458
 cache_create_db(dns_cache_t *cache, dns_db_t **db) {
854458
-	return (dns_db_create(cache->mctx, cache->db_type, dns_rootname,
854458
-			      dns_dbtype_cache, cache->rdclass,
854458
-			      cache->db_argc, cache->db_argv, db));
854458
+	isc_result_t result;
854458
+	result = dns_db_create(cache->mctx, cache->db_type, dns_rootname,
854458
+			       dns_dbtype_cache, cache->rdclass,
854458
+			       cache->db_argc, cache->db_argv, db);
854458
+	if (result == ISC_R_SUCCESS)
854458
+		dns_db_setservestalettl(*db, cache->serve_stale_ttl);
854458
+	return (result);
854458
 }
854458
 
854458
 isc_result_t
854458
@@ -238,6 +243,7 @@ dns_cache_create3(isc_mem_t *cmctx, isc_mem_t *hmctx, isc_taskmgr_t *taskmgr,
854458
 	cache->references = 1;
854458
 	cache->live_tasks = 0;
854458
 	cache->rdclass = rdclass;
854458
+	cache->serve_stale_ttl = 0;
854458
 
854458
 	cache->stats = NULL;
854458
 	result = isc_stats_create(cmctx, &cache->stats,
854458
@@ -1092,6 +1098,32 @@ dns_cache_getcachesize(dns_cache_t *cache) {
854458
 	return (size);
854458
 }
854458
 
854458
+void
854458
+dns_cache_setservestalettl(dns_cache_t *cache, dns_ttl_t ttl) {
854458
+	REQUIRE(VALID_CACHE(cache));
854458
+
854458
+	LOCK(&cache->lock);
854458
+	cache->serve_stale_ttl = ttl;
854458
+	UNLOCK(&cache->lock);
854458
+
854458
+	(void)dns_db_setservestalettl(cache->db, ttl);
854458
+}
854458
+
854458
+dns_ttl_t
854458
+dns_cache_getservestalettl(dns_cache_t *cache) {
854458
+	dns_ttl_t ttl;
854458
+	isc_result_t result;
854458
+
854458
+	REQUIRE(VALID_CACHE(cache));
854458
+
854458
+	/*
854458
+	 * Could get it straight from the dns_cache_t, but use db
854458
+	 * to confirm the value that the db is really using.
854458
+	 */
854458
+	result = dns_db_getservestalettl(cache->db, &ttl);
854458
+	return result == ISC_R_SUCCESS ? ttl : 0;
854458
+}
854458
+
854458
 /*
854458
  * The cleaner task is shutting down; do the necessary cleanup.
854458
  */
854458
diff --git a/lib/dns/db.c b/lib/dns/db.c
74b53c
index ee3e00d..576aa65 100644
854458
--- a/lib/dns/db.c
854458
+++ b/lib/dns/db.c
854458
@@ -1130,3 +1130,25 @@ dns_db_nodefullname(dns_db_t *db, dns_dbnode_t *node, dns_name_t *name) {
854458
 		return (ISC_R_NOTIMPLEMENTED);
854458
 	return ((db->methods->nodefullname)(db, node, name));
854458
 }
854458
+
854458
+isc_result_t
854458
+dns_db_setservestalettl(dns_db_t *db, dns_ttl_t ttl)
854458
+{
854458
+	REQUIRE(DNS_DB_VALID(db));
854458
+	REQUIRE((db->attributes & DNS_DBATTR_CACHE) != 0);
854458
+
854458
+	if (db->methods->setservestalettl != NULL)
854458
+		return ((db->methods->setservestalettl)(db, ttl));
854458
+	return (ISC_R_NOTIMPLEMENTED);
854458
+}
854458
+
854458
+isc_result_t
854458
+dns_db_getservestalettl(dns_db_t *db, dns_ttl_t *ttl)
854458
+{
854458
+	REQUIRE(DNS_DB_VALID(db));
854458
+	REQUIRE((db->attributes & DNS_DBATTR_CACHE) != 0);
854458
+
854458
+	if (db->methods->getservestalettl != NULL)
854458
+		return ((db->methods->getservestalettl)(db, ttl));
854458
+	return (ISC_R_NOTIMPLEMENTED);
854458
+}
854458
diff --git a/lib/dns/ecdb.c b/lib/dns/ecdb.c
74b53c
index 47994ea..23bfe7d 100644
854458
--- a/lib/dns/ecdb.c
854458
+++ b/lib/dns/ecdb.c
854458
@@ -588,7 +588,9 @@ static dns_dbmethods_t ecdb_methods = {
854458
 	NULL,			/* setcachestats */
854458
 	NULL,			/* hashsize */
854458
 	NULL,			/* nodefullname */
854458
-	NULL			/* getsize */
854458
+	NULL,			/* getsize */
854458
+	NULL,			/* setservestalettl */
854458
+	NULL			/* getservestalettl */
854458
 };
854458
 
854458
 static isc_result_t
854458
diff --git a/lib/dns/include/dns/cache.h b/lib/dns/include/dns/cache.h
74b53c
index 62797db..714b78e 100644
854458
--- a/lib/dns/include/dns/cache.h
854458
+++ b/lib/dns/include/dns/cache.h
854458
@@ -260,6 +260,27 @@ dns_cache_getcachesize(dns_cache_t *cache);
854458
  * Get the maximum cache size.
854458
  */
854458
 
854458
+void
854458
+dns_cache_setservestalettl(dns_cache_t *cache, dns_ttl_t ttl);
854458
+/*%<
854458
+ * Sets the maximum length of time that cached answers may be retained
854458
+ * past their normal TTL.  Default value for the library is 0, disabling
854458
+ * the use of stale data.
854458
+ *
854458
+ * Requires:
854458
+ *\li	'cache' to be valid.
854458
+ */
854458
+
854458
+dns_ttl_t
854458
+dns_cache_getservestalettl(dns_cache_t *cache);
854458
+/*%<
854458
+ * Gets the maximum length of time that cached answers may be kept past
854458
+ * normal expiry.
854458
+ *
854458
+ * Requires:
854458
+ *\li	'cache' to be valid.
854458
+ */
854458
+
854458
 isc_result_t
854458
 dns_cache_flush(dns_cache_t *cache);
854458
 /*%<
854458
diff --git a/lib/dns/include/dns/db.h b/lib/dns/include/dns/db.h
74b53c
index ae6ae36..5079053 100644
854458
--- a/lib/dns/include/dns/db.h
854458
+++ b/lib/dns/include/dns/db.h
854458
@@ -197,6 +197,8 @@ typedef struct dns_dbmethods {
854458
 					dns_name_t *name);
854458
 	isc_result_t	(*getsize)(dns_db_t *db, dns_dbversion_t *version,
854458
 				   uint64_t *records, uint64_t *bytes);
854458
+	isc_result_t	(*setservestalettl)(dns_db_t *db, dns_ttl_t ttl);
854458
+	isc_result_t	(*getservestalettl)(dns_db_t *db, dns_ttl_t *ttl);
854458
 } dns_dbmethods_t;
854458
 
854458
 typedef isc_result_t
854458
@@ -255,6 +257,7 @@ struct dns_dbonupdatelistener {
854458
 #define DNS_DBFIND_FORCENSEC3		0x0080
854458
 #define DNS_DBFIND_ADDITIONALOK		0x0100
854458
 #define DNS_DBFIND_NOZONECUT		0x0200
854458
+#define DNS_DBFIND_STALEOK		0x0400
854458
 /*@}*/
854458
 
854458
 /*@{*/
854458
@@ -1685,6 +1688,38 @@ dns_db_nodefullname(dns_db_t *db, dns_dbnode_t *node, dns_name_t *name);
854458
  * \li	'db' is a valid database
854458
  * \li	'node' and 'name' are not NULL
854458
  */
854458
+
854458
+isc_result_t
854458
+dns_db_setservestalettl(dns_db_t *db, dns_ttl_t ttl);
854458
+/*%<
854458
+ * Sets the maximum length of time that cached answers may be retained
854458
+ * past their normal TTL. Default value for the library is 0, disabling
854458
+ * the use of stale data.
854458
+ *
854458
+ * Requires:
854458
+ * \li	'db' is a valid cache database.
854458
+ * \li	'ttl' is the number of seconds to retain data past its normal expiry.
854458
+ *
854458
+ * Returns:
854458
+ * \li	#ISC_R_SUCCESS
854458
+ * \li	#ISC_R_NOTIMPLEMENTED - Not supported by this DB implementation.
854458
+ */
854458
+
854458
+isc_result_t
854458
+dns_db_getservestalettl(dns_db_t *db, dns_ttl_t *ttl);
854458
+/*%<
854458
+ * Gets maximum length of time that cached answers may be kept past
854458
+ * normal TTL expiration.
854458
+ *
854458
+ * Requires:
854458
+ * \li	'db' is a valid cache database.
854458
+ * \li	'ttl' is the number of seconds to retain data past its normal expiry.
854458
+ *
854458
+ * Returns:
854458
+ * \li	#ISC_R_SUCCESS
854458
+ * \li	#ISC_R_NOTIMPLEMENTED - Not supported by this DB implementation.
854458
+ */
854458
+
854458
 ISC_LANG_ENDDECLS
854458
 
854458
 #endif /* DNS_DB_H */
854458
diff --git a/lib/dns/include/dns/rdataset.h b/lib/dns/include/dns/rdataset.h
74b53c
index 5295d8e..97071ed 100644
854458
--- a/lib/dns/include/dns/rdataset.h
854458
+++ b/lib/dns/include/dns/rdataset.h
854458
@@ -128,6 +128,7 @@ struct dns_rdataset {
854458
 	unsigned int			magic;		/* XXX ? */
854458
 	dns_rdatasetmethods_t *		methods;
854458
 	ISC_LINK(dns_rdataset_t)	link;
854458
+
854458
 	/*
854458
 	 * XXX do we need these, or should they be retrieved by methods?
854458
 	 * Leaning towards the latter, since they are not frequently required
854458
@@ -136,12 +137,19 @@ struct dns_rdataset {
854458
 	dns_rdataclass_t		rdclass;
854458
 	dns_rdatatype_t			type;
854458
 	dns_ttl_t			ttl;
854458
+	/*
854458
+	 * Stale ttl is used to see how long this RRset can still be used
854458
+	 * to serve to clients, after the TTL has expired.
854458
+	 */
854458
+	dns_ttl_t			stale_ttl;
854458
 	dns_trust_t			trust;
854458
 	dns_rdatatype_t			covers;
854458
+
854458
 	/*
854458
 	 * attributes
854458
 	 */
854458
 	unsigned int			attributes;
854458
+
854458
 	/*%
854458
 	 * the counter provides the starting point in the "cyclic" order.
854458
 	 * The value UINT32_MAX has a special meaning of "picking up a
854458
@@ -149,11 +157,13 @@ struct dns_rdataset {
854458
 	 * increment the counter.
854458
 	 */
854458
 	uint32_t			count;
854458
+
854458
 	/*
854458
 	 * This RRSIG RRset should be re-generated around this time.
854458
 	 * Only valid if DNS_RDATASETATTR_RESIGN is set in attributes.
854458
 	 */
854458
 	isc_stdtime_t			resign;
854458
+
854458
 	/*@{*/
854458
 	/*%
854458
 	 * These are for use by the rdataset implementation, and MUST NOT
854458
@@ -206,6 +216,7 @@ struct dns_rdataset {
854458
 #define DNS_RDATASETATTR_OPTOUT		0x00100000	/*%< OPTOUT proof */
854458
 #define DNS_RDATASETATTR_NEGATIVE	0x00200000
854458
 #define DNS_RDATASETATTR_PREFETCH	0x00400000
854458
+#define DNS_RDATASETATTR_STALE		0x01000000
854458
 
854458
 /*%
854458
  * _OMITDNSSEC:
854458
diff --git a/lib/dns/include/dns/resolver.h b/lib/dns/include/dns/resolver.h
74b53c
index 6da41b7..7b397cb 100644
854458
--- a/lib/dns/include/dns/resolver.h
854458
+++ b/lib/dns/include/dns/resolver.h
854458
@@ -547,9 +547,12 @@ dns_resolver_getmustbesecure(dns_resolver_t *resolver, dns_name_t *name);
854458
 
854458
 
854458
 void
854458
-dns_resolver_settimeout(dns_resolver_t *resolver, unsigned int seconds);
854458
+dns_resolver_settimeout(dns_resolver_t *resolver, unsigned int timeout);
854458
 /*%<
854458
- * Set the length of time the resolver will work on a query, in seconds.
854458
+ * Set the length of time the resolver will work on a query, in milliseconds.
854458
+ *
854458
+ * 'timeout' was originally defined in seconds, and later redefined to be in
854458
+ * milliseconds.  Values less than or equal to 300 are treated as seconds.
854458
  *
854458
  * If timeout is 0, the default timeout will be applied.
854458
  *
854458
@@ -560,7 +563,8 @@ dns_resolver_settimeout(dns_resolver_t *resolver, unsigned int seconds);
854458
 unsigned int
854458
 dns_resolver_gettimeout(dns_resolver_t *resolver);
854458
 /*%<
854458
- * Get the current length of time the resolver will work on a query, in seconds.
854458
+ * Get the current length of time the resolver will work on a query,
854458
+ * in milliseconds.
854458
  *
854458
  * Requires:
854458
  * \li  resolver to be valid.
854458
@@ -582,6 +586,39 @@ dns_resolver_getzeronosoattl(dns_resolver_t *resolver);
854458
 void
854458
 dns_resolver_setzeronosoattl(dns_resolver_t *resolver, bool state);
854458
 
854458
+unsigned int
854458
+dns_resolver_getretryinterval(dns_resolver_t *resolver);
854458
+
854458
+void
854458
+dns_resolver_setretryinterval(dns_resolver_t *resolver, unsigned int interval);
854458
+/*%<
854458
+ * Sets the amount of time, in millseconds, that is waited for a reply
854458
+ * to a server before another server is tried.  Interacts with the
854458
+ * value of dns_resolver_getnonbackofftries() by trying that number of times
854458
+ * at this interval, before doing exponential backoff and doubling the interval
854458
+ * on each subsequent try, to a maximum of 10 seconds.  Defaults to 800 ms;
854458
+ * silently capped at 2000 ms.
854458
+ *
854458
+ * Requires:
854458
+ * \li	resolver to be valid.
854458
+ * \li  interval > 0.
854458
+ */
854458
+
854458
+unsigned int
854458
+dns_resolver_getnonbackofftries(dns_resolver_t *resolver);
854458
+
854458
+void
854458
+dns_resolver_setnonbackofftries(dns_resolver_t *resolver, unsigned int tries);
854458
+/*%<
854458
+ * Sets the number of failures of getting a reply from remote servers for
854458
+ * a query before backing off by doubling the retry interval for each
854458
+ * subsequent request sent.  Defaults to 3.
854458
+ *
854458
+ * Requires:
854458
+ * \li	resolver to be valid.
854458
+ * \li  tries > 0.
854458
+ */
854458
+
854458
 unsigned int
854458
 dns_resolver_getoptions(dns_resolver_t *resolver);
854458
 
854458
diff --git a/lib/dns/include/dns/types.h b/lib/dns/include/dns/types.h
74b53c
index 567e8a8..7bf2b60 100644
854458
--- a/lib/dns/include/dns/types.h
854458
+++ b/lib/dns/include/dns/types.h
854458
@@ -385,6 +385,12 @@ typedef enum {
854458
 	dns_updatemethod_date
854458
 } dns_updatemethod_t;
854458
 
854458
+typedef enum {
854458
+	dns_stale_answer_no,
854458
+	dns_stale_answer_yes,
854458
+	dns_stale_answer_conf
854458
+} dns_stale_answer_t;
854458
+
854458
 /*
854458
  * Functions.
854458
  */
854458
diff --git a/lib/dns/include/dns/view.h b/lib/dns/include/dns/view.h
74b53c
index c849dec..647ca2a 100644
854458
--- a/lib/dns/include/dns/view.h
854458
+++ b/lib/dns/include/dns/view.h
854458
@@ -229,6 +229,9 @@ struct dns_view {
854458
 	dns_dtenv_t			*dtenv;		/* Dnstap environment */
854458
 	dns_dtmsgtype_t			dttypes;	/* Dnstap message types
854458
 							   to log */
854458
+	dns_ttl_t			staleanswerttl;
854458
+	dns_stale_answer_t		staleanswersok;		/* rndc setting */
854458
+	bool				staleanswersenable;	/* named.conf setting */
854458
 };
854458
 
854458
 #define DNS_VIEW_MAGIC			ISC_MAGIC('V','i','e','w')
854458
diff --git a/lib/dns/master.c b/lib/dns/master.c
74b53c
index 2a87bca..ac4bb19 100644
854458
--- a/lib/dns/master.c
854458
+++ b/lib/dns/master.c
854458
@@ -1948,12 +1948,18 @@ load_text(dns_loadctx_t *lctx) {
854458
 
854458
 		if ((lctx->options & DNS_MASTER_AGETTL) != 0) {
854458
 			/*
854458
-			 * Adjust the TTL for $DATE.  If the RR has already
854458
-			 * expired, ignore it.
854458
+			 * Adjust the TTL for $DATE. If the RR has
854458
+			 * already expired, set its TTL to 0. This
854458
+			 * should be okay even if the TTL stretching
854458
+			 * feature is not in effect, because it will
854458
+			 * just be quickly expired by the cache, and the
854458
+			 * way this was written before the patch it
854458
+			 * could potentially add 0 TTLs anyway.
854458
 			 */
854458
 			if (lctx->ttl < ttl_offset)
854458
-				continue;
854458
-			lctx->ttl -= ttl_offset;
854458
+				lctx->ttl = 0;
854458
+			else
854458
+				lctx->ttl -= ttl_offset;
854458
 		}
854458
 
854458
 		/*
854458
diff --git a/lib/dns/masterdump.c b/lib/dns/masterdump.c
74b53c
index 13d1a3e..873b694 100644
854458
--- a/lib/dns/masterdump.c
854458
+++ b/lib/dns/masterdump.c
854458
@@ -81,6 +81,9 @@ struct dns_master_style {
854458
  */
854458
 #define DNS_TOTEXT_LINEBREAK_MAXLEN 100
854458
 
854458
+/*% Does the rdataset 'r' contain a stale answer? */
854458
+#define STALE(r) (((r)->attributes & DNS_RDATASETATTR_STALE) != 0)
854458
+
854458
 /*%
854458
  * Context structure for a masterfile dump in progress.
854458
  */
854458
@@ -94,6 +97,7 @@ typedef struct dns_totext_ctx {
854458
 	dns_fixedname_t		origin_fixname;
854458
 	uint32_t 		current_ttl;
854458
 	bool 			current_ttl_valid;
854458
+	dns_ttl_t		serve_stale_ttl;
854458
 } dns_totext_ctx_t;
854458
 
854458
 LIBDNS_EXTERNAL_DATA const dns_master_style_t
74b53c
@@ -382,6 +386,7 @@ totext_ctx_init(const dns_master_style_t *style, dns_totext_ctx_t *ctx) {
854458
 	ctx->neworigin = NULL;
854458
 	ctx->current_ttl = 0;
854458
 	ctx->current_ttl_valid = false;
854458
+	ctx->serve_stale_ttl = 0;
854458
 
854458
 	return (ISC_R_SUCCESS);
854458
 }
74b53c
@@ -1028,6 +1033,11 @@ dump_rdatasets_text(isc_mem_t *mctx, dns_name_t *name,
854458
 		    (ctx->style.flags & DNS_STYLEFLAG_NCACHE) == 0) {
854458
 			/* Omit negative cache entries */
854458
 		} else {
854458
+			if (STALE(rds)) {
854458
+				fprintf(f, "; stale (for %u more seconds)\n",
854458
+					(rds->stale_ttl -
854458
+					 ctx->serve_stale_ttl));
854458
+			}
854458
 			isc_result_t result =
854458
 				dump_rdataset(mctx, name, rds, ctx,
854458
 					       buffer, f);
74b53c
@@ -1496,6 +1506,16 @@ dumpctx_create(isc_mem_t *mctx, dns_db_t *db, dns_dbversion_t *version,
854458
 	dns_db_attach(db, &dctx->db);
854458
 
854458
 	dctx->do_date = dns_db_iscache(dctx->db);
854458
+	if (dctx->do_date) {
854458
+		/*
854458
+		 * Adjust the date backwards by the serve-stale TTL, if any.
854458
+		 * This is so the TTL will be loaded correctly when next
854458
+		 * started.
854458
+		 */
854458
+		(void)dns_db_getservestalettl(dctx->db,
854458
+					      &dctx->tctx.serve_stale_ttl);
854458
+		dctx->now -= dctx->tctx.serve_stale_ttl;
854458
+	}
854458
 
854458
 	if (dctx->format == dns_masterformat_text &&
854458
 	    (dctx->tctx.style.flags & DNS_STYLEFLAG_REL_OWNER) != 0) {
74b53c
@@ -1555,6 +1575,9 @@ writeheader(dns_dumpctx_t *dctx) {
854458
 		 * it in the zone case.
854458
 		 */
854458
 		if (dctx->do_date) {
854458
+			fprintf(dctx->f,
854458
+				"; using a %d second stale ttl\n",
854458
+				dctx->tctx.serve_stale_ttl);
854458
 			result = dns_time32_totext(dctx->now, &buffer);
854458
 			RUNTIME_CHECK(result == ISC_R_SUCCESS);
854458
 			isc_buffer_usedregion(&buffer, &r);
854458
diff --git a/lib/dns/rbtdb.c b/lib/dns/rbtdb.c
74b53c
index 738aa20..5055fcb 100644
854458
--- a/lib/dns/rbtdb.c
854458
+++ b/lib/dns/rbtdb.c
854458
@@ -488,6 +488,7 @@ typedef ISC_LIST(rdatasetheader_t)      rdatasetheaderlist_t;
854458
 typedef ISC_LIST(dns_rbtnode_t)         rbtnodelist_t;
854458
 
854458
 #define RDATASET_ATTR_NONEXISTENT       0x0001
854458
+/*%< May be potentially served as stale data. */
854458
 #define RDATASET_ATTR_STALE             0x0002
854458
 #define RDATASET_ATTR_IGNORE            0x0004
854458
 #define RDATASET_ATTR_RETAIN            0x0008
854458
@@ -500,6 +501,8 @@ typedef ISC_LIST(dns_rbtnode_t)         rbtnodelist_t;
854458
 #define RDATASET_ATTR_CASESET           0x0400
854458
 #define RDATASET_ATTR_ZEROTTL           0x0800
854458
 #define RDATASET_ATTR_CASEFULLYLOWER    0x1000
854458
+/*%< Ancient - awaiting cleanup. */
854458
+#define RDATASET_ATTR_ANCIENT           0x2000
854458
 
854458
 typedef struct acache_cbarg {
854458
 	dns_rdatasetadditional_t        type;
854458
@@ -550,6 +553,8 @@ struct acachectl {
854458
 	(((header)->attributes & RDATASET_ATTR_ZEROTTL) != 0)
854458
 #define CASEFULLYLOWER(header) \
854458
 	(((header)->attributes & RDATASET_ATTR_CASEFULLYLOWER) != 0)
854458
+#define ANCIENT(header) \
854458
+	(((header)->attributes & RDATASET_ATTR_ANCIENT) != 0)
854458
 
854458
 
854458
 #define ACTIVE(header, now) \
854458
@@ -609,6 +614,12 @@ typedef enum {
854458
 	expire_flush
854458
 } expire_t;
854458
 
854458
+typedef enum {
854458
+	rdataset_ttl_fresh,
854458
+	rdataset_ttl_stale,
854458
+	rdataset_ttl_ancient
854458
+} rdataset_ttl_t;
854458
+
854458
 typedef struct rbtdb_version {
854458
 	/* Not locked */
854458
 	rbtdb_serial_t                  serial;
854458
@@ -676,6 +687,12 @@ struct dns_rbtdb {
854458
 	dns_dbnode_t                    *soanode;
854458
 	dns_dbnode_t                    *nsnode;
854458
 
854458
+	/*
854458
+	 * Maximum length of time to keep using a stale answer past its
854458
+	 * normal TTL expiry.
854458
+	*/
854458
+	dns_ttl_t			serve_stale_ttl;
854458
+
854458
 	/*
854458
 	 * This is a linked list used to implement the LRU cache.  There will
854458
 	 * be node_lock_count linked lists here.  Nodes in bucket 1 will be
854458
@@ -719,6 +736,8 @@ struct dns_rbtdb {
854458
 #define RBTDB_ATTR_LOADED               0x01
854458
 #define RBTDB_ATTR_LOADING              0x02
854458
 
854458
+#define KEEPSTALE(rbtdb) ((rbtdb)->serve_stale_ttl > 0)
854458
+
854458
 /*%
854458
  * Search Context
854458
  */
854458
@@ -1784,15 +1803,15 @@ rollback_node(dns_rbtnode_t *node, rbtdb_serial_t serial) {
854458
 }
854458
 
854458
 static inline void
854458
-mark_stale_header(dns_rbtdb_t *rbtdb, rdatasetheader_t *header) {
854458
+mark_header_ancient(dns_rbtdb_t *rbtdb, rdatasetheader_t *header) {
854458
 
854458
 	/*
854458
-	 * If we are already stale there is nothing to do.
854458
+	 * If we are already ancient there is nothing to do.
854458
 	 */
854458
-	if ((header->attributes & RDATASET_ATTR_STALE) != 0)
854458
+	if (ANCIENT(header))
854458
 		return;
854458
 
854458
-	header->attributes |= RDATASET_ATTR_STALE;
854458
+	header->attributes |= RDATASET_ATTR_ANCIENT;
854458
 	header->node->dirty = 1;
854458
 
854458
 	/*
854458
@@ -1833,8 +1852,8 @@ clean_cache_node(dns_rbtdb_t *rbtdb, dns_rbtnode_t *node) {
854458
 		/*
854458
 		 * If current is nonexistent or stale, we can clean it up.
854458
 		 */
854458
-		if ((current->attributes &
854458
-		     (RDATASET_ATTR_NONEXISTENT|RDATASET_ATTR_STALE)) != 0) {
854458
+		if (NONEXISTENT(current) || ANCIENT(current) ||
854458
+		    (STALE(current) && ! KEEPSTALE(rbtdb))) {
854458
 			if (top_prev != NULL)
854458
 				top_prev->next = current->next;
854458
 			else
854458
@@ -2076,6 +2095,80 @@ delete_node(dns_rbtdb_t *rbtdb, dns_rbtnode_t *node) {
854458
 	}
854458
 }
854458
 
854458
+#if 0
854458
+static void
854458
+clean_now_or_later(dns_rbtnode_t *node, dns_rbtdb_t *rbtdb,
854458
+		   rdatasetheader_t *header, rdatasetheader_t **header_prevp)
854458
+{
854458
+	if (dns_rbtnode_refcurrent(node) == 0) {
854458
+		isc_mem_t *mctx;
854458
+
854458
+		/*
854458
+		 * header->down can be non-NULL if the refcount has just
854458
+		 * decremented to 0 but decrement_reference() has not performed
854458
+		 * clean_cache_node(), in which case we need to purge the stale
854458
+		 * headers first.
854458
+		 */
854458
+		mctx = rbtdb->common.mctx;
854458
+		clean_stale_headers(rbtdb, mctx, header);
854458
+		if (*header_prevp != NULL)
854458
+			(*header_prevp)->next = header->next;
854458
+		else
854458
+			node->data = header->next;
854458
+		free_rdataset(rbtdb, mctx, header);
854458
+	} else {
854458
+		header->attributes |= RDATASET_ATTR_STALE |
854458
+		                      RDATASET_ATTR_ANCIENT;
854458
+		node->dirty = 1;
854458
+		*header_prevp = header;
854458
+	}
854458
+}
854458
+
854458
+static rdataset_ttl_t
854458
+check_ttl(dns_rbtnode_t *node, rbtdb_search_t *search,
854458
+	  rdatasetheader_t *header, rdatasetheader_t **header_prevp,
854458
+	  nodelock_t *lock, isc_rwlocktype_t *locktype)
854458
+{
854458
+	dns_rbtdb_t *rbtdb = search->rbtdb;
854458
+
854458
+	if (header->rdh_ttl > search->now)
854458
+		return rdataset_ttl_fresh;
854458
+
854458
+	/*
854458
+	 * This rdataset is stale, but perhaps still usable.
854458
+	 */
854458
+	if (KEEPSTALE(rbtdb) &&
854458
+	    header->rdh_ttl + rbtdb->serve_stale_ttl > search->now) {
854458
+		header->attributes |= RDATASET_ATTR_STALE;
854458
+		/* Doesn't set dirty because it doesn't need removal. */
854458
+		return rdataset_ttl_stale;
854458
+	}
854458
+
854458
+	/*
854458
+	 * This rdataset is so stale it is no longer usable, even with
854458
+	 * KEEPSTALE.  If no one else is using the node, we can clean it up
854458
+	 * right now, otherwise we mark it as ancient, and the node as dirty,
854458
+	 * so it will get cleaned up later.
854458
+	 */
854458
+	if ((header->rdh_ttl <= search->now - RBTDB_VIRTUAL) &&
854458
+	    (*locktype == isc_rwlocktype_write ||
854458
+	     NODE_TRYUPGRADE(lock) == ISC_R_SUCCESS)) {
854458
+		/*
854458
+		 * We update the node's status only when we can get write
854458
+		 * access; otherwise, we leave others to this work.  Periodical
854458
+		 * cleaning will eventually take the job as the last resort.
854458
+		 * We won't downgrade the lock, since other rdatasets are
854458
+		 * probably stale, too.
854458
+		 */
854458
+		*locktype = isc_rwlocktype_write;
854458
+		clean_now_or_later(node, rbtdb, header, header_prevp);
854458
+	} else
854458
+		*header_prevp = header;
854458
+
854458
+	return rdataset_ttl_ancient;
854458
+}
854458
+#endif
854458
+
854458
 /*
854458
  * Caller must be holding the node lock.
854458
  */
854458
@@ -3308,6 +3401,12 @@ bind_rdataset(dns_rbtdb_t *rbtdb, dns_rbtnode_t *node,
854458
 		rdataset->attributes |= DNS_RDATASETATTR_OPTOUT;
854458
 	if (PREFETCH(header))
854458
 		rdataset->attributes |= DNS_RDATASETATTR_PREFETCH;
854458
+	if (STALE(header)) {
854458
+		rdataset->attributes |= DNS_RDATASETATTR_STALE;
854458
+		rdataset->stale_ttl =
854458
+			(rbtdb->serve_stale_ttl + header->rdh_ttl) - now;
854458
+		rdataset->ttl = 0;
854458
+	}
854458
 	rdataset->private1 = rbtdb;
854458
 	rdataset->private2 = node;
854458
 	raw = (unsigned char *)header + sizeof(*header);
854458
@@ -4648,6 +4747,19 @@ check_stale_header(dns_rbtnode_t *node, rdatasetheader_t *header,
854458
 #endif
854458
 
854458
 	if (!ACTIVE(header, search->now)) {
854458
+		dns_ttl_t stale = header->rdh_ttl +
854458
+				  search->rbtdb->serve_stale_ttl;
854458
+		/*
854458
+		 * If this data is in the stale window keep it and if
854458
+		 * DNS_DBFIND_STALEOK is not set we tell the caller to
854458
+		 * skip this record.
854458
+		 */
854458
+		if (KEEPSTALE(search->rbtdb) && stale > search->now) {
854458
+			header->attributes |= RDATASET_ATTR_STALE;
854458
+			*header_prev = header;
854458
+			return ((search->options & DNS_DBFIND_STALEOK) == 0);
854458
+		}
854458
+
854458
 		/*
854458
 		 * This rdataset is stale.  If no one else is using the
854458
 		 * node, we can clean it up right now, otherwise we mark
854458
@@ -4687,7 +4799,7 @@ check_stale_header(dns_rbtnode_t *node, rdatasetheader_t *header,
854458
 					node->data = header->next;
854458
 				free_rdataset(search->rbtdb, mctx, header);
854458
 			} else {
854458
-				mark_stale_header(search->rbtdb, header);
854458
+				mark_header_ancient(search->rbtdb, header);
854458
 				*header_prev = header;
854458
 			}
854458
 		} else
854458
@@ -5125,7 +5237,7 @@ cache_find(dns_db_t *db, dns_name_t *name, dns_dbversion_t *version,
854458
 				       &locktype, lock, &search,
854458
 				       &header_prev)) {
854458
 			/* Do nothing. */
854458
-		} else if (EXISTS(header) && (!STALE(header))) {
854458
+		} else if (EXISTS(header) && !ANCIENT(header)) {
854458
 			/*
854458
 			 * We now know that there is at least one active
854458
 			 * non-stale rdataset at this node.
854458
@@ -5603,7 +5715,7 @@ expirenode(dns_db_t *db, dns_dbnode_t *node, isc_stdtime_t now) {
854458
 			 * refcurrent(rbtnode) must be non-zero.  This is so
854458
 			 * because 'node' is an argument to the function.
854458
 			 */
854458
-			mark_stale_header(rbtdb, header);
854458
+			mark_header_ancient(rbtdb, header);
854458
 			if (log)
854458
 				isc_log_write(dns_lctx, category, module,
854458
 					      level, "overmem cache: stale %s",
854458
@@ -5611,7 +5723,7 @@ expirenode(dns_db_t *db, dns_dbnode_t *node, isc_stdtime_t now) {
854458
 		} else if (force_expire) {
854458
 			if (! RETAIN(header)) {
854458
 				set_ttl(rbtdb, header, 0);
854458
-				mark_stale_header(rbtdb, header);
854458
+				mark_header_ancient(rbtdb, header);
854458
 			} else if (log) {
854458
 				isc_log_write(dns_lctx, category, module,
854458
 					      level, "overmem cache: "
854458
@@ -5868,9 +5980,9 @@ cache_findrdataset(dns_db_t *db, dns_dbnode_t *node, dns_dbversion_t *version,
854458
 				 * non-zero.  This is so because 'node' is an
854458
 				 * argument to the function.
854458
 				 */
854458
-				mark_stale_header(rbtdb, header);
854458
+				mark_header_ancient(rbtdb, header);
854458
 			}
854458
-		} else if (EXISTS(header) && (!STALE(header))) {
854458
+		} else if (EXISTS(header) && !ANCIENT(header)) {
854458
 			if (header->type == matchtype)
854458
 				found = header;
854458
 			else if (header->type == RBTDB_RDATATYPE_NCACHEANY ||
854458
@@ -6160,7 +6272,7 @@ add32(dns_rbtdb_t *rbtdb, dns_rbtnode_t *rbtnode, rbtdb_version_t *rbtversion,
854458
 				     topheader = topheader->next)
854458
 				{
854458
 					set_ttl(rbtdb, topheader, 0);
854458
-					mark_stale_header(rbtdb, topheader);
854458
+					mark_header_ancient(rbtdb, topheader);
854458
 				}
854458
 				goto find_header;
854458
 			}
854458
@@ -6218,7 +6330,7 @@ add32(dns_rbtdb_t *rbtdb, dns_rbtnode_t *rbtnode, rbtdb_version_t *rbtversion,
854458
 				 * ncache entry.
854458
 				 */
854458
 				set_ttl(rbtdb, topheader, 0);
854458
-				mark_stale_header(rbtdb, topheader);
854458
+				mark_header_ancient(rbtdb, topheader);
854458
 				topheader = NULL;
854458
 				goto find_header;
854458
 			}
854458
@@ -6256,8 +6368,11 @@ add32(dns_rbtdb_t *rbtdb, dns_rbtnode_t *rbtnode, rbtdb_version_t *rbtversion,
854458
 		}
854458
 
854458
 		/*
854458
-		 * Trying to add an rdataset with lower trust to a cache DB
854458
-		 * has no effect, provided that the cache data isn't stale.
854458
+		 * Trying to add an rdataset with lower trust to a cache
854458
+		 * DB has no effect, provided that the cache data isn't
854458
+		 * stale. If the cache data is stale, new lower trust
854458
+		 * data will supersede it below. Unclear what the best
854458
+		 * policy is here.
854458
 		 */
854458
 		if (rbtversion == NULL && trust < header->trust &&
854458
 		    (ACTIVE(header, now) || header_nx)) {
854458
@@ -6286,6 +6401,10 @@ add32(dns_rbtdb_t *rbtdb, dns_rbtnode_t *rbtnode, rbtdb_version_t *rbtversion,
854458
 
854458
 			if ((options & DNS_DBADD_EXACT) != 0)
854458
 				flags |= DNS_RDATASLAB_EXACT;
854458
+			/*
854458
+			 * TTL use here is irrelevant to the cache;
854458
+			 * merge is only done with zonedbs.
854458
+			 */
854458
 			if ((options & DNS_DBADD_EXACTTTL) != 0 &&
854458
 			     newheader->rdh_ttl != header->rdh_ttl)
854458
 					result = DNS_R_NOTEXACT;
854458
@@ -6329,11 +6448,12 @@ add32(dns_rbtdb_t *rbtdb, dns_rbtnode_t *rbtnode, rbtdb_version_t *rbtversion,
854458
 			}
854458
 		}
854458
 		/*
854458
-		 * Don't replace existing NS, A and AAAA RRsets
854458
-		 * in the cache if they are already exist.  This
854458
-		 * prevents named being locked to old servers.
854458
-		 * Don't lower trust of existing record if the
854458
-		 * update is forced.
854458
+		 * Don't replace existing NS, A and AAAA RRsets in the
854458
+		 * cache if they are already exist. This prevents named
854458
+		 * being locked to old servers. Don't lower trust of
854458
+		 * existing record if the update is forced. Nothing
854458
+		 * special to be done w.r.t stale data; it gets replaced
854458
+		 * normally further down.
854458
 		 */
854458
 		if (IS_CACHE(rbtdb) && ACTIVE(header, now) &&
854458
 		    header->type == dns_rdatatype_ns &&
854458
@@ -6508,10 +6628,10 @@ add32(dns_rbtdb_t *rbtdb, dns_rbtnode_t *rbtnode, rbtdb_version_t *rbtversion,
854458
 				changed->dirty = true;
854458
 			if (rbtversion == NULL) {
854458
 				set_ttl(rbtdb, header, 0);
854458
-				mark_stale_header(rbtdb, header);
854458
+				mark_header_ancient(rbtdb, header);
854458
 				if (sigheader != NULL) {
854458
 					set_ttl(rbtdb, sigheader, 0);
854458
-					mark_stale_header(rbtdb, sigheader);
854458
+					mark_header_ancient(rbtdb, sigheader);
854458
 				}
854458
 			}
854458
 			if (rbtversion != NULL && !header_nx) {
74b53c
@@ -8310,6 +8430,30 @@ nodefullname(dns_db_t *db, dns_dbnode_t *node, dns_name_t *name) {
854458
 	return (result);
854458
 }
854458
 
854458
+static isc_result_t
854458
+setservestalettl(dns_db_t *db, dns_ttl_t ttl) {
854458
+	dns_rbtdb_t *rbtdb = (dns_rbtdb_t *)db;
854458
+
854458
+	REQUIRE(VALID_RBTDB(rbtdb));
854458
+	REQUIRE(IS_CACHE(rbtdb));
854458
+
854458
+	/* currently no bounds checking.  0 means disable. */
854458
+	rbtdb->serve_stale_ttl = ttl;
854458
+	return ISC_R_SUCCESS;
854458
+}
854458
+
854458
+static isc_result_t
854458
+getservestalettl(dns_db_t *db, dns_ttl_t *ttl) {
854458
+	dns_rbtdb_t *rbtdb = (dns_rbtdb_t *)db;
854458
+
854458
+	REQUIRE(VALID_RBTDB(rbtdb));
854458
+	REQUIRE(IS_CACHE(rbtdb));
854458
+
854458
+	*ttl = rbtdb->serve_stale_ttl;
854458
+	return ISC_R_SUCCESS;
854458
+}
854458
+
854458
+
854458
 static dns_dbmethods_t zone_methods = {
854458
 	attach,
854458
 	detach,
74b53c
@@ -8355,7 +8499,9 @@ static dns_dbmethods_t zone_methods = {
854458
 	NULL,
854458
 	hashsize,
854458
 	nodefullname,
854458
-	getsize
854458
+	getsize,
854458
+	NULL,
854458
+	NULL
854458
 };
854458
 
854458
 static dns_dbmethods_t cache_methods = {
74b53c
@@ -8403,7 +8549,9 @@ static dns_dbmethods_t cache_methods = {
854458
 	setcachestats,
854458
 	hashsize,
854458
 	nodefullname,
854458
-	NULL
854458
+	NULL,
854458
+	setservestalettl,
854458
+	getservestalettl
854458
 };
854458
 
854458
 isc_result_t
74b53c
@@ -8674,7 +8822,7 @@ dns_rbtdb_create
854458
 	rbtdb->rpzs = NULL;
854458
 	rbtdb->load_rpzs = NULL;
854458
 	rbtdb->rpz_num = DNS_RPZ_INVALID_NUM;
854458
-
854458
+	rbtdb->serve_stale_ttl = 0;
854458
 	/*
854458
 	 * Version Initialization.
854458
 	 */
74b53c
@@ -9092,7 +9240,8 @@ rdatasetiter_first(dns_rdatasetiter_t *iterator) {
854458
 				 * rdatasets to work.
854458
 				 */
854458
 				if (NONEXISTENT(header) ||
854458
-				    (now != 0 && now > header->rdh_ttl))
854458
+				    (now != 0 && now > header->rdh_ttl
854458
+						     + rbtdb->serve_stale_ttl))
854458
 					header = NULL;
854458
 				break;
854458
 			} else
74b53c
@@ -10280,7 +10429,7 @@ static inline bool
854458
 need_headerupdate(rdatasetheader_t *header, isc_stdtime_t now) {
854458
 	if ((header->attributes &
854458
 	     (RDATASET_ATTR_NONEXISTENT |
854458
-	      RDATASET_ATTR_STALE |
854458
+	      RDATASET_ATTR_ANCIENT |
854458
 	      RDATASET_ATTR_ZEROTTL)) != 0)
854458
 		return (false);
854458
 
74b53c
@@ -10386,7 +10535,7 @@ expire_header(dns_rbtdb_t *rbtdb, rdatasetheader_t *header,
854458
 	      bool tree_locked, expire_t reason)
854458
 {
854458
 	set_ttl(rbtdb, header, 0);
854458
-	mark_stale_header(rbtdb, header);
854458
+	mark_header_ancient(rbtdb, header);
854458
 
854458
 	/*
854458
 	 * Caller must hold the node (write) lock.
854458
diff --git a/lib/dns/resolver.c b/lib/dns/resolver.c
74b53c
index 04a58c0..164fc01 100644
854458
--- a/lib/dns/resolver.c
854458
+++ b/lib/dns/resolver.c
854458
@@ -141,16 +141,17 @@
854458
 #endif /* WANT_QUERYTRACE */
854458
 
854458
 #define US_PER_SEC 1000000U
854458
+#define US_PER_MSEC 1000U
854458
 /*
854458
  * The maximum time we will wait for a single query.
854458
  */
854458
-#define MAX_SINGLE_QUERY_TIMEOUT 9U
854458
-#define MAX_SINGLE_QUERY_TIMEOUT_US (MAX_SINGLE_QUERY_TIMEOUT*US_PER_SEC)
854458
+#define MAX_SINGLE_QUERY_TIMEOUT 9000U
854458
+#define MAX_SINGLE_QUERY_TIMEOUT_US (MAX_SINGLE_QUERY_TIMEOUT*US_PER_MSEC)
854458
 
854458
 /*
854458
  * We need to allow a individual query time to complete / timeout.
854458
  */
854458
-#define MINIMUM_QUERY_TIMEOUT (MAX_SINGLE_QUERY_TIMEOUT + 1U)
854458
+#define MINIMUM_QUERY_TIMEOUT (MAX_SINGLE_QUERY_TIMEOUT + 1000U)
854458
 
854458
 /* The default time in seconds for the whole query to live. */
854458
 #ifndef DEFAULT_QUERY_TIMEOUT
854458
@@ -159,7 +160,7 @@
854458
 
854458
 /* The maximum time in seconds for the whole query to live. */
854458
 #ifndef MAXIMUM_QUERY_TIMEOUT
854458
-#define MAXIMUM_QUERY_TIMEOUT 30
854458
+#define MAXIMUM_QUERY_TIMEOUT 30000
854458
 #endif
854458
 
854458
 /* The default maximum number of recursions to follow before giving up. */
854458
@@ -496,6 +497,10 @@ struct dns_resolver {
854458
 	unsigned int			maxqueries;
854458
 	isc_result_t			quotaresp[2];
854458
 
854458
+	/* Additions for serve-stale feature. */
854458
+	unsigned int			retryinterval; /* in milliseconds */
854458
+	unsigned int			nonbackofftries;
854458
+
854458
 	/* Locked by lock. */
854458
 	unsigned int			references;
854458
 	bool			exiting;
74b53c
@@ -1617,14 +1622,12 @@ fctx_setretryinterval(fetchctx_t *fctx, unsigned int rtt) {
854458
 	unsigned int seconds;
854458
 	unsigned int us;
854458
 
854458
+	us = fctx->res->retryinterval * 1000;
854458
 	/*
854458
-	 * We retry every .8 seconds the first two times through the address
854458
-	 * list, and then we do exponential back-off.
854458
+	 * Exponential backoff after the first few tries.
854458
 	 */
854458
-	if (fctx->restarts < 3)
854458
-		us = 800000;
854458
-	else
854458
-		us = (800000 << (fctx->restarts - 2));
854458
+	if (fctx->restarts >= fctx->res->nonbackofftries)
854458
+		us <<= (fctx->restarts - fctx->res->nonbackofftries - 1);
854458
 
854458
 	/*
854458
 	 * Add a fudge factor to the expected rtt based on the current
74b53c
@@ -4481,7 +4484,8 @@ fctx_create(dns_resolver_t *res, dns_name_t *name, dns_rdatatype_t type,
854458
 	/*
854458
 	 * Compute an expiration time for the entire fetch.
854458
 	 */
854458
-	isc_interval_set(&interval, res->query_timeout, 0);
854458
+	isc_interval_set(&interval, res->query_timeout / 1000,
854458
+			 res->query_timeout % 1000 * 1000000);
854458
 	iresult = isc_time_nowplusinterval(&fctx->expires, &interval);
854458
 	if (iresult != ISC_R_SUCCESS) {
854458
 		UNEXPECTED_ERROR(__FILE__, __LINE__,
74b53c
@@ -8965,6 +8969,8 @@ dns_resolver_create(dns_view_t *view,
854458
 	res->spillattimer = NULL;
854458
 	res->zspill = 0;
854458
 	res->zero_no_soa_ttl = false;
854458
+	res->retryinterval = 30000;
854458
+	res->nonbackofftries = 3;
854458
 	res->query_timeout = DEFAULT_QUERY_TIMEOUT;
854458
 	res->maxdepth = DEFAULT_RECURSION_DEPTH;
854458
 	res->maxqueries = DEFAULT_MAX_QUERIES;
74b53c
@@ -10291,17 +10297,20 @@ dns_resolver_gettimeout(dns_resolver_t *resolver) {
854458
 }
854458
 
854458
 void
854458
-dns_resolver_settimeout(dns_resolver_t *resolver, unsigned int seconds) {
854458
+dns_resolver_settimeout(dns_resolver_t *resolver, unsigned int timeout) {
854458
 	REQUIRE(VALID_RESOLVER(resolver));
854458
 
854458
-	if (seconds == 0)
854458
-		seconds = DEFAULT_QUERY_TIMEOUT;
854458
-	if (seconds > MAXIMUM_QUERY_TIMEOUT)
854458
-		seconds = MAXIMUM_QUERY_TIMEOUT;
854458
-	if (seconds < MINIMUM_QUERY_TIMEOUT)
854458
-		seconds =  MINIMUM_QUERY_TIMEOUT;
854458
+	if (timeout <= 300)
854458
+		timeout *= 1000;
854458
+
854458
+	if (timeout == 0)
854458
+		timeout = DEFAULT_QUERY_TIMEOUT;
854458
+	if (timeout > MAXIMUM_QUERY_TIMEOUT)
854458
+		timeout = MAXIMUM_QUERY_TIMEOUT;
854458
+	if (timeout < MINIMUM_QUERY_TIMEOUT)
854458
+		timeout =  MINIMUM_QUERY_TIMEOUT;
854458
 
854458
-	resolver->query_timeout = seconds;
854458
+	resolver->query_timeout = timeout;
854458
 }
854458
 
854458
 void
74b53c
@@ -10398,3 +10407,34 @@ dns_resolver_getquotaresponse(dns_resolver_t *resolver, dns_quotatype_t which)
854458
 
854458
 	return (resolver->quotaresp[which]);
854458
 }
854458
+
854458
+unsigned int
854458
+dns_resolver_getretryinterval(dns_resolver_t *resolver) {
854458
+	REQUIRE(VALID_RESOLVER(resolver));
854458
+
854458
+	return (resolver->retryinterval);
854458
+}
854458
+
854458
+void
854458
+dns_resolver_setretryinterval(dns_resolver_t *resolver, unsigned int interval)
854458
+{
854458
+	REQUIRE(VALID_RESOLVER(resolver));
854458
+	REQUIRE(interval > 0);
854458
+
854458
+	resolver->retryinterval = ISC_MIN(interval, 2000);
854458
+}
854458
+
854458
+unsigned int
854458
+dns_resolver_getnonbackofftries(dns_resolver_t *resolver) {
854458
+	REQUIRE(VALID_RESOLVER(resolver));
854458
+
854458
+	return (resolver->nonbackofftries);
854458
+}
854458
+
854458
+void
854458
+dns_resolver_setnonbackofftries(dns_resolver_t *resolver, unsigned int tries) {
854458
+	REQUIRE(VALID_RESOLVER(resolver));
854458
+	REQUIRE(tries > 0);
854458
+
854458
+	resolver->nonbackofftries = tries;
854458
+}
854458
diff --git a/lib/dns/sdb.c b/lib/dns/sdb.c
74b53c
index d4c8c67..ee9be79 100644
854458
--- a/lib/dns/sdb.c
854458
+++ b/lib/dns/sdb.c
854458
@@ -1368,7 +1368,9 @@ static dns_dbmethods_t sdb_methods = {
854458
 	NULL,			/* setcachestats */
854458
 	NULL,			/* hashsize */
854458
 	NULL,			/* nodefullname */
854458
-	NULL			/* getsize */
854458
+	NULL,			/* getsize */
854458
+	NULL,			/* setservestalettl */
854458
+	NULL			/* getservestalettl */
854458
 };
854458
 
854458
 static isc_result_t
854458
diff --git a/lib/dns/sdlz.c b/lib/dns/sdlz.c
74b53c
index 0b9620c..331992e 100644
854458
--- a/lib/dns/sdlz.c
854458
+++ b/lib/dns/sdlz.c
854458
@@ -1336,7 +1336,9 @@ static dns_dbmethods_t sdlzdb_methods = {
854458
 	NULL,			/* setcachestats */
854458
 	NULL,			/* hashsize */
854458
 	NULL,			/* nodefullname */
854458
-	NULL			/* getsize */
854458
+	NULL,			/* getsize */
854458
+	NULL,			/* setservestalettl */
854458
+	NULL			/* getservestalettl */
854458
 };
854458
 
854458
 /*
854458
diff --git a/lib/dns/tests/db_test.c b/lib/dns/tests/db_test.c
74b53c
index 35cf21d..bf39545 100644
854458
--- a/lib/dns/tests/db_test.c
854458
+++ b/lib/dns/tests/db_test.c
854458
@@ -28,8 +28,9 @@
854458
 
854458
 #include <dns/db.h>
854458
 #include <dns/dbiterator.h>
854458
-#include <dns/name.h>
854458
 #include <dns/journal.h>
854458
+#include <dns/name.h>
854458
+#include <dns/rdatalist.h>
854458
 
854458
 #include "dnstest.h"
854458
 
854458
@@ -76,7 +77,7 @@ getoriginnode_test(void **state) {
854458
 	assert_int_equal(result, ISC_R_SUCCESS);
854458
 
854458
 	result = dns_db_create(mymctx, "rbt", dns_rootname, dns_dbtype_zone,
854458
-			    dns_rdataclass_in, 0, NULL, &db);
854458
+			       dns_rdataclass_in, 0, NULL, &db);
854458
 	assert_int_equal(result, ISC_R_SUCCESS);
854458
 
854458
 	result = dns_db_getoriginnode(db, &node);
854458
@@ -91,6 +92,197 @@ getoriginnode_test(void **state) {
854458
 	isc_mem_detach(&mymctx);
854458
 }
854458
 
854458
+/* test getservestalettl and setservestalettl */
854458
+static void
854458
+getsetservestalettl_test(void **state) {
854458
+	dns_db_t *db = NULL;
854458
+	isc_mem_t *mymctx = NULL;
854458
+	isc_result_t result;
854458
+	dns_ttl_t ttl;
854458
+
854458
+	UNUSED(state);
854458
+
854458
+	result = isc_mem_create(0, 0, &mymctx);
854458
+	assert_int_equal(result, ISC_R_SUCCESS);
854458
+
854458
+	result = dns_db_create(mymctx, "rbt", dns_rootname, dns_dbtype_cache,
854458
+			       dns_rdataclass_in, 0, NULL, &db);
854458
+	assert_int_equal(result, ISC_R_SUCCESS);
854458
+
854458
+	ttl = 5000;
854458
+	result = dns_db_getservestalettl(db, &ttl);
854458
+	assert_int_equal(result, ISC_R_SUCCESS);
854458
+	assert_int_equal(ttl, 0);
854458
+
854458
+	ttl = 6 * 3600;
854458
+	result = dns_db_setservestalettl(db, ttl);
854458
+	assert_int_equal(result, ISC_R_SUCCESS);
854458
+
854458
+	ttl = 5000;
854458
+	result = dns_db_getservestalettl(db, &ttl);
854458
+	assert_int_equal(result, ISC_R_SUCCESS);
854458
+	assert_int_equal(ttl, 6 * 3600);
854458
+
854458
+	dns_db_detach(&db);
854458
+	isc_mem_detach(&mymctx);
854458
+}
854458
+
854458
+/* check DNS_DBFIND_STALEOK works */
854458
+static void
854458
+dns_dbfind_staleok_test(void **state) {
854458
+	dns_db_t *db = NULL;
854458
+	dns_dbnode_t *node = NULL;
854458
+	dns_fixedname_t example_fixed;
854458
+	dns_fixedname_t found_fixed;
854458
+	dns_name_t *example;
854458
+	dns_name_t *found;
854458
+	dns_rdatalist_t rdatalist;
854458
+	dns_rdataset_t rdataset;
854458
+	int count;
854458
+	int pass;
854458
+	isc_mem_t *mymctx = NULL;
854458
+	isc_result_t result;
854458
+	unsigned char data[] = { 0x0a, 0x00, 0x00, 0x01 };
854458
+
854458
+	UNUSED(state);
854458
+
854458
+	result = isc_mem_create(0, 0, &mymctx);
854458
+	assert_int_equal(result, ISC_R_SUCCESS);
854458
+
854458
+	result = dns_db_create(mymctx, "rbt", dns_rootname, dns_dbtype_cache,
854458
+			       dns_rdataclass_in, 0, NULL, &db);
854458
+	assert_int_equal(result, ISC_R_SUCCESS);
854458
+
854458
+	example = dns_fixedname_initname(&example_fixed);
854458
+	found = dns_fixedname_initname(&found_fixed);
854458
+
854458
+	result = dns_name_fromstring(example, "example", 0, NULL);
854458
+	assert_int_equal(result, ISC_R_SUCCESS);
854458
+
854458
+	/*
854458
+	 * Pass 0: default; no stale processing permitted.
854458
+	 * Pass 1: stale processing for 1 second.
854458
+	 * Pass 2: stale turned off after being on.
854458
+	 */
854458
+	for (pass = 0; pass < 3; pass++) {
854458
+		dns_rdata_t rdata = DNS_RDATA_INIT;
854458
+
854458
+		/* 10.0.0.1 */
854458
+		rdata.data = data;
854458
+		rdata.length = 4;
854458
+		rdata.rdclass = dns_rdataclass_in;
854458
+		rdata.type = dns_rdatatype_a;
854458
+
854458
+		dns_rdatalist_init(&rdatalist);
854458
+		rdatalist.ttl = 2;
854458
+		rdatalist.type = dns_rdatatype_a;
854458
+		rdatalist.rdclass = dns_rdataclass_in;
854458
+		ISC_LIST_APPEND(rdatalist.rdata, &rdata, link);
854458
+
854458
+		switch (pass) {
854458
+		case 0:
854458
+			/* default: stale processing off */
854458
+			break;
854458
+		case 1:
854458
+			/* turn on stale processing */
854458
+			result = dns_db_setservestalettl(db, 1);
854458
+			assert_int_equal(result, ISC_R_SUCCESS);
854458
+			break;
854458
+		case 2:
854458
+			/* turn off stale processing */
854458
+			result = dns_db_setservestalettl(db, 0);
854458
+			assert_int_equal(result, ISC_R_SUCCESS);
854458
+			break;
854458
+		}
854458
+
854458
+		dns_rdataset_init(&rdataset);
854458
+		result = dns_rdatalist_tordataset(&rdatalist, &rdataset);
854458
+		assert_int_equal(result, ISC_R_SUCCESS);
854458
+
854458
+		result = dns_db_findnode(db, example, true, &node);
854458
+		assert_int_equal(result, ISC_R_SUCCESS);
854458
+
854458
+		result = dns_db_addrdataset(db, node, NULL, 0, &rdataset, 0,
854458
+					    NULL);
854458
+		assert_int_equal(result, ISC_R_SUCCESS);
854458
+
854458
+		dns_db_detachnode(db, &node);
854458
+		dns_rdataset_disassociate(&rdataset);
854458
+
854458
+		result = dns_db_find(db, example, NULL, dns_rdatatype_a,
854458
+				     0, 0, &node, found, &rdataset, NULL);
854458
+		assert_int_equal(result, ISC_R_SUCCESS);
854458
+
854458
+		/*
854458
+		 * May loop for up to 2 seconds performing non stale lookups.
854458
+		 */
854458
+		count = 0;
854458
+		do {
854458
+			count++;
854458
+			assert_in_range(count, 0, 20); /* loop sanity */
854458
+			assert_int_equal(rdataset.attributes &
854458
+				     DNS_RDATASETATTR_STALE, 0);
854458
+			assert_true(rdataset.ttl > 0);
854458
+			dns_db_detachnode(db, &node);
854458
+			dns_rdataset_disassociate(&rdataset);
854458
+
854458
+			usleep(100000);	/* 100 ms */
854458
+
854458
+			result = dns_db_find(db, example, NULL,
854458
+					     dns_rdatatype_a, 0, 0,
854458
+					     &node, found, &rdataset, NULL);
854458
+		} while (result == ISC_R_SUCCESS);
854458
+
854458
+		assert_int_equal(result, ISC_R_NOTFOUND);
854458
+
854458
+		/*
854458
+		 * Check whether we can get stale data.
854458
+		 */
854458
+		result = dns_db_find(db, example, NULL, dns_rdatatype_a,
854458
+				     DNS_DBFIND_STALEOK, 0,
854458
+				     &node, found, &rdataset, NULL);
854458
+		switch (pass) {
854458
+		case 0:
854458
+			assert_int_equal(result, ISC_R_NOTFOUND);
854458
+			break;
854458
+		case 1:
854458
+			/*
854458
+			 * Should loop for 1 second with stale lookups then
854458
+			 * stop.
854458
+			 */
854458
+			count = 0;
854458
+			do {
854458
+				count++;
854458
+				assert_in_range(count, 0, 49); /* loop sanity */
854458
+				assert_int_equal(result, ISC_R_SUCCESS);
854458
+				assert_int_equal(rdataset.ttl, 0);
854458
+				assert_int_equal(rdataset.attributes &
854458
+					     DNS_RDATASETATTR_STALE,
854458
+					     DNS_RDATASETATTR_STALE);
854458
+				dns_db_detachnode(db, &node);
854458
+				dns_rdataset_disassociate(&rdataset);
854458
+
854458
+				usleep(100000);	/* 100 ms */
854458
+
854458
+				result = dns_db_find(db, example, NULL,
854458
+						     dns_rdatatype_a,
854458
+						     DNS_DBFIND_STALEOK,
854458
+						     0, &node, found,
854458
+						     &rdataset, NULL);
854458
+			} while (result == ISC_R_SUCCESS);
854458
+			assert_in_range(count, 1, 10);
854458
+			assert_int_equal(result, ISC_R_NOTFOUND);
854458
+			break;
854458
+		case 2:
854458
+			assert_int_equal(result, ISC_R_NOTFOUND);
854458
+			break;
854458
+		}
854458
+	}
854458
+
854458
+	dns_db_detach(&db);
854458
+	isc_mem_detach(&mymctx);
854458
+}
854458
+
854458
 /* database class */
854458
 static void
854458
 class_test(void **state) {
854458
@@ -213,6 +405,8 @@ int
854458
 main(void) {
854458
 	const struct CMUnitTest tests[] = {
854458
 		cmocka_unit_test(getoriginnode_test),
854458
+		cmocka_unit_test(getsetservestalettl_test),
854458
+		cmocka_unit_test(dns_dbfind_staleok_test),
854458
 		cmocka_unit_test_setup_teardown(class_test,
854458
 						_setup, _teardown),
854458
 		cmocka_unit_test_setup_teardown(dbtype_test,
854458
diff --git a/lib/dns/view.c b/lib/dns/view.c
74b53c
index a1a4301..abf6a4c 100644
854458
--- a/lib/dns/view.c
854458
+++ b/lib/dns/view.c
854458
@@ -229,6 +229,9 @@ dns_view_create(isc_mem_t *mctx, dns_rdataclass_t rdclass,
854458
 	view->flush = false;
854458
 	view->dlv = NULL;
854458
 	view->maxudp = 0;
854458
+	view->staleanswerttl = 1;
854458
+	view->staleanswersok = dns_stale_answer_conf;
854458
+	view->staleanswersenable = false;
854458
 	view->nocookieudp = 0;
854458
 	view->maxbits = 0;
854458
 	view->v4_aaaa = dns_aaaa_ok;
854458
diff --git a/lib/isccfg/namedconf.c b/lib/isccfg/namedconf.c
74b53c
index 7bad989..bbf4b45 100644
854458
--- a/lib/isccfg/namedconf.c
854458
+++ b/lib/isccfg/namedconf.c
854458
@@ -1778,6 +1778,7 @@ view_clauses[] = {
854458
 	{ "max-ncache-ttl", &cfg_type_uint32, 0 },
854458
 	{ "max-recursion-depth", &cfg_type_uint32, 0 },
854458
 	{ "max-recursion-queries", &cfg_type_uint32, 0 },
854458
+	{ "max-stale-ttl", &cfg_type_ttlval, 0 },
854458
 	{ "max-udp-size", &cfg_type_uint32, 0 },
854458
 	{ "message-compression", &cfg_type_boolean, 0 },
854458
 	{ "min-roots", &cfg_type_uint32, CFG_CLAUSEFLAG_NOTIMP },
854458
@@ -1806,7 +1807,9 @@ view_clauses[] = {
854458
 	{ "request-nsid", &cfg_type_boolean, 0 },
854458
 	{ "request-sit", &cfg_type_boolean, CFG_CLAUSEFLAG_OBSOLETE },
854458
 	{ "require-server-cookie", &cfg_type_boolean, 0 },
854458
+	{ "resolver-nonbackoff-tries", &cfg_type_uint32, 0 },
854458
 	{ "resolver-query-timeout", &cfg_type_uint32, 0 },
854458
+	{ "resolver-retry-interval", &cfg_type_uint32, 0 },
854458
 	{ "response-policy", &cfg_type_rpz, 0 },
854458
 	{ "rfc2308-type1", &cfg_type_boolean, CFG_CLAUSEFLAG_NYI },
854458
 	{ "root-delegation-only",  &cfg_type_optional_exclude, 0 },
854458
@@ -1815,6 +1818,8 @@ view_clauses[] = {
854458
 	{ "send-cookie", &cfg_type_boolean, 0 },
854458
 	{ "servfail-ttl", &cfg_type_ttlval, 0 },
854458
 	{ "sortlist", &cfg_type_bracketed_aml, 0 },
854458
+	{ "stale-answer-enable", &cfg_type_boolean, 0 },
854458
+	{ "stale-answer-ttl", &cfg_type_ttlval, 0 },
854458
 	{ "suppress-initial-notify", &cfg_type_boolean, CFG_CLAUSEFLAG_NYI },
854458
 	{ "topology", &cfg_type_bracketed_aml, CFG_CLAUSEFLAG_NOTIMP },
854458
 	{ "transfer-format", &cfg_type_transferformat, 0 },
854458
-- 
854458
2.20.1
854458