2
0
mirror of https://gitlab.isc.org/isc-projects/bind9 synced 2025-08-22 18:19:42 +00:00
bind/lib/dns/tests/dnstest.c

635 lines
13 KiB
C
Raw Normal View History

/*
* Copyright (C) Internet Systems Consortium, Inc. ("ISC")
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at https://mozilla.org/MPL/2.0/.
*
* See the COPYRIGHT file distributed with this work for additional
* information regarding copyright ownership.
*/
/*! \file */
#include <inttypes.h>
Include <sched.h> where necessary for musl libc All unit tests define the UNIT_TESTING macro, which causes <cmocka.h> to replace malloc(), calloc(), realloc(), and free() with its own functions tracking memory allocations. In order for this not to break compilation, the system header declaring the prototypes for these standard functions must be included before <cmocka.h>. Normally, these prototypes are only present in <stdlib.h>, so we make sure it is included before <cmocka.h>. However, musl libc also defines the prototypes for calloc() and free() in <sched.h>, which is included by <pthread.h>, which is included e.g. by <isc/mutex.h>. Thus, unit tests including "dnstest.h" (which includes <isc/mem.h>, which includes <isc/mutex.h>) after <cmocka.h> will not compile with musl libc as for these programs, <sched.h> will be included after <cmocka.h>. Always including <cmocka.h> after all other header files is not a feasible solution as that causes the mock assertion macros defined in <isc/util.h> to mangle the contents of <cmocka.h>, thus breaking compilation. We cannot really use the __noreturn__ or analyzer_noreturn attributes with cmocka assertion functions because they do return if the tested condition is true. The problem is that what BIND unit tests do is incompatible with Clang Static Analyzer's assumptions: since we use cmocka, our custom assertion handlers are present in a shared library (i.e. it is the cmocka library that checks the assertion condition, not a macro in unit test code). Redefining cmocka's assertion macros in <isc/util.h> is an ugly hack to overcome that problem - unfortunately, this is the only way we can think of to make Clang Static Analyzer properly process unit test code. Giving up on Clang Static Analyzer being able to properly process unit test code is not a satisfactory solution. Undefining _GNU_SOURCE for unit test code could work around the problem (musl libc's <sched.h> only defines the prototypes for calloc() and free() when _GNU_SOURCE is defined), but doing that could introduce discrepancies for unit tests including entire *.c files, so it is also not a good solution. All in all, including <sched.h> before <cmocka.h> for all affected unit tests seems to be the most benign way of working around this musl libc quirk. While quite an ugly solution, it achieves our goals here, which are to keep the benefit of proper static analysis of unit test code and to fix compilation against musl libc.
2019-07-30 21:08:40 +02:00
#include <sched.h> /* IWYU pragma: keep */
#include <setjmp.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
2015-10-06 14:10:49 +11:00
#include <stdlib.h>
Include <sched.h> where necessary for musl libc All unit tests define the UNIT_TESTING macro, which causes <cmocka.h> to replace malloc(), calloc(), realloc(), and free() with its own functions tracking memory allocations. In order for this not to break compilation, the system header declaring the prototypes for these standard functions must be included before <cmocka.h>. Normally, these prototypes are only present in <stdlib.h>, so we make sure it is included before <cmocka.h>. However, musl libc also defines the prototypes for calloc() and free() in <sched.h>, which is included by <pthread.h>, which is included e.g. by <isc/mutex.h>. Thus, unit tests including "dnstest.h" (which includes <isc/mem.h>, which includes <isc/mutex.h>) after <cmocka.h> will not compile with musl libc as for these programs, <sched.h> will be included after <cmocka.h>. Always including <cmocka.h> after all other header files is not a feasible solution as that causes the mock assertion macros defined in <isc/util.h> to mangle the contents of <cmocka.h>, thus breaking compilation. We cannot really use the __noreturn__ or analyzer_noreturn attributes with cmocka assertion functions because they do return if the tested condition is true. The problem is that what BIND unit tests do is incompatible with Clang Static Analyzer's assumptions: since we use cmocka, our custom assertion handlers are present in a shared library (i.e. it is the cmocka library that checks the assertion condition, not a macro in unit test code). Redefining cmocka's assertion macros in <isc/util.h> is an ugly hack to overcome that problem - unfortunately, this is the only way we can think of to make Clang Static Analyzer properly process unit test code. Giving up on Clang Static Analyzer being able to properly process unit test code is not a satisfactory solution. Undefining _GNU_SOURCE for unit test code could work around the problem (musl libc's <sched.h> only defines the prototypes for calloc() and free() when _GNU_SOURCE is defined), but doing that could introduce discrepancies for unit tests including entire *.c files, so it is also not a good solution. All in all, including <sched.h> before <cmocka.h> for all affected unit tests seems to be the most benign way of working around this musl libc quirk. While quite an ugly solution, it achieves our goals here, which are to keep the benefit of proper static analysis of unit test code and to fix compilation against musl libc.
2019-07-30 21:08:40 +02:00
#include <string.h>
#include <time.h>
#include <unistd.h>
#if HAVE_CMOCKA
#define UNIT_TESTING
#include <cmocka.h>
#include <isc/app.h>
#include <isc/buffer.h>
#include <isc/file.h>
#include <isc/hash.h>
#include <isc/hex.h>
#include <isc/lex.h>
#include <isc/managers.h>
#include <isc/mem.h>
Convert dispatch to netmgr The flow of operations in dispatch is changing and will now be similar for both UDP and TCP queries: 1) Call dns_dispatch_addresponse() to assign a query ID and register that we'll be listening for a response with that ID soon. the parameters for this function include callback functions to inform the caller when the socket is connected and when the message has been sent, as well as a task action that will be sent when the response arrives. (later this could become a netmgr callback, but at this stage to minimize disruption to the calling code, we continue to use isc_task for the response event.) on successful completion of this function, a dispatch entry object will be instantiated. 2) Call dns_dispatch_connect() on the dispatch entry. this runs isc_nm_udpconnect() or isc_nm_tcpdnsconnect(), as needed, and begins listening for responses. the caller is informed via a callback function when the connection is established. 3) Call dns_dispatch_send() on the dispatch entry. this runs isc_nm_send() to send a request. 4) Call dns_dispatch_removeresponse() to terminate listening and close the connection. Implementation comments below: - As we will be using netmgr buffers now. code to send the length in TCP queries has also been removed as that is handled by the netmgr. - TCP dispatches can be used by multiple simultaneous queries, so dns_dispatch_connect() now checks whether the dispatch is already connected before calling isc_nm_tcpdnsconnect() again. - Running dns_dispatch_getnext() from a non-network thread caused a crash due to assertions in the netmgr read functions that appear to be unnecessary now. the assertions have been removed. - fctx->nqueries was formerly incremented when the connection was successful, but is now incremented when the query is started and decremented if the connection fails. - It's no longer necessary for each dispatch to have a pool of tasks, so there's now a single task per dispatch. - Dispatch code to avoid UDP ports already in use has been removed. - dns_resolver and dns_request have been modified to use netmgr callback functions instead of task events. some additional changes were needed to handle shutdown processing correctly. - Timeout processing is not yet fully converted to use netmgr timeouts. - Fixed a lock order cycle reported by TSAN (view -> zone-> adb -> view) by by calling dns_zt functions without holding the view lock.
2021-01-14 13:02:57 -08:00
#include <isc/netmgr.h>
#include <isc/os.h>
2015-10-02 14:38:59 -07:00
#include <isc/print.h>
#include <isc/socket.h>
#include <isc/stdio.h>
#include <isc/string.h>
#include <isc/task.h>
#include <isc/timer.h>
#include <isc/util.h>
#include <dns/callbacks.h>
2011-12-05 20:51:41 +00:00
#include <dns/db.h>
#include <dns/fixedname.h>
#include <dns/log.h>
#include <dns/name.h>
#include <dns/result.h>
#include <dns/view.h>
#include <dns/zone.h>
#include "dnstest.h"
#define CHECK(r) \
do { \
result = (r); \
if (result != ISC_R_SUCCESS) { \
goto cleanup; \
} \
} while (0)
2020-02-13 14:44:37 -08:00
isc_mem_t *dt_mctx = NULL;
isc_log_t *lctx = NULL;
Refactor taskmgr to run on top of netmgr This commit changes the taskmgr to run the individual tasks on the netmgr internal workers. While an effort has been put into keeping the taskmgr interface intact, couple of changes have been made: * The taskmgr has no concept of universal privileged mode - rather the tasks are either privileged or unprivileged (normal). The privileged tasks are run as a first thing when the netmgr is unpaused. There are now four different queues in in the netmgr: 1. priority queue - netievent on the priority queue are run even when the taskmgr enter exclusive mode and netmgr is paused. This is needed to properly start listening on the interfaces, free resources and resume. 2. privileged task queue - only privileged tasks are queued here and this is the first queue that gets processed when network manager is unpaused using isc_nm_resume(). All netmgr workers need to clean the privileged task queue before they all proceed normal operation. Both task queues are processed when the workers are finished. 3. task queue - only (traditional) task are scheduled here and this queue along with privileged task queues are process when the netmgr workers are finishing. This is needed to process the task shutdown events. 4. normal queue - this is the queue with netmgr events, e.g. reading, sending, callbacks and pretty much everything is processed here. * The isc_taskmgr_create() now requires initialized netmgr (isc_nm_t) object. * The isc_nm_destroy() function now waits for indefinite time, but it will print out the active objects when in tracing mode (-DNETMGR_TRACE=1 and -DNETMGR_TRACE_VERBOSE=1), the netmgr has been made a little bit more asynchronous and it might take longer time to shutdown all the active networking connections. * Previously, the isc_nm_stoplistening() was a synchronous operation. This has been changed and the isc_nm_stoplistening() just schedules the child sockets to stop listening and exits. This was needed to prevent a deadlock as the the (traditional) tasks are now executed on the netmgr threads. * The socket selection logic in isc__nm_udp_send() was flawed, but fortunatelly, it was broken, so we never hit the problem where we created uvreq_t on a socket from nmhandle_t, but then a different socket could be picked up and then we were trying to run the send callback on a socket that had different threadid than currently running.
2021-04-09 11:31:19 +02:00
isc_nm_t *netmgr = NULL;
2020-02-13 14:44:37 -08:00
isc_taskmgr_t *taskmgr = NULL;
isc_task_t *maintask = NULL;
isc_timermgr_t *timermgr = NULL;
dns_zonemgr_t *zonemgr = NULL;
bool app_running = false;
int ncpus;
bool debug_mem_record = true;
static bool dst_active = false;
static bool test_running = false;
/*
* Logging categories: this needs to match the list in bin/named/log.c.
*/
static isc_logcategory_t categories[] = { { "", 0 },
{ "client", 0 },
{ "network", 0 },
{ "update", 0 },
{ "queries", 0 },
{ "unmatched", 0 },
{ "update-security", 0 },
{ "query-errors", 0 },
{ NULL, 0 } };
static void
2020-02-13 14:44:37 -08:00
cleanup_managers(void) {
if (maintask != NULL) {
isc_task_shutdown(maintask);
isc_task_destroy(&maintask);
}
Convert dispatch to netmgr The flow of operations in dispatch is changing and will now be similar for both UDP and TCP queries: 1) Call dns_dispatch_addresponse() to assign a query ID and register that we'll be listening for a response with that ID soon. the parameters for this function include callback functions to inform the caller when the socket is connected and when the message has been sent, as well as a task action that will be sent when the response arrives. (later this could become a netmgr callback, but at this stage to minimize disruption to the calling code, we continue to use isc_task for the response event.) on successful completion of this function, a dispatch entry object will be instantiated. 2) Call dns_dispatch_connect() on the dispatch entry. this runs isc_nm_udpconnect() or isc_nm_tcpdnsconnect(), as needed, and begins listening for responses. the caller is informed via a callback function when the connection is established. 3) Call dns_dispatch_send() on the dispatch entry. this runs isc_nm_send() to send a request. 4) Call dns_dispatch_removeresponse() to terminate listening and close the connection. Implementation comments below: - As we will be using netmgr buffers now. code to send the length in TCP queries has also been removed as that is handled by the netmgr. - TCP dispatches can be used by multiple simultaneous queries, so dns_dispatch_connect() now checks whether the dispatch is already connected before calling isc_nm_tcpdnsconnect() again. - Running dns_dispatch_getnext() from a non-network thread caused a crash due to assertions in the netmgr read functions that appear to be unnecessary now. the assertions have been removed. - fctx->nqueries was formerly incremented when the connection was successful, but is now incremented when the query is started and decremented if the connection fails. - It's no longer necessary for each dispatch to have a pool of tasks, so there's now a single task per dispatch. - Dispatch code to avoid UDP ports already in use has been removed. - dns_resolver and dns_request have been modified to use netmgr callback functions instead of task events. some additional changes were needed to handle shutdown processing correctly. - Timeout processing is not yet fully converted to use netmgr timeouts. - Fixed a lock order cycle reported by TSAN (view -> zone-> adb -> view) by by calling dns_zt functions without holding the view lock.
2021-01-14 13:02:57 -08:00
isc_managers_destroy(netmgr == NULL ? NULL : &netmgr,
taskmgr == NULL ? NULL : &taskmgr,
dispatch: Clean up connect and recv callbacks - disp_connected() has been split into two functions, udp_connected() (which takes 'resp' as an argument) and tcp_connected() (which takes 'disp', and calls the connect callbacks for all pending resps). - In dns_dispatch_connect(), if a connection is already open, we need to detach the dispentry immediately because we won't be running tcp_connected(). - dns_disptach_cancel() also now calls the connect callbacks for pending TCP responses, and the response callbacks for open TCP connections waiting on read. - If udp_connected() runs after dns_dispatch_cancel() has been called, ensure that the caller's connect callback is run. - If a UDP connection fails with EADDRINUSE, we try again up to five times with a different local port number before giving up. - If a TCP connection is canceled while still pending connection, the connect timeout may still fire. we attach the dispatch before connecting to ensure that it won't be detached too soon in this case. - The dispentry is no longer removed from the pending list when deactivating, so that the connect callback can still be run if dns_dispatch_removeresponse() was run while the connecting was pending. - Rewrote dns_dispatch_gettcp() to avoid a data race. - startrecv() and dispatch_getnext() can be called with a NULL resp when using TCP. - Refactored udp_recv() and tcp_recv() and added result logging. - EOF is now treated the same as CANCELED in response callbacks. - ISC_R_SHUTTINGDOWN is sent to the reponse callbacks for all resps if tcp_recv() is triggered by a netmgr shutdown. (response callbacks are *not* sent by udp_recv() in this case.)
2021-08-04 13:14:11 -07:00
timermgr == NULL ? NULL : &timermgr, NULL);
Convert dispatch to netmgr The flow of operations in dispatch is changing and will now be similar for both UDP and TCP queries: 1) Call dns_dispatch_addresponse() to assign a query ID and register that we'll be listening for a response with that ID soon. the parameters for this function include callback functions to inform the caller when the socket is connected and when the message has been sent, as well as a task action that will be sent when the response arrives. (later this could become a netmgr callback, but at this stage to minimize disruption to the calling code, we continue to use isc_task for the response event.) on successful completion of this function, a dispatch entry object will be instantiated. 2) Call dns_dispatch_connect() on the dispatch entry. this runs isc_nm_udpconnect() or isc_nm_tcpdnsconnect(), as needed, and begins listening for responses. the caller is informed via a callback function when the connection is established. 3) Call dns_dispatch_send() on the dispatch entry. this runs isc_nm_send() to send a request. 4) Call dns_dispatch_removeresponse() to terminate listening and close the connection. Implementation comments below: - As we will be using netmgr buffers now. code to send the length in TCP queries has also been removed as that is handled by the netmgr. - TCP dispatches can be used by multiple simultaneous queries, so dns_dispatch_connect() now checks whether the dispatch is already connected before calling isc_nm_tcpdnsconnect() again. - Running dns_dispatch_getnext() from a non-network thread caused a crash due to assertions in the netmgr read functions that appear to be unnecessary now. the assertions have been removed. - fctx->nqueries was formerly incremented when the connection was successful, but is now incremented when the query is started and decremented if the connection fails. - It's no longer necessary for each dispatch to have a pool of tasks, so there's now a single task per dispatch. - Dispatch code to avoid UDP ports already in use has been removed. - dns_resolver and dns_request have been modified to use netmgr callback functions instead of task events. some additional changes were needed to handle shutdown processing correctly. - Timeout processing is not yet fully converted to use netmgr timeouts. - Fixed a lock order cycle reported by TSAN (view -> zone-> adb -> view) by by calling dns_zt functions without holding the view lock.
2021-01-14 13:02:57 -08:00
if (app_running) {
isc_app_finish();
}
}
static isc_result_t
2020-02-13 14:44:37 -08:00
create_managers(void) {
isc_result_t result;
ncpus = isc_os_ncpus();
isc_managers_create(dt_mctx, ncpus, 0, 0, &netmgr, &taskmgr, &timermgr,
dispatch: Clean up connect and recv callbacks - disp_connected() has been split into two functions, udp_connected() (which takes 'resp' as an argument) and tcp_connected() (which takes 'disp', and calls the connect callbacks for all pending resps). - In dns_dispatch_connect(), if a connection is already open, we need to detach the dispentry immediately because we won't be running tcp_connected(). - dns_disptach_cancel() also now calls the connect callbacks for pending TCP responses, and the response callbacks for open TCP connections waiting on read. - If udp_connected() runs after dns_dispatch_cancel() has been called, ensure that the caller's connect callback is run. - If a UDP connection fails with EADDRINUSE, we try again up to five times with a different local port number before giving up. - If a TCP connection is canceled while still pending connection, the connect timeout may still fire. we attach the dispatch before connecting to ensure that it won't be detached too soon in this case. - The dispentry is no longer removed from the pending list when deactivating, so that the connect callback can still be run if dns_dispatch_removeresponse() was run while the connecting was pending. - Rewrote dns_dispatch_gettcp() to avoid a data race. - startrecv() and dispatch_getnext() can be called with a NULL resp when using TCP. - Refactored udp_recv() and tcp_recv() and added result logging. - EOF is now treated the same as CANCELED in response callbacks. - ISC_R_SHUTTINGDOWN is sent to the reponse callbacks for all resps if tcp_recv() is triggered by a netmgr shutdown. (response callbacks are *not* sent by udp_recv() in this case.)
2021-08-04 13:14:11 -07:00
NULL);
CHECK(isc_task_create(taskmgr, 0, &maintask));
return (ISC_R_SUCCESS);
cleanup:
cleanup_managers();
return (result);
}
isc_result_t
2020-02-13 14:44:37 -08:00
dns_test_begin(FILE *logfile, bool start_managers) {
isc_result_t result;
INSIST(!test_running);
test_running = true;
if (start_managers) {
CHECK(isc_app_start());
}
if (debug_mem_record) {
2015-12-09 19:07:20 +05:30
isc_mem_debugging |= ISC_MEM_DEBUGRECORD;
}
INSIST(dt_mctx == NULL);
isc_mem_create(&dt_mctx);
/* Don't check the memory leaks as they hide the assertions */
isc_mem_setdestroycheck(dt_mctx, false);
INSIST(!dst_active);
CHECK(dst_lib_init(dt_mctx, NULL));
dst_active = true;
if (logfile != NULL) {
isc_logdestination_t destination;
2020-02-13 14:44:37 -08:00
isc_logconfig_t *logconfig = NULL;
INSIST(lctx == NULL);
isc_log_create(dt_mctx, &lctx, &logconfig);
isc_log_registercategories(lctx, categories);
isc_log_setcontext(lctx);
dns_log_init(lctx);
dns_log_setcontext(lctx);
destination.file.stream = logfile;
destination.file.name = NULL;
destination.file.versions = ISC_LOG_ROLLNEVER;
destination.file.maximum_size = 0;
isc_log_createchannel(logconfig, "stderr", ISC_LOG_TOFILEDESC,
ISC_LOG_DYNAMIC, &destination, 0);
CHECK(isc_log_usechannel(logconfig, "stderr", NULL, NULL));
}
dns_result_register();
if (start_managers) {
CHECK(create_managers());
}
/*
* The caller might run from another directory, so tests
* that access test data files must first chdir to the proper
* location.
*/
if (chdir(TESTS_DIR) == -1) {
CHECK(ISC_R_FAILURE);
}
return (ISC_R_SUCCESS);
cleanup:
dns_test_end();
return (result);
}
void
2020-02-13 14:44:37 -08:00
dns_test_end(void) {
cleanup_managers();
dst_lib_destroy();
dst_active = false;
if (lctx != NULL) {
isc_log_destroy(&lctx);
}
if (dt_mctx != NULL) {
isc_mem_destroy(&dt_mctx);
}
test_running = false;
}
/*
* Create a view.
*/
isc_result_t
2020-02-13 14:44:37 -08:00
dns_test_makeview(const char *name, dns_view_t **viewp) {
isc_result_t result;
2020-02-13 14:44:37 -08:00
dns_view_t *view = NULL;
CHECK(dns_view_create(dt_mctx, dns_rdataclass_in, name, &view));
*viewp = view;
return (ISC_R_SUCCESS);
cleanup:
if (view != NULL) {
dns_view_detach(&view);
}
return (result);
}
isc_result_t
dns_test_makezone(const char *name, dns_zone_t **zonep, dns_view_t *view,
2020-02-13 14:44:37 -08:00
bool createview) {
dns_fixedname_t fixed_origin;
2020-02-13 14:44:37 -08:00
dns_zone_t *zone = NULL;
isc_result_t result;
dns_name_t *origin;
REQUIRE(view == NULL || !createview);
/*
* Create the zone structure.
*/
result = dns_zone_create(&zone, dt_mctx);
if (result != ISC_R_SUCCESS) {
return (result);
}
/*
* Set zone type and origin.
*/
dns_zone_settype(zone, dns_zone_primary);
origin = dns_fixedname_initname(&fixed_origin);
result = dns_name_fromstring(origin, name, 0, NULL);
if (result != ISC_R_SUCCESS) {
goto detach_zone;
}
result = dns_zone_setorigin(zone, origin);
if (result != ISC_R_SUCCESS) {
goto detach_zone;
}
/*
* If requested, create a view.
*/
if (createview) {
result = dns_test_makeview("view", &view);
if (result != ISC_R_SUCCESS) {
goto detach_zone;
}
}
/*
* If a view was passed as an argument or created above, attach the
* created zone to it. Otherwise, set the zone's class to IN.
*/
if (view != NULL) {
dns_zone_setview(zone, view);
dns_zone_setclass(zone, view->rdclass);
dns_view_addzone(view, zone);
} else {
dns_zone_setclass(zone, dns_rdataclass_in);
}
*zonep = zone;
return (ISC_R_SUCCESS);
detach_zone:
dns_zone_detach(&zone);
return (result);
}
isc_result_t
2020-02-13 14:44:37 -08:00
dns_test_setupzonemgr(void) {
isc_result_t result;
REQUIRE(zonemgr == NULL);
2011-09-02 23:46:33 +00:00
dispatch: Clean up connect and recv callbacks - disp_connected() has been split into two functions, udp_connected() (which takes 'resp' as an argument) and tcp_connected() (which takes 'disp', and calls the connect callbacks for all pending resps). - In dns_dispatch_connect(), if a connection is already open, we need to detach the dispentry immediately because we won't be running tcp_connected(). - dns_disptach_cancel() also now calls the connect callbacks for pending TCP responses, and the response callbacks for open TCP connections waiting on read. - If udp_connected() runs after dns_dispatch_cancel() has been called, ensure that the caller's connect callback is run. - If a UDP connection fails with EADDRINUSE, we try again up to five times with a different local port number before giving up. - If a TCP connection is canceled while still pending connection, the connect timeout may still fire. we attach the dispatch before connecting to ensure that it won't be detached too soon in this case. - The dispentry is no longer removed from the pending list when deactivating, so that the connect callback can still be run if dns_dispatch_removeresponse() was run while the connecting was pending. - Rewrote dns_dispatch_gettcp() to avoid a data race. - startrecv() and dispatch_getnext() can be called with a NULL resp when using TCP. - Refactored udp_recv() and tcp_recv() and added result logging. - EOF is now treated the same as CANCELED in response callbacks. - ISC_R_SHUTTINGDOWN is sent to the reponse callbacks for all resps if tcp_recv() is triggered by a netmgr shutdown. (response callbacks are *not* sent by udp_recv() in this case.)
2021-08-04 13:14:11 -07:00
result = dns_zonemgr_create(dt_mctx, taskmgr, timermgr, NULL, &zonemgr);
return (result);
}
isc_result_t
2020-02-13 14:44:37 -08:00
dns_test_managezone(dns_zone_t *zone) {
isc_result_t result;
REQUIRE(zonemgr != NULL);
result = dns_zonemgr_setsize(zonemgr, 1);
if (result != ISC_R_SUCCESS) {
return (result);
}
result = dns_zonemgr_managezone(zonemgr, zone);
return (result);
}
void
2020-02-13 14:44:37 -08:00
dns_test_releasezone(dns_zone_t *zone) {
REQUIRE(zonemgr != NULL);
dns_zonemgr_releasezone(zonemgr, zone);
}
void
2020-02-13 14:44:37 -08:00
dns_test_closezonemgr(void) {
REQUIRE(zonemgr != NULL);
2011-09-02 23:46:33 +00:00
dns_zonemgr_shutdown(zonemgr);
dns_zonemgr_detach(&zonemgr);
}
/*
* Sleep for 'usec' microseconds.
*/
void
2020-02-13 14:44:37 -08:00
dns_test_nap(uint32_t usec) {
struct timespec ts;
ts.tv_sec = usec / 1000000;
ts.tv_nsec = (usec % 1000000) * 1000;
nanosleep(&ts, NULL);
}
isc_result_t
dns_test_loaddb(dns_db_t **db, dns_dbtype_t dbtype, const char *origin,
2020-02-13 14:44:37 -08:00
const char *testfile) {
isc_result_t result;
dns_fixedname_t fixed;
2020-02-13 14:44:37 -08:00
dns_name_t *name;
name = dns_fixedname_initname(&fixed);
result = dns_name_fromstring(name, origin, 0, NULL);
if (result != ISC_R_SUCCESS) {
return (result);
}
result = dns_db_create(dt_mctx, "rbt", name, dbtype, dns_rdataclass_in,
0, NULL, db);
if (result != ISC_R_SUCCESS) {
return (result);
}
result = dns_db_load(*db, testfile, dns_masterformat_text, 0);
return (result);
}
static int
2020-02-13 14:44:37 -08:00
fromhex(char c) {
if (c >= '0' && c <= '9') {
return (c - '0');
} else if (c >= 'a' && c <= 'f') {
return (c - 'a' + 10);
} else if (c >= 'A' && c <= 'F') {
return (c - 'A' + 10);
}
printf("bad input format: %02x\n", c);
exit(3);
/* NOTREACHED */
}
/*
* Format contents of given memory region as a hex string, using the buffer
* of length 'buflen' pointed to by 'buf'. 'buflen' must be at least three
* times 'len'. Always returns 'buf'.
*/
char *
2020-02-13 14:44:37 -08:00
dns_test_tohex(const unsigned char *data, size_t len, char *buf,
size_t buflen) {
isc_constregion_t source = { .base = data, .length = len };
2020-02-13 14:44:37 -08:00
isc_buffer_t target;
isc_result_t result;
memset(buf, 0, buflen);
isc_buffer_init(&target, buf, buflen);
result = isc_hex_totext((isc_region_t *)&source, 1, " ", &target);
assert_int_equal(result, ISC_R_SUCCESS);
return (buf);
}
isc_result_t
dns_test_getdata(const char *file, unsigned char *buf, size_t bufsiz,
2020-02-13 14:44:37 -08:00
size_t *sizep) {
isc_result_t result;
unsigned char *bp;
2020-02-13 14:44:37 -08:00
char *rp, *wp;
char s[BUFSIZ];
size_t len, i;
FILE *f = NULL;
int n;
result = isc_stdio_open(file, "r", &f);
if (result != ISC_R_SUCCESS) {
return (result);
}
bp = buf;
while (fgets(s, sizeof(s), f) != NULL) {
rp = s;
wp = s;
len = 0;
while (*rp != '\0') {
if (*rp == '#') {
break;
}
if (*rp != ' ' && *rp != '\t' && *rp != '\r' &&
*rp != '\n') {
*wp++ = *rp;
len++;
}
rp++;
}
if (len == 0U) {
continue;
}
if (len % 2 != 0U) {
2015-10-08 09:56:48 -07:00
CHECK(ISC_R_UNEXPECTEDEND);
}
if (len > bufsiz * 2) {
2015-10-08 09:56:48 -07:00
CHECK(ISC_R_NOSPACE);
}
rp = s;
for (i = 0; i < len; i += 2) {
n = fromhex(*rp++);
n *= 16;
n += fromhex(*rp++);
*bp++ = n;
}
}
*sizep = bp - buf;
2015-10-08 09:56:48 -07:00
result = ISC_R_SUCCESS;
cleanup:
isc_stdio_close(f);
2015-10-08 09:56:48 -07:00
return (result);
}
static void
2020-02-13 14:44:37 -08:00
nullmsg(dns_rdatacallbacks_t *cb, const char *fmt, ...) {
UNUSED(cb);
UNUSED(fmt);
}
isc_result_t
dns_test_rdatafromstring(dns_rdata_t *rdata, dns_rdataclass_t rdclass,
dns_rdatatype_t rdtype, unsigned char *dst,
2020-02-13 14:44:37 -08:00
size_t dstlen, const char *src, bool warnings) {
dns_rdatacallbacks_t callbacks;
2020-02-13 14:44:37 -08:00
isc_buffer_t source, target;
isc_lex_t *lex = NULL;
isc_lexspecials_t specials = { 0 };
isc_result_t result;
size_t length;
REQUIRE(rdata != NULL);
REQUIRE(DNS_RDATA_INITIALIZED(rdata));
REQUIRE(dst != NULL);
REQUIRE(src != NULL);
/*
* Set up source to hold the input string.
*/
length = strlen(src);
isc_buffer_constinit(&source, src, length);
isc_buffer_add(&source, length);
/*
* Create a lexer as one is required by dns_rdata_fromtext().
*/
result = isc_lex_create(dt_mctx, 64, &lex);
if (result != ISC_R_SUCCESS) {
return (result);
}
/*
* Set characters which will be treated as valid multi-line RDATA
* delimiters while reading the source string. These should match
* specials from lib/dns/master.c.
*/
specials[0] = 1;
specials['('] = 1;
specials[')'] = 1;
specials['"'] = 1;
isc_lex_setspecials(lex, specials);
/*
* Expect DNS masterfile comments.
*/
isc_lex_setcomments(lex, ISC_LEXCOMMENT_DNSMASTERFILE);
/*
* Point lexer at source.
*/
result = isc_lex_openbuffer(lex, &source);
if (result != ISC_R_SUCCESS) {
goto destroy_lexer;
}
/*
* Set up target for storing uncompressed wire form of provided RDATA.
*/
isc_buffer_init(&target, dst, dstlen);
/*
* Set up callbacks so warnings and errors are not printed.
*/
if (!warnings) {
dns_rdatacallbacks_init(&callbacks);
callbacks.warn = callbacks.error = nullmsg;
}
/*
* Parse input string, determining result.
*/
result = dns_rdata_fromtext(rdata, rdclass, rdtype, lex, dns_rootname,
0, dt_mctx, &target, &callbacks);
destroy_lexer:
isc_lex_destroy(&lex);
return (result);
}
void
2020-02-13 14:44:37 -08:00
dns_test_namefromstring(const char *namestr, dns_fixedname_t *fname) {
size_t length;
isc_buffer_t *b = NULL;
2020-02-13 14:44:37 -08:00
isc_result_t result;
dns_name_t *name;
length = strlen(namestr);
name = dns_fixedname_initname(fname);
isc_buffer_allocate(dt_mctx, &b, length);
isc_buffer_putmem(b, (const unsigned char *)namestr, length);
result = dns_name_fromtext(name, b, dns_rootname, 0, NULL);
assert_int_equal(result, ISC_R_SUCCESS);
isc_buffer_free(&b);
}
isc_result_t
dns_test_difffromchanges(dns_diff_t *diff, const zonechange_t *changes,
2020-02-13 14:44:37 -08:00
bool warnings) {
isc_result_t result = ISC_R_SUCCESS;
unsigned char rdata_buf[1024];
dns_difftuple_t *tuple = NULL;
isc_consttextregion_t region;
2020-02-13 14:44:37 -08:00
dns_rdatatype_t rdatatype;
dns_fixedname_t fixedname;
dns_rdata_t rdata;
dns_name_t *name;
size_t i;
REQUIRE(diff != NULL);
REQUIRE(changes != NULL);
dns_diff_init(dt_mctx, diff);
for (i = 0; changes[i].owner != NULL; i++) {
/*
* Parse owner name.
*/
name = dns_fixedname_initname(&fixedname);
2020-02-13 14:44:37 -08:00
result = dns_name_fromstring(name, changes[i].owner, 0,
dt_mctx);
if (result != ISC_R_SUCCESS) {
break;
}
/*
* Parse RDATA type.
*/
region.base = changes[i].type;
region.length = strlen(changes[i].type);
result = dns_rdatatype_fromtext(&rdatatype,
(isc_textregion_t *)&region);
if (result != ISC_R_SUCCESS) {
break;
}
/*
* Parse RDATA.
*/
dns_rdata_init(&rdata);
result = dns_test_rdatafromstring(
&rdata, dns_rdataclass_in, rdatatype, rdata_buf,
sizeof(rdata_buf), changes[i].rdata, warnings);
if (result != ISC_R_SUCCESS) {
break;
}
/*
* Create a diff tuple for the parsed change and append it to
* the diff.
*/
result = dns_difftuple_create(dt_mctx, changes[i].op, name,
changes[i].ttl, &rdata, &tuple);
if (result != ISC_R_SUCCESS) {
break;
}
dns_diff_append(diff, &tuple);
}
if (result != ISC_R_SUCCESS) {
dns_diff_clear(diff);
}
return (result);
}
#endif /* HAVE_CMOCKA */