7¤0ìÀÅd/B 3ãÃ0Ã0Ã0Ã0ã£~û)R·ÈÕ$ß6—¬X(­ÒP�ÝÖ÷b,ß>˜à˜Å@|ûßË~Ú¼Qìx¾"“   ŠÆyD$�è`@�¦›ÏeâXä8Ž¢ …Œ1ÆCˆ1DfhÐ   ”ö•±d
"                   .h>

/*% ISCCC Message Structur work for additional
 * information regarding copyright ownership.
 */

/* draft-ietf-dnsext-delegation-signer-05.txt */
#pragma once

typedef struct dns_rdata_ds dns_rdata_dlv_t;
/*
 * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
 *
 * SPDX-License-Identifier: MPL-2.0
 *
 * 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.
 */

#pragma once

typedef struct dns_rdata_keydata {
	dns_rdatacommon_t common;
	isc_mem_t *mctx;
	uint32_t refresh;  /* Timer for refreshing data */
	uint32_t addhd;	   /* Hold-down timer for adding */
	uint32_t removehd; /* Hold-down timer for removing */
	uint16_t flags;	   /* Copy of DNSKEY_48 */
	dns_secproto_t protocol;
	dns_secalg_t algorithm;
	uint16_t datalen;
	unsigned char *data;
} dns_rdata_keydata_t;
/*ship.
 */

#pragma once

/* Known digest type(s). */
#define DNS_ZONEMD_DIGEST_SHA384 (1)
#define DNS_ZONEMD_DIGEST_SHA512 (2)

/*
 *  \brief per RFC 8976
 */
typedef struct dns_rdata_zonemd {
	dns_rdatacommon_t common;
	isc_mem_t *mctx;
	uint32_t serial;
	uint8_t scheme;
	uint8_t digest_type;
	unsigned char *digest;
	uint16_t length;
} dns_rdata_zonemd_t;
/*
 * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
 *
 * SPDX-License-Identifier: MPL-2.0
 *
 * 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.
 */

#pragma once

/*!
 *  \brief Per draft-ietf-dnsop-svcb-https-02
 */

typedef struct dns_rdata_in_svcb {
	dns_rdatacommon_t common;
	isc_mem_t *mctx;
	uint16_t priority;
	dns_name_t svcdomain;
	unsigned char *svc;
	uint16_t svclen;
	uintdata_nsec3_t;

/*
 * The corresponding NSEC3 interval is OPTOUT indicating possible
 * insecure delegations.
 */
#define DNS_NSEC3FLAG_OPTOUT 0x01U

/*%
 * The following flags are used in the private-type record (implemented in
 * lib/dns/private.c) which is used to store NSEC3PARAM data during the
 * time when it is not legal to have an actual NSEC3PARAM record in the
 * zone.  They are defined here because the private-type record uses the
 * same flags field for the OPTOUT flag above and for the private flags
 * below.  XXX: This should be considered for refactoring.
 */

/*%
 * Non-standard, private type only.
 *
 * Create a corresponding NSEC3 chain.
 * Once the NSEC3 chain is complete this flag will be removed to signal
 * that there is a complete chain.
 *
 * This flag is automatically set when a NSEC3PARAM record is added to
 * the zone via UPDATE.
 *
 * NSEC3PARAM records containing this flag should never be published,
 * but if they are, they should be ignored by RFC 5155 compliant
 * nameservers.
 *ht ownership.
 */

#pragma once

/*!
 * \brief Per RFC1876 */

typedef struct dns_rdata_loc_0 {
	uint8_t version; /* must be first and zero */
	uint8_t size;
	uint8_t horizontal;
	uint8_t vertical;
	uint32_t latitude;
	uint32_t longitude;
	uint32_t altitude;
} dns_rdata_loc_0_t;

typedef struct dns_rdata_loc {
	dns_rdatacommon_t common;
	union {
		dns_rdata_loc_0_t v0;
	} v;
} dns_rdata_loc_t;
/*
 * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
 *
 * SPDX-License-Identifier: MPL-2.0
 *
 * 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.
 */

#pragma once

/*!
 *  \brief RFC2535 */

typedef struct dns_rdata_nxt {
	dns_rdatacommon_t common;
	isc_mem_t *mctx;
	dns_name_t next;
	unsigned char *typebits;
	uint16_t len;
} dns_rdata_nxt_t;
/*
string {
	uint8_t length;
	unsigned char *data;
} dns_rdata_txt_string_t;

typedef struct dns_rdata_txt {
	dns_rdatacommon_t common;
	isc_mem_t *mctx;
	unsigned char *txt;
	uint16_t txt_len;
	/* private */
	uint16_t offset;
} dns_rdata_txt_t;

/*
 * ISC_LANG_BEGINDECLS and ISC_LANG_ENDDECLS are already done
 * via rdatastructpre.h and rdatastructsuf.h.
 */

isc_result_t
dns_rdata_txt_first(dns_rdata_txt_t *);

isc_result_t
dns_rdata_txt_next(dns_rdata_txt_t *);

isc_result_t
dns_rdata_txt_current(dns_rdata_txt_t *, dns_rdata_txt_string_t *);
/*
 * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
 *
 * SPDX-License-Identifier: MPL-2.0
 *
 * 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.
 */

#pragma once

/*!
 *  \brief Per RFC1183 */

tyee the COPYRIGHT file distributed with this work for additional
 * information regarding copyright ownership.
 */

/* */
#pragma once

typedef struct dns_rdata_in_a {
	dns_rdatacommon_t common;
	struct in_addr in_addr;
} dns_rdata_in_a_t;
/*
 * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
 *
 * SPDX-License-Identifier: MPL-2.0
 *
 * 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.
 */

/* by Bjorn.Victor@it.uu.se, 2005-05-07 */
/* Based on generic/mx_15.h */

#pragma once

typedef uint16_t ch_addr_t;

typedef struct dns_rdata_ch_a {
	dns_rdatacommon_t common;
	isc_mem_t *mctx;
	dns_name_t ch_addr_dom; /* ch-addr domain for back mapping
				 * */
	ch_addr_t ch_addr;	/* chaos address (16 bit) network
				 * order */
} dns_rdata_ch_a_t;
/'s metadata to
 * support rollback, and it aims to minimize the memory usage of the
 * trie between transactions. The trie is compacted when the transaction
 * commits, and any partly-used chunk is shrunk to fit.
 *
 * During the transaction, the modification mutex is held.
 *
 * Requires:
 * \li  `multi` is a pointer to a valid multi-threaded qp-trie
 * \li  `qptp != NULL`
 * \li  `*qptp == NULL`
 *
 * Returns:
 * \li  `*qptp` is a pointer to the modifiable qp-trie inside `multi`
 */

void
dns_qpmulti_write(dns_qpmulti_t *multi, dns_qp_t **qptp);
/*%<
 * Start a lightweight write transaction
 *
 * This style of transaction does not need extra allocations in addition
 * to the ones required by insert and delete operations. It is intended
 * for a large trie that gets frequent small writes, such as a DNS
 * cache.
 *
 * A sequence of lightweight write transactions can accumulate
 * garbage that the automatic compact/recycle cannot reclaim.
 * To reclaim this space, you can use the `dns_qp_memusage
 * fragmente
dns_qp_deletename(dns_qp_t *qp, const dns_name_t *name, void **pval_r,
		  uint32_t *ival_r);
/*%<
 * Delete a leaf from a qp-trie that matches the given DNS name
 *
 * The leaf values are assigned to whichever of `*pval_r` and `*ival_r`
 * are not null, unless the return value is ISC_R_NOTFOUND.
 *
 * Requires:
 * \li  `qp` is a pointer to a valid qp-trie
 * \li  `name` is a pointer to a valid qp-trie
 *
 * Returns:
 * \li  ISC_R_NOTFOUND if the trie has no leaf with a matching name
 * \li  ISC_R_SUCCESS if the leaf was deleted from the trie
 */

void
dns_qpiter_init(dns_qpreadable_t qpr, dns_qpiter_t *qpi);
/*%<
 * Initialize an iterator
 *
 * SAFETY NOTE: If `qpr` is a `dns_qp_t`, it is not safe to modify the
 * trie during iteration. If `qpr` is a `dns_qpread_t` or `dns_qpsnap_t`
 * then (like any other read-only access) modifications will not affect
 * iteration.
 *
 * Requires:
 * \li  `qp` is a pointer to a valid qp-trie
 * \li  `qpi` is a pointer to a qp iterator
 */

isc_result_t
dns_qpiter_next(dnsgned int	magic;
	dns_qpreader_t *qp;
	uint8_t		len;
	struct {
		dns_qpnode_t *node;
		size_t	      offset;
	} chain[DNS_NAME_MAXLABELS];
} dns_qpchain_t;

/*%
 * These leaf methods allow the qp-trie code to call back to the code
 * responsible for the leaf values that are stored in the trie. The
 * methods are provided for a whole trie when the trie is created.
 *
 * When you create a qp-trie, you provide a context pointer that is
 * passed to the methods. The context pointer can tell the methods
 * something about the trie as a whole, in addition to a particular
 * leaf's values.
 *
 * The `attach` and `detach` methods adjust reference counts on value
 * objects. They support copy-on-write and safe memory reclamation
 * needed for multi-version concurrency. The methods are only called
 * when the `dns_qpmulti_t` mutex is held.
 *
 * Note: When a value object reference count is greater than one, the
 * object is in use by concurrent readers so it must not be modified. A
 * refcount equal to one does not indicinformation regarding copyright ownership.
 */

#pragma once

/*
 * A qp-trie is a kind of key -> value map, supporting lookups that are
 * aware of the lexicographic order of keys.
 *
 * Keys are `dns_qpkey_t`, which is a string-like thing, usually created
 * from a DNS name. You can use both relative and absolute DNS names as
 * keys, even in the same trie, except for one caveat: if a trie contains
 * names relative to the zone apex, the natural way to represent the apex
 * itself (spelled `@` in zone files) is a zero-length name; but a
 * zero-length name has the same qpkey representation as the root zone
 * (apart from its length), so they collide.
 *
 * Leaf values are a pair of a `void *` pointer and a `uint32_t`
 * (because that is what fits inside an internal qp-trie leaf node).
 *
 * The trie does not store keys; instead keys are derived from leaf values
 * by calling a method provided by the user.
 *
 * There are a few flavours of qp-trie.
 *
 * The basic `dns_qp_t` supports single-threaded read/wriumber of signatures that will be generated per quantum.
 */

isc_result_t
dns_zone_signwithkey(dns_zone_t *zone, dns_secalg_t algorithm, uint16_t keyid,
		     bool deleteit);
/*%<
 * Initiate/resume signing of the entire zone with the zone DNSKEY(s)
 * that match the given algorithm and keyid.
 */

isc_result_t
dns_zone_addnsec3chain(dns_zone_t *zone, dns_rdata_nsec3param_t *nsec3param);
/*%<
 * Incrementally add a NSEC3 chain that corresponds to 'nsec3param'.
 */

void
dns_zone_setprivatetype(dns_zone_t *zone, dns_rdatatype_t type);
dns_rdatatype_t
dns_zone_getprivatetype(dns_zone_t *zone);
/*
 * Get/Set the private record type.  It is expected that these interfaces
 * will not be permanent.
 */

void
dns_zone_rekey(dns_zone_t *zone, bool fullsign);
/*%<
 * Update the zone's DNSKEY set from the key repository.
 *
 * If 'fullsign' is true, trigger an immediate full signing of
 * the zone with the new key.  Otherwise, if there are no keys or
 * if the new keys are for algorithms that have already signed the
 _t *ver,
		  isc_stdtime_t now, isc_mem_t *mctx, unsigned int maxkeys,
		  dst_key_t **keys, unsigned int *nkeys);
/*%<
 * Finds a set of zone keys. Searches in the applicable key stores for the
 * given 'zone' if there is a dnssec-policy attached, otherwise it looks up
 * the keys in the zone's key-directory. The found keys are loaded into 'keys'.
 *
 * Requires:
 *\li	'zone' to be a valid initialised zone.
 *\li	'mctx' is not NULL.
 *\li	'keys' is not NULL and has enough space form 'nkeys' keys.
 *\li	'nkeys' is not NULL.
 *
 * Returns:
 *\li	#ISC_R_SUCCESS
 *\li	Error
 */

void
dns_zone_prepare_shutdown(dns_zone_t *zone);
/*%<
 * Prepare a zone for shutdown by setting the DNS_ZONEFLG_EXITING flag even
 * before the final reference is detached. Useful, because the zone object can
 * be kept around with a valid reference from the zonetable until qp garbage
 * collector runs, and we don't want, for example, zone maintenance to happen
 * while waiting for it. Note that the zone can not be used normally again a*zone, uint32_t maxxfrout);
/*%<
 * Set the maximum time (in seconds) that a zone transfer out (AXFR/IXFR)
 * of this zone will use before being aborted.
 *
 * Requires:
 * \li	'zone' to be valid initialised zone.
 */

uint32_t
dns_zone_getmaxxfrout(dns_zone_t *zone);
/*%<
 * Returns the maximum transfer time for this zone.  This will be
 * either the value set by the last call to dns_zone_setmaxxfrout() or
 * the default value of 1 hour.
 *
 * Requires:
 *\li	'zone' to be valid initialised zone.
 */

isc_result_t
dns_zone_setjournal(dns_zone_t *zone, const char *myjournal);
/*%<
 * Sets the filename used for journaling updates / IXFR transfers.
 * The default journal name is set by dns_zone_setfile() to be
 * "file.jnl".  If 'myjournal' is NULL, the zone will have no
 * journal name.
 *
 * Requires:
 *\li	'zone' to be a valid zone.
 *
 * Returns:
 *\li	#ISC_R_SUCCESS
 *\li	#ISC_R_NOMEMORY
 */

char *
dns_zone_getjournal(dns_zone_t *zone);
/*%<
 * Returns the journal name associated with this zone.
 * If no jatible form of
 *    dns_zone_dumptostream3(), which always uses the current
 *    default raw file format version.
 *
 *    Note that dns_zone_dumptostream3() is the most flexible form.  It
 *    can also provide the functionality of dns_zone_fulldumptostream().
 *
 * Require:
 *\li	'zone' to be a valid zone.
 *\li	'fd' to be a stream open for writing.
 */

void
dns_zone_setprimaries(dns_zone_t *zone, isc_sockaddr_t *addresses,
		      isc_sockaddr_t *sources, dns_name_t **keynames,
		      dns_name_t **tlsnames, uint32_t count);
/*%<
 *	Set the list of primary servers for the zone.
 *
 * Require:
 *\li	'zone' to be a valid zone.
 *\li	'addresses' array of isc_sockaddr_t with port set or NULL.
 *\li	'count' the number of primaries.
 *\li	'keynames' array of dns_name_t's for tsig keys or NULL.
 *
 *\li	If 'addresses' is NULL then 'count' must be zero.
 *
 * Returns:
 *\li	#ISC_R_SUCCESS
 *\li	#ISC_R_NOMEMORY
 *\li      Any result dns_name_dup() can return, if keynames!=NULL
 */

void
dns_zone_setparentals(dnsed based on
 *			  file system timestamps.
 *\li	DNS_R_BADZONE
 *\li	Any result value from dns_db_load().
 */

isc_result_t
dns_zone_asyncload(dns_zone_t *zone, bool newonly, dns_zt_callback_t done,
		   void *arg);
/*%<
 * Cause the database to be loaded from its backing store asynchronously.
 * Other zone maintenance functions are suspended until this is complete.
 * When finished, 'done' is called to inform the caller, with 'arg' as
 * its argument. (Normally, 'arg' is expected to point to the zone table
 * but is left undefined for testing purposes.)
 *
 * Require:
 *\li	'zone' to be a valid zone.
 *
 * Returns:
 *\li	#ISC_R_ALREADYRUNNING
 *\li	#ISC_R_SUCCESS
 *\li	#ISC_R_FAILURE
 *\li	#ISC_R_NOMEMORY
 */

bool
dns__zone_loadpending(dns_zone_t *zone);
/*%<
 * Indicates whether the zone is waiting to be loaded asynchronously.
 * (Not currently intended for use outside of this module and associated
 * tests.)
 */

void
dns_zone_iattach(dns_zone_t *source, dns_zone_t **target);
/*%<
 *	Attach '*target' to 'if			      /* ifndef DNS_ZONE_MINRETRY */
#ifndef DNS_ZONE_MAXRETRY
#define DNS_ZONE_MAXRETRY 1209600 /*%< 2 weeks */
#endif				  /* ifndef DNS_ZONE_MAXRETRY */
#ifndef DNS_ZONE_DEFAULTRETRY
#define DNS_ZONE_DEFAULTRETRY        \
	60 /*%< 1 minute, subject to \
	    * exponential backoff */
#endif	   /* ifndef DNS_ZONE_DEFAULTRETRY */

ISC_LANG_BEGINDECLS

/***
 ***	Functions
 ***/

void
dns_zone_create(dns_zone_t **zonep, isc_mem_t *mctx, unsigned int tid);
/*%<
 *	Creates a new empty zone and attach '*zonep' to it.
 *
 * Requires:
 *\li	'zonep' to point to a NULL pointer.
 *\li	'mctx' to be a valid memory context.
 *
 * Ensures:
 *\li	'*zonep' refers to a valid zone.
 */

isc_result_t
dns_zone_makedb(dns_zone_t *zone, dns_db_t **dbp);
/*%<
 *	Creates a new empty database for the 'zone'.
 *
 * Requires:
 *\li	'zone' to be a valid zone.
 *\li	'dbp' to point to NULL pointer.
 *
 * Returns:
 *\li	dns_db_create() error codes.
 */

void
dns_zone_setclass(dns_zone_t *zone, dns_rdataclass_t rdclass);
/*%<
 *	Sets tst, if any.  If this key was
 * not negotiated via TKEY, return NULL.
 *
 * Requires:
 *	"key" is a valid key.
 */

isc_result_t
dst_key_dump(dst_key_t *key, isc_mem_t *mctx, char **buffer, int *length);
/*%<
 * Allocate 'buffer' and dump the key into it in base64 format. The buffer
 * is not NUL terminated. The length of the buffer is returned in *length.
 *
 * 'buffer' needs to be freed using isc_mem_put(mctx, buffer, length);
 *
 * Requires:
 *	'buffer' to be non NULL and *buffer to be NULL.
 *	'length' to be non NULL and *length to be zero.
 *
 * Returns:
 *	ISC_R_SUCCESS
 *	ISC_R_NOMEMORY
 *	ISC_R_NOTIMPLEMENTED
 *	others.
 */

isc_result_t
dst_key_restore(dns_name_t *name, unsigned int alg, unsigned int flags,
		unsigned int protocol, dns_rdataclass_t rdclass,
		isc_mem_t *mctx, const char *keystr, dst_key_t **keyp);

bool
dst_key_inactive(const dst_key_t *key);
/*%<
 * Determines if the private key is missing due the key being deemed inactive.
 *
 * Requires:
 *	'key' to be valid.
 */

void
dst_key_setfile(dns_name_t *name, dns_keytag_t id, unsigned int alg, int type,
		 const char *directory, isc_mem_t *mctx, dst_key_t **keyp);
/*%<
 * Reads a key from permanent storage.  The key can either be a public or
 * private key, or a key state. It specified by name, algorithm, and id.  If
 * a private key or key state is specified, the public key must also be
 * present.  If directory is NULL, the current directory is assumed.
 *
 * Requires:
 * \li	"name" is a valid absolute dns name.
 * \li	"id" is a valid key tag identifier.
 * \li	"alg" is a supported key algorithm.
 * \li	"type" is DST_TYPE_PUBLIC, DST_TYPE_PRIVATE or the bitwise union.
 *		  DST_TYPE_KEY look for a KEY record otherwise DNSKEY.
 *		  DST_TYPE_STATE to also read the key state.
 * \li	"mctx" is a valid memory context.
 * \li	"keyp" is not NULL and "*keyp" is NULL.
 *
 * Returns:
 * \li	ISC_R_SUCCESS
 * \li	any other result indicates failure
 *
 * Ensures:
 * \li	If successful, *keyp will contain a valid key.
 */

isc_result_t
dst_key_fromnamedl.
 */

unsigned int
isc_mempool_getfillcount(isc_mempool_t *restrict mpctx);
/*%<
 * Returns the number of items allocated as a block from the parent
 * memory context when the free list is empty.
 */

void
isc_mempool_setfillcount(isc_mempool_t *restrict mpctx,
			 const unsigned int limit);
/*%<
 * Sets the fillcount.
 *
 * Additional requirements:
 *\li	limit > 0
 */

#if defined(UNIT_TESTING) && defined(malloc)
/*
 * cmocka.h redefined malloc as a macro, we #undef it
 * to avoid replacing ISC_ATTR_MALLOC with garbage.
 */
#pragma push_macro("malloc")
#undef malloc
#define POP_MALLOC_MACRO 1
#endif

/*
 * Pseudo-private functions for use via macros.  Do not call directly.
 */
void
isc__mem_putanddetach(isc_mem_t **, void *, size_t, int _ISC_MEM_FLARG);
void
isc__mem_put(isc_mem_t *, void *, size_t, int _ISC_MEM_FLARG);
void
isc__mem_free(isc_mem_t *, void *, int _ISC_MEM_FLARG);

ISC_ATTR_MALLOC_DEALLOCATOR_IDX(isc__mem_put, 2)
void *
isc__mem_get(isc_mem_t *, size_t, int _ISC_MEM_FLARG);

ISC_ATTR_DEALLO*	...
 * } *ptr;
 *
 * isc_mem_t *mctx;
 *
 * isc_mem_putanddetach(&ptr->mctx, ptr, sizeof(*ptr));
 * \endcode
 *
 * is the equivalent of:
 *
 * \code
 * mctx = NULL;
 * isc_mem_attach(ptr->mctx, &mctx);
 * isc_mem_detach(&ptr->mctx);
 * isc_mem_put(mctx, ptr, sizeof(*ptr));
 * isc_mem_detach(&mctx);
 * \endcode
 */

/*%
 * These functions are actually implemented in isc__mem_<function>
 * (two underscores). The single-underscore macros are used to pass
 * __FILE__ and __LINE__, and in the case of the put functions, to
 * set the pointer being freed to NULL in the calling function.
 */

/*%
 * The definitions of the macros have been pulled directly from jemalloc.h
 * and checked for consistency in mem.c.
 *
 *\li	ISC__MEM_ZERO - fill the memory with zeroes before returning
 */

#define ISC__MEM_ZERO ((int)0x40)

#define isc_mem_get(c, s) isc__mem_get((c), (s), 0 _ISC_MEM_FILELINE)
#define isc_mem_cget(c, n, s)                        \
	isc__mem_get((c), ISC_CHECKED_MUL((n), (s)), \
		     ISC__MEM_ZERO _ISC_M*!<
 * The variable isc_mem_debugging holds a set of flags for
 * turning certain memory debugging options on or off at
 * runtime.  It is initialized to the value ISC_MEM_DEGBUGGING,
 * which is 0 by default but may be overridden at compile time.
 * The following flags can be specified:
 *
 * \li #ISC_MEM_DEBUGTRACE
 *	Log each allocation and free to isc_lctx.
 *
 * \li #ISC_MEM_DEBUGRECORD
 *	Remember each allocation, and match them up on free.
 *	Crash if a free doesn't match an allocation.
 *
 * \li #ISC_MEM_DEBUGUSAGE
 *	Every time the memory usage is greater (lower) than hi_water
 *	(lo_water) mark, print the current inuse memory.
 */
/*@}*/

#if ISC_MEM_TRACKLINES
#define _ISC_MEM_FILELINE , __FILE__, __LINE__
#define _ISC_MEM_FLARG	  , const char *, unsigned int
#else /* if ISC_MEM_TRACKLINES */
#define _ISC_MEM_FILELINE
#define _ISC_MEM_FLARG
#endif /* if ISC_MEM_TRACKLINES */

/*
 * Flags for isc_mem_create() calls.
 */
#define ISC_MEMFLAG_RESERVED1 0x00000001 /* reserved, obsoleted, don't use */
#daining 'NULL'.
 */

void
isc_tls_cert_store_free(isc_tls_cert_store_t **pstore);
/*%<
 * Free X509 certificate store.
 *
 * Requires:
 *\li	'pstore' is a valid pointer to a pointer containing a non-'NULL' value.
 */

typedef struct isc_tlsctx_client_session_cache isc_tlsctx_client_session_cache_t;
/*%<
 * TLS client session cache is an object which allows efficient
 * storing and retrieval of previously saved TLS sessions so that they
 * can be resumed. This object is supposed to be a foundation for
 * implementing TLS session resumption - a standard technique to
 * reduce the cost of re-establishing a connection to the remote
 * server endpoint.
 *
 * OpenSSL does server-side TLS session caching transparently by
 * default. However, on the client-side, a TLS session to resume must
 * be manually specified when establishing the TLS connection. The TLS
 * client session cache is precisely the foundation for that.
 *
 * The cache has been designed to have the following characteristics:
 *
 * - Fixed maximal numcsignstats_type_t operation);
/*%<
 * Increment the statistics counter for the DNSKEY 'id' with algorithm 'alg'.
 * The 'operation' determines what counter is incremented.
 *
 * Requires:
 *\li	'stats' is a valid dns_stats_t created by dns_dnssecsignstats_create().
 */

void
dns_dnssecsignstats_clear(dns_stats_t *stats, dns_keytag_t id, uint8_t alg);
/*%<
 * Clear the statistics counter for the DNSKEY 'id' with algorithm 'alg'.
 *
 * Requires:
 *\li	'stats' is a valid dns_stats_t created by dns_dnssecsignstats_create().
 */

void
dns_generalstats_dump(dns_stats_t *stats, dns_generalstats_dumper_t dump_fn,
		      void *arg, unsigned int options);
/*%<
 * Dump the current statistics counters in a specified way.  For each counter
 * in stats, dump_fn is called with its current value and the given argument
 * arg.  By default counters that have a value of 0 is skipped; if options has
 * the ISC_STATSDUMP_VERBOSE flag, even such counters are dumped.
 *
 * This function is obsolete.  A more general function, isc_s,
	dns_resstatscounter_queryrtt5 = 29,
	dns_resstatscounter_nfetch = 30,
	dns_resstatscounter_disprequdp = 31,
	dns_resstatscounter_dispreqtcp = 32,
	dns_resstatscounter_buckets = 33,
	dns_resstatscounter_refused = 34,
	dns_resstatscounter_cookienew = 35,
	dns_resstatscounter_cookieout = 36,
	dns_resstatscounter_cookiein = 37,
	dns_resstatscounter_cookieok = 38,
	dns_resstatscounter_badvers = 39,
	dns_resstatscounter_badcookie = 40,
	dns_resstatscounter_zonequota = 41,
	dns_resstatscounter_serverquota = 42,
	dns_resstatscounter_clientquota = 43,
	dns_resstatscounter_nextitem = 44,
	dns_resstatscounter_priming = 45,
	dns_resstatscounter_max = 46,

	/*
	 * DNSSEC stats.
	 */
	dns_dnssecstats_asis = 0,
	dns_dnssecstats_downcase = 1,
	dns_dnssecstats_wildcard = 2,
	dns_dnssecstats_fail = 3,

	dns_dnssecstats_max = 4,

	/*%
	 * Zone statistics counters.
	 */
	dns_zonestatscounter_notifyoutv4 = 0,
	dns_zonestatscounter_notifyoutv6 = 1,
	dns_zonestatscounter_notifyinv4 = 2,
	dns_zonestatscounter_notifyinv6 = 3,
	dns	  bool have_rd, bool have_do);
LIBDEF_F(rsp_create)

/**
 * Finish RPZ work for a DNS response.
 */
typedef void(librpz_rsp_detach_t)(librpz_rsp_t **rspp);
LIBDEF_F(rsp_detach)

/**
 * Get the final, accumulated result of a set of RPZ queries.
 * Yield LIBRPZ_POLICY_UNDEFINED if
 *  - there were no hits,
 *  - there was a dispositive hit, be we have not recursed and are required
 *	to recurse so that evil DNS authorities will not know we are using RPZ
 *  - we have a hit and have recursed, but later data such as NSIP could
 *	override
 * @param[out] emsg
 * @param[out] result describes the hit
 *	or result->policy=LIBRPZ_POLICY_UNDEFINED without a hit
 * @param[out] result: current policy rewrite values
 * @param recursed: recursion has now been done even if it was not done
 *	when the hit was found
 * @param[in,out] rsp state from librpz_itr_start()
 * @return false on error
 */
typedef bool(librpz_rsp_result_t)(librpz_emsg_t *emsg, librpz_result_t *result,
				  bool recursed, const librpz_rsp_t *rsp);
LIB on
 *	the consistency of version N+1.
 *
 * This version mechanism depends in part on not being exercised too frequently
 *	Version numbers are 32 bits long and dnsrpzd creates new versions
 *	at most once every 30 seconds.
 */

/*
 * Lock functions for concurrent use of a single librpz_client_t client handle.
 */
typedef void(librpz_mutex_t)(void *mutex);

/*
 * List of connections to dnsrpzd daemons.
 */
typedef struct librpz_clist librpz_clist_t;

/*
 * Client's handle on dnsrpzd.
 */
typedef struct librpz_client librpz_client_t;

/**
 * Create the list of connections to the dnsrpzd daemon.
 * @param[out] emsg: error message
 * @param lock: start exclusive access to the client handle
 * @param unlock: end exclusive access to the client handle
 * @param mutex_destroy: release the lock
 * @param mutex: pointer to the lock for the client handle
 * @param log_ctx: NULL or resolver's context log messages
 */
typedef librpz_clist_t *(librpz_clist_create_t)(librpz_emsg_t * emsg,
						librpz_mutex_t *lock,
					 LIBDEF(t, s)
#define LIBDEF_F(f)
#endif /* ifdef LIBRPZ_INTERNAL */

#define LIBRPZ_MAXDOMAIN 255

/*
 * Response Policy Zone triggers.
 *	Comparisons of trigger precedences require
 *	LIBRPZ_TRIG_CLIENT_IP < LIBRPZ_TRIG_QNAME < LIBRPZ_TRIG_IP
 *	    < LIBRPZ_TRIG_NSDNAME < LIBRPZ_TRIG_NSIP}
 */
typedef enum {
	LIBRPZ_TRIG_BAD = 0,
	LIBRPZ_TRIG_CLIENT_IP = 1,
	LIBRPZ_TRIG_QNAME = 2,
	LIBRPZ_TRIG_IP = 3,
	LIBRPZ_TRIG_NSDNAME = 4,
	LIBRPZ_TRIG_NSIP = 5
} librpz_trig_t;
#define LIBRPZ_TRIG_SIZE 3     /* sizeof librpz_trig_t in bits */
typedef uint8_t librpz_tbit_t; /* one bit for each of the TRIGS_NUM
				* trigger types */

/*
 * Response Policy Zone Actions or policies
 */
typedef enum {
	LIBRPZ_POLICY_UNDEFINED = 0, /* an empty entry or no decision yet */
	LIBRPZ_POLICY_DELETED = 1,   /* placeholder for a deleted policy */

	LIBRPZ_POLICY_PASSTHRU = 2, /* 'passthru': do not rewrite */
	LIBRPZ_POLICY_DROP = 3,	    /* 'drop': do not respond */
	LIBRPZ_POLICY_TCP_ONLY = 4, /* 'tcp-only': answer UDP with TC=1 */luded AAAA records in from the
 * matching dns64 records in the list starting at 'dns64'.  If there
 * is a non-excluded address return true.  If all addresses are
 * excluded in the matched records return false.   If no records
 * match then return true.
 *
 * If aaaaok is defined then dns_dns64_aaaaok() return a array of which
 * addresses in 'rdataset' were deemed to not be exclude by any matching
 * record.  If there are no matching records then all entries are set
 * to true.
 *
 * Requires
 * 	'rdataset'	to be valid and to be for type AAAA and class IN.
 *	'aaaaoklen'	must match the number of records in 'rdataset'
 *			if 'aaaaok' in non NULL.
 */

isc_result_t
dns_dns64_findprefix(dns_rdataset_t *rdataset, isc_netprefix_t *prefix,
		     size_t *len);
/*
 * Look through 'rdataset' for AAAA pairs which define encoded DNS64 prefixes.
 * 'len' should be set to the number of entries in 'prefix' and returns
 * the number of prefixes discovered.  This may be bigger than those that
 * can fit in 'prefix'.
 *
     * though the result would   \
	      * fail validation.          \
	      */

/*
 * dns_dns64_aaaaok() and dns_dns64_aaaafroma() flags.
 */
#define DNS_DNS64_RECURSIVE 0x01 /* Recursive query. */
#define DNS_DNS64_DNSSEC    0x02 /* DNSSEC sensitive query. */

isc_result_t
dns_dns64_create(isc_mem_t *mctx, const isc_netaddr_t *prefix,
		 unsigned int prefixlen, const isc_netaddr_t *suffix,
		 dns_acl_t *client, dns_acl_t *mapped, dns_acl_t *excluded,
		 unsigned int flags, dns_dns64_t **dns64);
/*
 * Create a dns64 record which is used to identify the set of clients
 * it applies to and how to perform the DNS64 synthesis.
 *
 * 'prefix' and 'prefixlen' defined the leading bits of the AAAA records
 * to be synthesised.  'suffix' defines the bits after the A records bits.
 * If suffix is NULL zeros will be used for these bits.  'client' defines
 * for which clients this record applies.  If 'client' is NULL then all
 * clients apply.  'mapped' defines which A records are candidated for
 * mapping.  If 'mappe by dns_name_totext().  This does not
 * include space for a terminating NULL.
 *
 * This definition is conservative - the actual maximum
 * is 1004, derived as follows:
 *
 *   A backslash-decimal escaped character takes 4 bytes.
 *   A wire-encoded name can be up to 255 bytes and each
 *   label is one length byte + at most 63 bytes of data.
 *   Maximizing the label lengths gives us a name of
 *   three 63-octet labels, one 61-octet label, and the
 *   root label:
 *
 *      1 + 63 + 1 + 63 + 1 + 63 + 1 + 61 + 1 = 255
 *
 *   When printed, this is (3 * 63 + 61) * 4
 *   bytes for the escaped label data + 4 bytes for the
 *   dot terminating each label = 1004 bytes total.
 */

isc_result_t
dns_name_tofilenametext(const dns_name_t *name, bool omit_final_dot,
			isc_buffer_t *target);
/*%<
 * Convert 'name' into an alternate text format appropriate for filenames,
 * storing the result in 'target'.  The name data is downcased, guaranteeing
 * that the filename does not depend on the case of the converted name.of labels at the end of name.
 *
 * \li	It makes no sense for one of the names to be relative and the
 *	other absolute.  If both names are relative, then to be meaningfully
 *	compared the caller must ensure that they are both relative to the
 *	same domain.
 *
 * Requires:
 * \li	'name' is a valid name
 *
 * \li	dns_name_countlabels(name) > 0
 *
 * \li	'wname' is a valid name
 *
 * \li	dns_name_countlabels(wname) > 0
 *
 * \li	dns_name_iswildcard(wname) is true
 *
 * \li	Either name is absolute and wname is absolute, or neither is.
 *
 * Returns:
 * \li	TRUE		'name' matches the wildcard specified in 'wname'
 * \li	FALSE		'name' does not match the wildcard specified in 'wname'
 */

/***
 *** Labels
 ***/

static inline unsigned int
dns_name_countlabels(const dns_name_t *name) {
	REQUIRE(DNS_NAME_VALID(name));
	REQUIRE(name->labels <= DNS_NAME_MAXLABELS);

	return name->labels;
}
/*%<
 * How many labels does 'name' have?
 *
 * Notes:
 * \li	In this case, as in other places, a 'label' is an ordinary label.
 *
server know
 * the representation would be perilous, and we certainly don't want each
 * user of names to be manipulating such a low-level structure.  This is
 * where the Names and Labels module comes in. The module allows name
 * handles to be created and attached to uncompressed wire format
 * regions. All name operations and conversions are done through these
 * handles.
 *
 * MP:
 *\li	Clients of this module must impose any required synchronization.
 *
 * Reliability:
 *\li	This module deals with low-level byte streams.  Errors in any of
 *	the functions are likely to crash the server or corrupt memory.
 *
 * Resources:
 *\li	None.
 *
 * Security:
 *
 *\li	*** WARNING ***
 *
 *\li	dns_name_fromwire() deals with raw network data.  An error in
 *	this routine could result in the failure or hijacking of the server.
 *
 * Standards:
 *\li	RFC1035
 *\li	Draft EDNS0 (0)
 *
 */

/***
 *** Imports
 ***/

#include <inttypes.h>
#include <stdbool.h>
#include <stdio.h>

#include <isc/buffer.h>
#include <isc/hashmap.rawmessage(dns_message_t *msg);
/*%<
 * Retrieve the raw message in compressed wire format.  The message must
 * have been successfully parsed for it to have been saved.
 *
 * Requires:
 *\li	msg is a valid parsed message.
 *
 * Returns:
 *\li	NULL	if there is no saved message.
 *	a pointer to a region which refers the dns message.
 */

void
dns_message_setsortorder(dns_message_t *msg, dns_rdatasetorderfunc_t order,
			 dns_aclenv_t *env, dns_acl_t *acl,
			 const dns_aclelement_t *element);
/*%<
 * Define the order in which RR sets get rendered by
 * dns_message_rendersection() to be the ascending order
 * defined by the integer value returned by 'order' when
 * given each RR and a ns_sortlist_arg_t constructed from 'env',
 * 'acl', and 'element' as arguments.
 *
 * If 'order' is NULL, a default order is used.
 *
 * Requires:
 *\li	msg be a valid message.
 *\li	If 'env' is NULL, 'order' must be NULL.
 *\li	If 'env' is not NULL, 'order' must not be NULL and at least one of
 *	'acl' and 'element' must also notion' be a named section.
 */

/*
 * LOANOUT FUNCTIONS
 *
 * Each of these functions loan a particular type of data to the caller.
 * The storage for these will vanish when the message is destroyed or
 * reset, and must NOT be used after these operations.
 */

void
dns_message_gettempname(dns_message_t *msg, dns_name_t **item);
/*%<
 * Return a name that can be used for any temporary purpose, including
 * inserting into the message's linked lists.  The name must be returned
 * to the message code using dns_message_puttempname() or inserted into
 * one of the message's sections before the message is destroyed.
 *
 * The name will be associated with a dns_fixedname object, and will
 * be initialized.
 *
 * Requires:
 *\li	msg be a valid message
 *
 *\li	item != NULL && *item == NULL
 */

void
dns_message_gettemprdata(dns_message_t *msg, dns_rdata_t **item);
/*%<
 * Return a rdata that can be used for any temporary purpose, including
 * inserting into the message's linked lists.  The rdata will be freed
 * when tote that more data can be in the
 * 'msg' structure.  Destroying the structure will free this, or in a multi-
 * part EDNS1 message this data can be rendered to another buffer later.
 *
 * Requires:
 *
 *\li	'msg' be a valid message.
 *
 *\li	dns_message_renderbegin() was called.
 *
 * Returns:
 *\li	#ISC_R_SUCCESS		-- all is well.
 */

void
dns_message_renderreset(dns_message_t *msg);
/*%<
 * Reset the message so that it may be rendered again.
 *
 * Notes:
 *
 *\li	If dns_message_renderbegin() has been called, dns_message_renderend()
 *	must be called before calling this function.
 *
 * Requires:
 *
 *\li	'msg' be a valid message with rendering intent.
 */

isc_result_t
dns_message_firstname(dns_message_t *msg, dns_section_t section);
/*%<
 * Set internal per-section name pointer to the beginning of the section.
 *
 * The functions dns_message_firstname() and dns_message_nextname() may
 * be used for iterating over the owner names in a section.
 *
 * Requires:
 *
 *\li	'msg' be valid.
 *
 *\li	'section' be aon_t saved;

	/*
	 * Time to be used when fuzzing.
	 */
	isc_stdtime_t fuzztime;

	dns_rdatasetorderfunc_t order;
	dns_sortlist_arg_t	order_arg;

	dns_indent_t indent;

	dns_minttl_t minttl[DNS_SECTION_MAX];
};

struct dns_ednsopt {
	uint16_t code;
	uint16_t length;
	uint8_t *value;
};

typedef void (*dns_message_cb_t)(void *arg, isc_result_t result);

/***
 *** Functions
 ***/

ISC_LANG_BEGINDECLS

void
dns_message_create(isc_mem_t *mctx, isc_mempool_t *namepool,
		   isc_mempool_t *rdspool, dns_message_intent_t intent,
		   dns_message_t **msgp);
/*%<
 * Create msg structure.
 *
 * This function will allocate some internal blocks of memory that are
 * expected to be needed for parsing or rendering nearly any type of message.
 *
 * Requires:
 *\li	'mctx' be a valid memory context.
 *
 *\li	'msgp' be non-null and '*msg' be NULL.
 *
 *\li	'namepool' and 'rdspool' must be either both NULL or both valid
 *	isc_mempool_t
 *
 *\li	'intent' must be one of DNS_MESSAGE_INTENTPARSE or
 *	#DNS_MESSAGE_INTENTRENDER.
 *
nts to cfg_listelt_t obtained from cfg_list_first() or
 *	cfg_list_next().
 *
 * Returns:
 * \li     A non-NULL pointer to a configuration object.
 */

void
cfg_print(const cfg_obj_t *obj,
	  void (*f)(void *closure, const char *text, int textlen),
	  void *closure);
void
cfg_printx(const cfg_obj_t *obj, unsigned int flags,
	   void (*f)(void *closure, const char *text, int textlen),
	   void *closure);

#define CFG_PRINTER_XKEY    0x1 /* '?' out shared keys. */
#define CFG_PRINTER_ONELINE 0x2 /* print config as a single line */
#define CFG_PRINTER_ACTIVEONLY                 \
	0x4 /* print only active configuration \
	     * options, omitting ancient,      \
	     * obsolete, nonimplemented,       \
	     * and test-only options. */

/*%<
 * Print the configuration object 'obj' by repeatedly calling the
 * function 'f', passing 'closure' and a region of text starting
 * at 'text' and comprising 'textlen' characters.
 *
 * If CFG_PRINTER_XKEY the contents of shared keys will be obscured
 * by replacing them w a valid cfg_parser_t.
 */

void
cfg_parser_reset(cfg_parser_t *pctx);
/*%<
 * Reset an existing parser so it can be re-used for a new file or
 * buffer.
 */

void
cfg_parser_destroy(cfg_parser_t **pctxp);
/*%<
 * Remove a reference to a configuration parser; destroy it if there are no
 * more references.
 */

bool
cfg_obj_isvoid(const cfg_obj_t *obj);
/*%<
 * Return true iff 'obj' is of void type (e.g., an optional
 * value not specified).
 */

bool
cfg_obj_ismap(const cfg_obj_t *obj);
/*%<
 * Return true iff 'obj' is of a map type.
 */

bool
cfg_obj_isfixedpoint(const cfg_obj_t *obj);
/*%<
 * Return true iff 'obj' is of a fixedpoint type.
 */

bool
cfg_obj_ispercentage(const cfg_obj_t *obj);
/*%<
 * Return true iff 'obj' is of a percentage type.
 */

isc_result_t
cfg_map_get(const cfg_obj_t *mapobj, const char *name, const cfg_obj_t **obj);
/*%<
 * Extract an element from a configuration object, which
 * must be of a map type.
 *
 * Requires:
 * \li     'mapobj' points to a valid configuration object of a m_t digest, void *arg);
/*%<
 * Send 'rdata' in DNSSEC canonical form to 'digest'.
 *
 * Note:
 *\li	'digest' may be called more than once by dns_rdata_digest().  The
 *	concatenation of all the regions, in the order they were given
 *	to 'digest', will be the DNSSEC canonical form of 'rdata'.
 *
 * Requires:
 *
 *\li	'rdata' is a valid, non-empty rdata.
 *
 *\li	'digest' is a valid dns_digestfunc_t.
 *
 * Ensures:
 *
 *\li	If successful, then all of the rdata's data has been sent, in
 *	DNSSEC canonical form, to 'digest'.
 *
 *\li	If digest() returns something other than ISC_R_SUCCESS, that result
 *	will be returned as the result of dns_rdata_digest().
 *
 * Returns:
 *
 *\li	ISC_R_SUCCESS
 *
 *\li	Many other results are possible if not successful.
 */

bool
dns_rdatatype_questiononly(dns_rdatatype_t type);
/*%<
 * Return true iff rdata of type 'type' can only appear in the question
 * section of a properly formatted message.
 *
 * Requires:
 * \li	'type' is a valid rdata type.
 *
 */

bool
dns_rdatatype_notd decompression context.
 *
 * Ensures,
 *	if result is success:
 *	\li 	If 'rdata' is not NULL, it is attached to the target.
 *	\li	The conditions dns_name_fromwire() ensures for names hold
 *		for all names in the rdata.
 *	\li	The current location in source is advanced, and the used space
 *		in target is updated.
 *
 * Result:
 *\li	Success
 *\li	Any non-success status from dns_name_fromwire()
 *\li	Various 'Bad Form' class failures depending on class and type
 *\li	Bad Form: Input too short
 *\li	Resource Limit: Not enough space
 */

isc_result_t
dns_rdata_towire(dns_rdata_t *rdata, dns_compress_t *cctx,
		 isc_buffer_t *target);
/*%<
 * Convert 'rdata' into wire format, compressing it as specified by the
 * compression context 'cctx', and storing the result in 'target'.
 *
 * Notes:
 *\li	If compression is permitted, then the cctx table may be updated.
 *
 * Requires:
 *\li	'rdata' is a valid, non-empty rdata
 *
 *\li	target is a valid buffer
 *
 *\li	Any offsets in the compression table are valid for t *cds, dns_rdataset_t *cdnskey,
		      isc_stdtime_t now, dns_kasp_digestlist_t *digests,
		      bool gencdnskey, dns_ttl_t hint_ttl, dns_diff_t *diff,
		      isc_mem_t *mctx);
/*%<
 * Update the CDS and CDNSKEY RRsets, adding and removing keys as needed.
 *
 * For each key in 'keys', check if corresponding CDS and CDNSKEY records
 * need to be published. If needed and 'gencdnskey' is true, there will be one
 * CDNSKEY record added to the 'cdnskey' RRset. Also one CDS record will be
 * added to the 'cds' RRset for each digest type in 'digests'.
 *
 * For each key in 'rmkeys', remove any associated CDS and CDNSKEY records from
 * the RRsets 'cds' and 'cdnskey'.
 *
 * 'hint_ttl' is the TTL to use for the CDS and CDNSKEY RRsets if there is no
 * existing RRset.
 *
 * Any changes made also cause a dns_difftuple to be added to 'diff'.
 *
 * Requires:
 *\li	'keys' is not NULL.
 *\li	'rmkeys' is not NULL.
 *\li	'digests' is not NULL.
 *
 * Returns:
 *\li   ISC_R_SUCCESS
 *\li   Other values indicate error
 */

iard expansion.  dns_dnssec_verify2() only.
 *			'wild' contains the name of the wildcard if non-NULL.
 *\li		#DNS_R_SIGINVALID - the signature fails to verify
 *\li		#DNS_R_SIGEXPIRED - the signature has expired
 *\li		#DNS_R_SIGFUTURE - the signature's validity period has not begun
 *\li		#DNS_R_KEYUNAUTHORIZED - the key cannot sign this data (either
 *			it is not a zone key or its flags prevent
 *			authentication)
 *\li		DST_R_*
 */

bool
dns_dnssec_keyactive(dst_key_t *key, isc_stdtime_t now);
/*%<
 *
 * 	Returns true if 'key' is active as of the time specified
 * 	in 'now' (i.e., if the activation date has passed, inactivation or
 * 	deletion date has not yet been reached, and the key is not revoked
 * 	-- or if it is a legacy key without metadata). Otherwise returns
 * 	false.
 *
 *	Requires:
 *\li		'key' is a valid key
 */

isc_result_t
dns_dnssec_signmessage(dns_message_t *msg, dst_key_t *key);
/*%<
 *	Signs a message with a SIG(0) record.  This is implicitly called by
 *	dns_message_renderend() if m* This can be used as an iterator, by initializing `key` to zero
 * and incrementing by one or using `isc_histo_next()` until
 * `isc_histo_get()` returns ISC_R_RANGE. The number of iterations is
 * less than `64 << sigbits`. (64 for the maximum number of chunks,
 * multiplied by the size of each chunk.)
 *
 * It is also a counterpart to `isc_histo_put()`.
 *
 * If `minp` is non-NULL it is set to the minimum inclusive value
 * that maps to this bucket.
 *
 * If `maxp` is non-NULL it is set to the maximum inclusive value
 * that maps to this bucket.
 *
 * If `countp` is non-NULL it is set to the bucket's counter,
 * which can be zero.
 *
 * Requires:
 *\li	`hg` is a pointer to a valid histogram
 *
 * Returns:
 *\li	ISC_R_SUCCESS, if `key` is valid
 *\li	ISC_R_RANGE, otherwise
 */

void
isc_histo_next(const isc_histo_t *hg, uint *keyp);
/*%<
 * Skip to the next key, omitting chunks of unallocated buckets.
 *
 * This function does not skip buckets that have been allocated but
 * are zero. A chunk contains `1 << 
 */

#pragma once

/*! \file dns/rcode.h */

#include <isc/lang.h>

#include <dns/types.h>

ISC_LANG_BEGINDECLS

isc_result_t
dns_rcode_fromtext(dns_rcode_t *rcodep, isc_textregion_t *source);
/*%<
 * Convert the text 'source' refers to into a DNS error value.
 *
 * Requires:
 *\li	'rcodep' is a valid pointer.
 *
 *\li	'source' is a valid text region.
 *
 * Returns:
 *\li	#ISC_R_SUCCESS			on success
 *\li	#DNS_R_UNKNOWN			type is unknown
 */

isc_result_t
dns_rcode_totext(dns_rcode_t rcode, isc_buffer_t *target);
/*%<
 * Put a textual representation of error 'rcode' into 'target'.
 *
 * Requires:
 *\li	'rcode' is a valid rcode.
 *
 *\li	'target' is a valid text buffer.
 *
 * Ensures:
 *\li	If the result is success:
 *		The used space in 'target' is updated.
 *
 * Returns:
 *\li	#ISC_R_SUCCESS			on success
 *\li	#ISC_R_NOSPACE			target buffer is too small
 */

isc_result_t
dns_tsigrcode_fromtext(dns_rcode_t *rcodep, isc_textregion_t *source);
/*%<
 * Convert the text 'source' refers to into a TSIG/TKEY error ED_TYPE(elt, link, type) \
	((type *)((elt)->link.prev) != ISC_LINK_TOMBSTONE(type))
#define ISC_LINK_LINKED(elt, link) ISC_LINK_LINKED_TYPE(elt, link, void)

#define ISC_LIST_HEAD(list)  ((list).head)
#define ISC_LIST_TAIL(list)  ((list).tail)
#define ISC_LIST_EMPTY(list) ((list).head == NULL)

#define __ISC_LIST_PREPENDUNSAFE(list, elt, link)       \
	do {                                            \
		if ((list).head != NULL) {              \
			(list).head->link.prev = (elt); \
		} else {                                \
			(list).tail = (elt);            \
		}                                       \
		(elt)->link.prev = NULL;                \
		(elt)->link.next = (list).head;         \
		(list).head = (elt);                    \
	} while (0)

#define ISC_LIST_PREPEND(list, elt, link)                     \
	do {                                                  \
		ISC_LINK_INSIST(!ISC_LINK_LINKED(elt, link)); \
		__ISC_LIST_PREPENDUNSAFE(list, elt, link);    \
	} while (0)

#define ISC_LIST_INITANDPREPENDe number from which the parameters were taken, so that logged
 * error messages, if any, will display the correct locations.
 *
 * Returns:
 *\li	#ISC_R_SUCCESS
 *\li	#ISC_R_NOMEMORY
 *\li	Other errors are possible
 */

void
dns_dyndb_cleanup(bool exiting);
/*%
 * Shut down and destroy all running dyndb modules.
 *
 * 'exiting' indicates whether the server is shutting down,
 * as opposed to merely being reconfigured.
 */

isc_result_t
dns_dyndb_createctx(isc_mem_t *mctx, const void *hashinit, isc_log_t *lctx,
		    dns_view_t *view, dns_zonemgr_t *zmgr,
		    isc_loopmgr_t *loopmgr, dns_dyndbctx_t **dctxp);
/*%
 * Create a dyndb initialization context structure, with
 * pointers to structures in the server that the dyndb module will
 * need to access (view, zone manager, memory context, hash initializer,
 * etc). This structure is expected to last only until all dyndb
 * modules have been loaded and initialized; after that it will be
 * destroyed with dns_dyndb_destroyctx().
 *
/*! \file
 * \brief
 * The keytable module provides services for storing and retrieving DNSSEC
 * trusted keys, as well as the ability to find the deepest matching key
 * for a given domain name.
 *
 * MP:
 *\li	The module ensures appropriate synchronization of data structures it
 *	creates and manipulates.
 *
 * Resources:
 *\li	TBS
 *
 * Security:
 *\li	No anticipated impact.
 */

#include <stdbool.h>

#include <isc/lang.h>
#include <isc/magic.h>
#include <isc/refcount.h>
#include <isc/rwlock.h>
#include <isc/stdtime.h>

#include <dns/rdatastruct.h>
#include <dns/types.h>

#include <dst/dst.h>

ISC_LANG_BEGINDECLS

typedef void (*dns_keytable_callback_t)(const dns_name_t *name, void *fn_arg);

void
dns_keytable_create(dns_view_t *view, dns_keytable_t **keytablep);
/*%<
 * Create a keytable.
 *
 * Requires:
 *
 *\li	'view' is a valid memory context.
 *\li	keytablep != NULL && *keytablep == NULL
 */

isc_result_t
dns_keytable_add(dns_keytable_t *keytable, bool managed, bool initial,
		 dns_name_t *name, dns_rine uint64_t
isc_hash64(const void *data, const size_t length, const bool case_sensitive) {
	isc_hash64_t state;
	isc_hash64_init(&state);
	isc_hash64_hash(&state, data, length, case_sensitive);
	return isc_hash64_finalize(&state);
}
/*!<
 * \brief Calculate a hash over data.
 *
 * This hash function is useful for hashtables. The hash function is
 * opaque and not important to the caller. The returned hash values are
 * non-deterministic and will have different mapping every time a
 * process using this library is run, but will have uniform
 * distribution.
 *
 * isc_hash_32/64() calculates the hash from start to end over the
 * input data.
 *
 * 'data' is the data to be hashed.
 *
 * 'length' is the size of the data to be hashed.
 *
 * 'case_sensitive' specifies whether the hash key should be treated as
 * case_sensitive values.  It should typically be false if the hash key
 * is a DNS name.
 *
 * Returns:
 * \li 32 or 64-bit hash value
 */

/*!
 * \brief Return a hash value of a specified number of bits
 *
/*
 * Any updates to this structure should also be applied in
 * https://gitlab.isc.org/isc-projects/dlz-modules/-/raw/main/modules/include/dlz_minimal.h
 */
struct isc_sockaddr {
	union {
		struct sockaddr	    sa;
		struct sockaddr_in  sin;
		struct sockaddr_in6 sin6;
	} type;
	unsigned int length; /* XXXRTH beginning? */
	ISC_LINK(struct isc_sockaddr) link;
};

#define ISC_SOCKADDR_CMPADDR            \
	0x0001 /*%< compare the address \
		*   sin_addr/sin6_addr */
#define ISC_SOCKADDR_CMPPORT         \
	0x0002 /*%< compare the port \
		*   sin_port/sin6_port */
#define ISC_SOCKADDR_CMPSCOPE         \
	0x0004 /*%< compare the scope \
		*   sin6_scope */
#define ISC_SOCKADDR_CMPSCOPEZERO         \
	0x0008 /*%< when comparing scopes \
		*   zero scopes always match */

ISC_LANG_BEGINDECLS

bool
isc_sockaddr_compare(const isc_sockaddr_t *a, const isc_sockaddr_t *b,
		     unsigned int flags);
/*%<
 * Compare the elements of the two address ('a' and 'b') as specified
 * by 'flags' and report if they are equal orsigkey_t **key);
/*%<
 *	Creates a tsig key structure and stores it in *keyp.
 *	The key's validity period is specified by (inception, expire),
 *	and will not expire if inception == expire.
 *
 *	If generated is true (meaning the key was generated
 *	via TKEY negotation), the creating identity (if any), should
 *	be specified in the creator parameter.
 *
 *	If restored is true, this indicates the key was restored from
 *	a dump file created by dns_tsigkeyring_dumpanddetach(). This is
 *	used only for logging purposes and doesn't affect the key any
 *	other way.
 *
 *	Specifying an unimplemented algorithm will cause failure only if
 *	dstkey != NULL; this allows a transient key with an invalid
 *	algorithm to exist long enough to generate a BADKEY response.
 *
 *	If dns_tsigkey_createfromkey() is successful, a new reference to
 *	'dstkey' will have been made.
 *
 *	dns_tsigkey_create() is a simplified interface that omits
 *	dstkey, generated, restored, inception, and expired (defaulting
 *	to NULL, false, fao be a valid sockaddr.
 *
 *\li	localaddr to be NULL or a valid sockaddr.
 *
 *\li	transport is NULL or a valid transport.
 *
 *\li	dispp to be non NULL and *dispp to be NULL
 *
 * Returns:
 *\li	ISC_R_SUCCESS	-- success.
 *
 *\li	Anything else	-- failure.
 */

typedef void (*dispatch_cb_t)(isc_result_t eresult, isc_region_t *region,
			      void *cbarg);

isc_result_t
dns_dispatch_add(dns_dispatch_t *disp, isc_loop_t *loop,
		 dns_dispatchopt_t options, unsigned int timeout,
		 const isc_sockaddr_t *dest, dns_transport_t *transport,
		 isc_tlsctx_cache_t *tlsctx_cache, dispatch_cb_t connected,
		 dispatch_cb_t sent, dispatch_cb_t response, void *arg,
		 dns_messageid_t *idp, dns_dispentry_t **resp);
/*%<
 * Add a response entry for this dispatch.
 *
 * "*idp" is filled in with the assigned message ID, and *resp is filled in
 * with the dispatch entry object.
 *
 * The 'connected' and 'sent' callbacks are run to inform the caller when
 * the connect and send functions are complete. The 'timedout' callback
 *r is a valid dispatchmgr
 * Returns:
 *\li	A pointer to the current blackhole list, or NULL.
 */

isc_result_t
dns_dispatchmgr_setavailports(dns_dispatchmgr_t *mgr, isc_portset_t *v4portset,
			      isc_portset_t *v6portset);
/*%<
 * Sets a list of UDP ports that can be used for outgoing UDP messages.
 *
 * Requires:
 *\li	mgr is a valid dispatchmgr
 *\li	v4portset is NULL or a valid port set
 *\li	v6portset is NULL or a valid port set
 */

void
dns_dispatchmgr_setstats(dns_dispatchmgr_t *mgr, isc_stats_t *stats);
/*%<
 * Sets statistics counter for the dispatchmgr.  This function is expected to
 * be called only on zone creation (when necessary).
 * Once installed, it cannot be removed or replaced.  Also, there is no
 * interface to get the installed stats from the zone; the caller must keep the
 * stats to reference (e.g. dump) it later.
 *
 * Requires:
 *\li	mgr is a valid dispatchmgr with no managed dispatch.
 *\li	stats is a valid statistics supporting resolver statistics counters
 *	(see dns/stats.h).
brief Provides a simple memory-based symbol table.
 *
 * Keys are C strings, and key comparisons are case-insensitive.  A type may
 * be specified when looking up, defining, or undefining.  A type value of
 * 0 means "match any type"; any other value will only match the given
 * type.
 *
 * It's possible that a client will attempt to define a <key, type, value>
 * tuple when a tuple with the given key and type already exists in the table.
 * What to do in this case is specified by the client.  Possible policies are:
 *
 *\li	#isc_symexists_reject	Disallow the define, returning #ISC_R_EXISTS
 *\li	#isc_symexists_replace	Replace the old value with the new.  The
 *				undefine action (if provided) will be called
 *				with the old <key, type, value> tuple.
 *\li	#isc_symexists_add	Add the new tuple, leaving the old tuple in
 *				the table.  Subsequent lookups will retrieve
 *				the most-recently-defined tuple.
 *
 * A lookup of a key using type 0 will return the most-recently defined
 * symbol with that key.                                 \
		uint_fast32_t __v;                         \
		__v = atomic_fetch_add_release(target, 1); \
		INSIST(__v > 0 && __v < UINT32_MAX);       \
		__v;                                       \
	})

/** \def isc_refcount_decrement(ref)
 *  \brief decreases reference counter by 1.
 *  \param[in] ref pointer to reference counter.
 *  \returns previous value of reference counter.
 */
#define isc_refcount_decrement(target)                     \
	({                                                 \
		uint_fast32_t __v;                         \
		__v = atomic_fetch_sub_acq_rel(target, 1); \
		INSIST(__v > 0);                           \
		__v;                                       \
	})

#define isc_refcount_decrementz(target)                               \
	do {                                                          \
		uint_fast32_t _refs = isc_refcount_decrement(target); \
		ISC_INSIST(_refs == 1);                               \
	} while (0)

#define isc_refcount_decrement1(targetnes_t *catzs, const dns_name_t *name);
/*%<
 * Allocate a new catz zone on catzs mctx
 *
 * Requires:
 * \li	'catzs' is a valid dns_catz_zones_t.
 * \li	'catzp' is not NULL and '*catzp' is NULL.
 * \li	'name' is a valid dns_name_t.
 *
 */

dns_name_t *
dns_catz_zone_getname(dns_catz_zone_t *catz);
/*%<
 * Get catalog zone name
 *
 * Requires:
 * \li	'catz' is a valid dns_catz_zone_t.
 */

dns_catz_options_t *
dns_catz_zone_getdefoptions(dns_catz_zone_t *catz);
/*%<
 * Get default member zone options for catalog zone 'catz'
 *
 * Requires:
 * \li	'catz' is a valid dns_catz_zone_t.
 */

void
dns_catz_zone_resetdefoptions(dns_catz_zone_t *catz);
/*%<
 * Reset the default member zone options for catalog zone 'catz' to
 * the default values.
 *
 * Requires:
 * \li	'catz' is a valid dns_catz_zone_t.
 */

isc_result_t
dns_catz_generate_masterfilename(dns_catz_zone_t *catz, dns_catz_entry_t *entry,
				 isc_buffer_t **buffer);
/*%<
 * Generate master file name and put it into *buffer (might be reallocated).
 * The geefine DNS_CATZ_DEBUG_QUIET  (DNS_CATZ_DEBUG_LEVEL3 + 1)

/*
 * Catalog Zones functions and structures.
 */

/*
 * Options for a member zone in a catalog
 */
struct dns_catz_entry_options {
	/*
	 * Options that can be overridden in catalog zone
	 */
	/* default-masters/default-primaries definition */
	dns_ipkeylist_t masters;

	/* both as text in config format, NULL if none */
	isc_buffer_t *allow_query;
	isc_buffer_t *allow_transfer;

	/*
	 * Options that are only set in named.conf
	 */
	/* zone-directory definition */
	char *zonedir;

	/* zone should not be stored on disk (no 'file' statement in def */
	bool in_memory;
	/*
	 * Minimal interval between catalog zone updates, if a new version
	 * of catalog zone is received before this time the update will be
	 * postponed. This is a global option for the whole catalog zone.
	 */
	uint32_t min_update_interval;
};

void
dns_catz_options_init(dns_catz_options_t *options);
/*%<
 * Initialize 'options' to NULL values.
 *
 * Requires:
 * \li	'options' to be non NULL		int _ret = pthread_barrier_destroy(bp);                \
		PTHREADS_RUNTIME_CHECK(pthread_barrier_destroy, _ret); \
	}

#else

#include <uv.h>

#if ISC_TRACK_PTHREADS_OBJECTS
typedef uv_barrier_t *isc_barrier_t;
#else
typedef uv_barrier_t isc_barrier_t;
#endif

#define isc__barrier_init(bp, count)                     \
	{                                                \
		int _ret = uv_barrier_init(bp, count);   \
		UV_RUNTIME_CHECK(uv_barrier_init, _ret); \
	}

#define isc__barrier_wait(bp) uv_barrier_wait(bp)

#define isc__barrier_destroy(bp) uv_barrier_destroy(bp)

#endif

#if ISC_TRACK_PTHREADS_OBJECTS

#define isc_barrier_init(bp, count)            \
	{                                      \
		*bp = malloc(sizeof(**bp));    \
		isc__barrier_init(*bp, count); \
	}
#define isc_barrier_wait(bp) isc__barrier_wait(*bp)
#define isc_barrier_destroy(bp)            \
	{                                  \
		isc__barrier_destroy(*bp); \
		free(*bp);                 \
	}

#else /* ISC_TRACK_PTHREADS_OBJECTS */

#df memory
 * \li	#ISC_R_EXISTS	A database implementation with the same name exists
 *
 * Ensures:
 *
 * \li	*dbimp points to an opaque structure which must be passed to
 *	dns_db_unregister().
 */

void
dns_db_unregister(dns_dbimplementation_t **dbimp);
/*%<
 * Remove a database implementation from the list of supported
 * implementations.  No databases of this type can be active when this
 * is called.
 *
 * Requires:
 * \li 	dbimp != NULL && *dbimp == NULL
 *
 * Ensures:
 *
 * \li	Any memory allocated in *dbimp will be freed.
 */

#define dns_db_getoriginnode(db, nodep) \
	dns__db_getoriginnode(db, nodep DNS__DB_FILELINE)
isc_result_t
dns__db_getoriginnode(dns_db_t *db, dns_dbnode_t **nodep DNS__DB_FLARG);
/*%<
 * Get the origin DB node corresponding to the DB's zone.  This function
 * should typically succeed unless the underlying DB implementation doesn't
 * support the feature.
 *
 * Requires:
 *
 * \li	'db' is a valid zone database.
 * \li	'nodep' != NULL && '*nodep' == NULL
 *
 * Ensures:
 * \li	On succn look for a
 *	NSEC record that potentially covers 'name' if a answer cannot
 *	be found.  Note the returned NSEC needs to be checked to ensure
 *	that it is correct.  This only affects answers returned from the
 *	cache.
 *
 * \li	If the #DNS_DBFIND_FORCENSEC3 option is set, then we are looking
 *	in the NSEC3 tree and not the main tree.  Without this option being
 *	set NSEC3 records will not be found.
 *
 * \li	To respond to a query for SIG records, the caller should create a
 *	rdataset iterator and extract the signatures from each rdataset.
 *
 * \li	Making queries of type ANY with #DNS_DBFIND_GLUEOK is not recommended,
 *	because the burden of determining whether a given rdataset is valid
 *	glue or not falls upon the caller.
 *
 * \li	The 'now' field is ignored if 'db' is a zone database.  If 'db' is a
 *	cache database, an rdataset will not be found unless it expires after
 *	'now'.  Any ANY query will not match unless at least one rdataset at
 *	the node expires after 'now'.  If 'now' is zero, then  current version.
 *
 * Returns:
 *
 * \li	#ISC_R_SUCCESS
 * \li	#ISC_R_NOMEMORY
 *
 * \li	Other results are possible, depending upon the database
 *	implementation used.
 */

void
dns_db_attachversion(dns_db_t *db, dns_dbversion_t *source,
		     dns_dbversion_t **targetp);
/*%<
 * Attach '*targetp' to 'source'.
 *
 * Requires:
 *
 * \li	'db' is a valid database with zone semantics.
 *
 * \li	source is a valid open version
 *
 * \li	targetp != NULL && *targetp == NULL
 *
 * Ensures:
 *
 * \li	'*targetp' is attached to source.
 */

#define dns_db_closeversion(db, versionp, commit) \
	dns__db_closeversion(db, versionp, commit DNS__DB_FILELINE)
void
dns__db_closeversion(dns_db_t *db, dns_dbversion_t **versionp,
		     bool commit DNS__DB_FLARG);
/*%<
 * Close version '*versionp'.
 *
 * Note: if '*versionp' is a read-write version and 'commit' is true,
 * then all changes made in the version will take effect, otherwise they
 * will be rolled back.  The value of 'commit' is ignored for read-only
 * versions.
 *
 set_t *rdataset,
				       isc_stdtime_t resign);
	isc_result_t (*getsigningtime)(dns_db_t *db, isc_stdtime_t *resign,
				       dns_name_t     *name,
				       dns_typepair_t *typepair);
	dns_stats_t *(*getrrsetstats)(dns_db_t *db);
	isc_result_t (*findnodeext)(dns_db_t *db, const dns_name_t *name,
				    bool		     create,
				    dns_clientinfomethods_t *methods,
				    dns_clientinfo_t	    *clientinfo,
				    dns_dbnode_t **nodep     DNS__DB_FLARG);
	isc_result_t (*findext)(dns_db_t *db, const dns_name_t *name,
				dns_dbversion_t *version, dns_rdatatype_t type,
				unsigned int options, isc_stdtime_t now,
				dns_dbnode_t **nodep, dns_name_t *foundname,
				dns_clientinfomethods_t	   *methods,
				dns_clientinfo_t	   *clientinfo,
				dns_rdataset_t		   *rdataset,
				dns_rdataset_t *sigrdataset DNS__DB_FLARG);
	isc_result_t (*setcachestats)(dns_db_t *db, isc_stats_t *stats);
	size_t (*hashsize)(dns_db_t *db);
	isc_result_t (*getsize)(dns_db_t *db, dns_dbversion_t *version,
				uint64_t *records, uid
 * past their normal TTL.  Default value for the library is 0, disabling
 * the use of stale data.
 *
 * Requires:
 *\li	'cache' to be valid.
 */

dns_ttl_t
dns_cache_getservestalettl(dns_cache_t *cache);
/*%<
 * Gets the maximum length of time that cached answers may be kept past
 * normal expiry.
 *
 * Requires:
 *\li	'cache' to be valid.
 */

void
dns_cache_setservestalerefresh(dns_cache_t *cache, dns_ttl_t interval);
/*%<
 * Sets the length of time to wait before attempting to refresh a rrset
 * if a previous attempt in doing so has failed.
 * During this time window if stale rrset are available in cache they
 * will be directly returned to client.
 *
 * Requires:
 *\li	'cache' to be valid.
 */

dns_ttl_t
dns_cache_getservestalerefresh(dns_cache_t *cache);
/*%<
 * Gets the 'stale-refresh-time' value, set by a previous call to
 * 'dns_cache_setservestalerefresh'.
 *
 * Requires:
 *\li	'cache' to be valid.
 */

isc_result_t
dns_cache_flush(dns_cache_t *cache);
/*%<
 * Flushes all data from the cache.
 *
 ll records in the iteration (excluding headers). This
 * is meant to be a rough approximation of the size of an incremental
 * zone transfer, though it does not account for DNS message overhead
 * or name compression.)
 *
 * Returns:
 *\li	ISC_R_SUCCESS
 *\li	ISC_R_RANGE	begin_serial is outside the addressable range.
 *\li	ISC_R_NOTFOUND	begin_serial is within the range of addressable
 *			serial numbers covered by the journal, but
 *			this particular serial number does not exist.
 */

/*@{*/
isc_result_t
dns_journal_first_rr(dns_journal_t *j);
isc_result_t
dns_journal_next_rr(dns_journal_t *j);
/*%<
 * Position the iterator at the first/next RR in a journal
 * transaction sequence established using dns_journal_iter_init().
 *
 * Requires:
 *    \li  dns_journal_iter_init() has been called.
 *
 */
/*@}*/

void
dns_journal_current_rr(dns_journal_t *j, dns_name_t **name, uint32_t *ttl,
		       dns_rdata_t **rdata);
/*%<
 * Get the name, ttl, and rdata of the current journal RR.
 *
 * Requires:
 * \li     The    \
		if (!urcu_qsbr_read_ongoing()) {   \
			urcu_qsbr_thread_online(); \
		}                                  \
		_rcu_dereference(ptr);             \
	})

#undef rcu_dereference
#define rcu_dereference(ptr) isc_qsbr_rcu_dereference(ptr)

#endif /* RCU_QSBR */

/* clang-format off */
/*
 * Following definitions were copied from liburcu development branch to help
 * with AddressSanitizer complaining about calling caa_container_of on NULL.
 */

#if !defined(caa_container_of_check_null)
/*
 * caa_container_of_check_null - Get the address of an object containing a field.
 *
 * @ptr: pointer to the field.
 * @type: type of the object.
 * @member: name of the field within the object.
 *
 * Return the address of the object containing the field. Return NULL if
 * @ptr is NULL.
 */
#define caa_container_of_check_null(ptr, type, member)			\
	__extension__							\
	({								\
		const __typeof__(((type *) NULL)->member) * __ptr = (ptr); \
		(__ptr) ? (type *)((char *)__ptr - offsetof(type, member)) : NULL; \
	})

#de <dns/rpz.h>

/*
 * Error message if dlopen(librpz) failed.
 */
extern librpz_emsg_t librpz_lib_open_emsg;

/*
 * These shim BIND9 database, node, and rdataset are handles on RRs from librpz.
 *
 * All of these structures are used by a single thread and so need no locks.
 *
 * dns_rpsdb_t holds the state for a set of RPZ queries.
 *
 * rpsnode_t is a link to the dns_rpsdb_t for the set of  RPZ queries
 * and a flag saying whether it is pretending to be a node with RRs for
 * the qname or the node with the SOA for the zone containing the rewritten
 * RRs or justifying NXDOMAIN.
 */
typedef struct {
	uint8_t unused;
} rpsnode_t;

struct dns_rpsdb {
	dns_db_t	    common;
	int		    ref_cnt;
	librpz_result_id_t  hit_id;
	librpz_result_t	    result;
	librpz_rsp_t	   *rsp;
	librpz_domain_buf_t origin_buf;
	const dns_name_t   *qname;
	rpsnode_t	    origin_node;
	rpsnode_t	    data_node;
};

/*
 * Convert a dnsrps policy to a classic BIND9 RPZ policy.
 */
dns_rpz_policy_t
dns_dnsrps_2policy(librpz_policy_t rps_policy) bswap_32(x)
#define le32toh(x) (x)

#endif /* WORDS_BIGENDIAN */
#endif /* !htobe32 */

#ifndef htobe64
#if WORDS_BIGENDIAN

#define htobe64(x) (x)
#define htole64(x) bswap_64(x)
#define be64toh(x) (x)
#define le64toh(x) bswap_64(x)

#else /* WORDS_BIGENDIAN */

#define htobe64(x) bswap_64(x)
#define htole64(x) (x)
#define be64toh(x) bswap_64(x)
#define le64toh(x) (x)

#endif /* WORDS_BIGENDIAN */
#endif /* !htobe64 */

/*
 * Macros to convert uint8_t arrays to integers.
 */

/* Low-Endian */

#define ISC_U16TO8_LE(p, v)      \
	(p)[0] = (uint8_t)((v)); \
	(p)[1] = (uint8_t)((v) >> 8);

#define ISC_U8TO16_LE(p) (((uint16_t)((p)[0])) | ((uint16_t)((p)[1]) << 8))

#define ISC_U32TO8_LE(p, v)            \
	(p)[0] = (uint8_t)((v));       \
	(p)[1] = (uint8_t)((v) >> 8);  \
	(p)[2] = (uint8_t)((v) >> 16); \
	(p)[3] = (uint8_t)((v) >> 24);

#define ISC_U8TO32_LE(p)                                    \
	(((uint32_t)((p)[0])) | ((uint32_t)((p)[1]) << 8) | \
	 ((uint32_t)((p)[2]) << 16) | ((uint32_t)((p)[3]) << 24))
chtype_tcpself the addresses are mapped to
 *		the standard reverse names under IN-ADDR.ARPA and IP6.ARPA.
 *		RFC 1035, Section 3.5, "IN-ADDR.ARPA domain" and RFC 3596,
 *		Section 2.5, "IP6.ARPA Domain".
 *
 *		For dns_ssumatchtype_6to4self, IPv4 address are converted
 *		to a 6to4 prefix (48 bits) per the rules in RFC 3056.  Only
 *		the top	48 bits of the IPv6 address are mapped to the reverse
 *		name. This is independent of whether the most significant 16
 *		bits match 2002::/16, assigned for 6to4 prefixes, or not.
 *
 *	Requires:
 *\li		'table' is a valid SSU table
 *\li		'signer' is NULL or a valid absolute name
 *\li		'addr' is NULL or a valid network address.
 *\li		'aclenv' is NULL or a valid ACL environment.
 *\li		'name' is a valid absolute name
 *\li		if 'addr' is not NULL, 'env' is not NULL.
 */

/*% Accessor functions to extract rule components */
bool
dns_ssurule_isgrant(const dns_ssurule_t *rule);

/*% Accessor functions to extract rule components */
dns_name_t *
dns_ssurule_identity(const UIRE(k != NULL);

	uint32_t k0 = ISC_U8TO32_LE(k);
	uint32_t k1 = ISC_U8TO32_LE(k + 4);

	*state = (isc_halfsiphash24_t){
		.k0 = k0,
		.k1 = k1,
		.v0 = UINT32_C(0x00000000) ^ k0,
		.v1 = UINT32_C(0x00000000) ^ k1,
		.v2 = UINT32_C(0x6c796765) ^ k0,
		.v3 = UINT32_C(0x74656462) ^ k1,
	};
}

static inline void
isc_halfsiphash24_one(isc_halfsiphash24_t *restrict state, const uint32_t m) {
	state->v3 ^= m;

	for (size_t i = 0; i < cROUNDS; ++i) {
		HALFSIPROUND(state->v0, state->v1, state->v2, state->v3);
	}

	state->v0 ^= m;
}

static inline void
isc_halfsiphash24_hash(isc_halfsiphash24_t *restrict state, const uint8_t *in,
		       const size_t inlen, const bool case_sensitive) {
	REQUIRE(inlen == 0 || in != NULL);

	if (in == NULL || inlen == 0) {
		return;
	}

	size_t	  len = inlen;
	const int right = state->inlen & 3;

	switch (right) {
	case 0:
		break;
	case 1:
		state->b |= U8TO32_ONE(case_sensitive, in[0]) << 8;
		state->inlen++;
		++in;

		if (--len == 0) {
			return;
		}
		FALLTHROUGH;
	case 2:
		sta
 *
 * For efficiency, the diff should be sorted by owner name.
 * If it is not sorted, operation will still be correct,
 * but less efficient.
 *
 * Requires:
 *\li	*diff is a valid diff (possibly empty), containing
 *	tuples of type #DNS_DIFFOP_ADD and/or
 *	For #DNS_DIFFOP_DEL tuples, the TTL is ignored.
 *
 */

isc_result_t
dns_diff_load(const dns_diff_t *diff, dns_rdatacallbacks_t *callbacks);
/*%<
 * Like dns_diff_apply, but for use when loading a new database
 * instead of modifying an existing one.  This bypasses the
 * database transaction mechanisms.
 *
 * Requires:
 *\li	'callbacks' points to a dns_rdatacallbacks_t structure obtained
 *	from dns_db_beginload()
 */

isc_result_t
dns_diff_print(const dns_diff_t *diff, FILE *file);

/*%<
 * Print the differences to 'file' or if 'file' is NULL via the
 * logging system.
 *
 * Require:
 *\li	'diff' to be valid.
 *\li	'file' to refer to a open file or NULL.
 *
 * Returns:
 *\li	#ISC_R_SUCCESS
 *\li	#ISC_R_NOMEMORY
 *\li	#ISC_R_UNEXPECTED
 *\li	any error /name.h>
#include <dns/rdata.h>
#include <dns/types.h>

/***
 *** Types
 ***/

/*%
 * A dns_difftuple_t represents a single RR being added or deleted.
 * The RR type and class are in the 'rdata' member; the class is always
 * the real one, not a DynDNS meta-class, so that the rdatas can be
 * compared using dns_rdata_compare().  The TTL is significant
 * even for deletions, because a deletion/addition pair cannot
 * be canceled out if the TTL differs (it might be an explicit
 * TTL update).
 *
 * Tuples are also used to represent complete RRs with owner
 * names for a couple of other purposes, such as the
 * individual RRs of a "RRset exists (value dependent)"
 * prerequisite set.  In this case, op==DNS_DIFFOP_EXISTS,
 * and the TTL is ignored.
 *
 * DNS_DIFFOP_*RESIGN will cause the 'resign' attribute of the resulting
 * RRset to be recomputed to be 'resign' seconds before the earliest RRSIG
 * timeexpire.
 */

typedef enum {
	DNS_DIFFOP_ADD = 0,	  /*%< Add an RR. */
	DNS_DIFFOP_DEL = 1,	  /*%< Delete an RR.' is no longer frozen.
 */

const char *
dns_kasp_getname(dns_kasp_t *kasp);
/*%<
 * Get kasp name.
 *
 * Requires:
 *
 *\li   'kasp' is a valid kasp.
 *
 * Returns:
 *
 *\li   name of 'kasp'.
 */

uint32_t
dns_kasp_signdelay(dns_kasp_t *kasp);
/*%<
 * Get the delay that is needed to ensure that all existing RRsets have been
 * re-signed with a successor key.  This is the signature validity minus the
 * signature refresh time (that indicates how far before signature expiry an
 * RRSIG should be refreshed).
 *
 * Requires:
 *
 *\li   'kasp' is a valid, frozen kasp.
 *
 * Returns:
 *
 *\li   signature refresh interval.
 */

uint32_t
dns_kasp_sigjitter(dns_kasp_t *kasp);
/*%<
 * Get signature jitter value.
 *
 * Requires:
 *
 *\li   'kasp' is a valid, frozen kasp.
 *
 * Returns:
 *
 *\li   signature jitter value.
 */

void
dns_kasp_setsigjitter(dns_kasp_t *kasp, uint32_t value);
/*%<
 * Set signature jitter value.
 *
 * Requires:
 *
 *\li   'kasp' is a valid, thawed kasp.
 */

uint32_t
dns_kasp_sigrefresh(dns_kac_loopmgr_t *loopmgr, isc_nm_t *nm,
		  unsigned int options, isc_tlsctx_cache_t *tlsctx_client_cache,
		  dns_client_t **clientp, const isc_sockaddr_t *localaddr4,
		  const isc_sockaddr_t *localaddr6);
/*%<
 * Create a DNS client object with minimal internal resources, such as
 * a default view for the IN class and IPv4/IPv6 dispatches for the view.
 *
 * dns_client_create() takes 'manager' arguments so that the caller can
 * control the behavior of the client through the underlying event framework.
 * 'localaddr4' and 'localaddr6' specify the local addresses to use for
 * each address family; if both are set to NULL, then wildcard addresses
 * will be used for both families. If only one is NULL, then the other
 * address will be used as the local address, and the NULL protocol family
 * will not be used.
 *
 * Requires:
 *
 *\li	'mctx' is a valid memory context.
 *
 *\li	'loopmgr' is a valid loop manager.

 *\li	'nm' is a valid network manager.
 *
 *\li	'tlsctx_client_cache' is a valid TLS context cache.
 	    dns_rdata_t *rdata);
/*%<
 * Build the rdata of a NSEC record.
 *
 * Requires:
 *\li	buffer	Points to a temporary buffer of at least
 * 		DNS_NSEC_BUFFERSIZE bytes.
 *\li	rdata	Points to an initialized dns_rdata_t.
 *
 * Ensures:
 *  \li    *rdata	Contains a valid NSEC rdata.  The 'data' member refers
 *		to 'buffer'.
 */

isc_result_t
dns_nsec_build(dns_db_t *db, dns_dbversion_t *version, dns_dbnode_t *node,
	       const dns_name_t *target, dns_ttl_t ttl);
/*%<
 * Build a NSEC record and add it to a database.
 */

bool
dns_nsec_typepresent(dns_rdata_t *nsec, dns_rdatatype_t type);
/*%<
 * Determine if a type is marked as present in an NSEC record.
 *
 * Requires:
 *\li	'nsec' points to a valid rdataset of type NSEC
 */

isc_result_t
dns_nsec_nseconly(dns_db_t *db, dns_dbversion_t *version, dns_diff_t *diff,
		  bool *answer);
/*
 * Report whether the DNSKEY RRset has a NSEC only algorithm.  Unknown
 * algorithms are assumed to support NSEC3.  If DNSKEY is not found,
 * *answer is set to false, and ISC_e <isc/endian.h>

/*
 * ASCII case conversion
 */
extern const uint8_t isc__ascii_tolower[256];
extern const uint8_t isc__ascii_toupper[256];

/*
 * Wrappers so we don't have to cast all over the place like <ctype.h>
 */
#define isc_ascii_tolower(c) isc__ascii_tolower[(uint8_t)(c)]
#define isc_ascii_toupper(c) isc__ascii_toupper[(uint8_t)(c)]

/*
 * A variant tolower() implementation with no memory accesses,
 * for use when the compiler is able to autovectorize.
 */
static inline uint8_t
isc__ascii_tolower1(uint8_t c) {
	return c + ('a' - 'A') * ('A' <= c && c <= 'Z');
}

/*
 * Copy `len` bytes from `src` to `dst`, converting to lower case.
 */
static inline void
isc_ascii_lowercopy(uint8_t *dst, const uint8_t *src, unsigned int len) {
	while (len-- > 0) {
		*dst++ = isc__ascii_tolower1(*src++);
	}
}

/*
 * Convert a string to lower case in place
 */
static inline void
isc_ascii_strtolower(char *str) {
	isc_ascii_lowercopy((uint8_t *)str, (uint8_t *)str,
			    (unsigned int)strlen(str));
}

/*
 * Convert 8 br query, before the all
 * nodes method can be called.  This method and the all node method
 * are both required for zone transfers to be supported.  If the
 * driver generates data dynamically (instead of searching in a
 * database for it) it should not implement this function as a zone
 * transfer would be meaningless.  A SDLZ driver does not have to
 * implement an allow zone transfer method.
 *
 * This method should return ISC_R_SUCCESS if the zone is supported by
 * the database and a zone transfer is allowed for the specified
 * client.  If the zone is supported by the database, but zone
 * transfers are not allowed for the specified client this method
 * should return ISC_R_NOPERM..  Lastly the method should return
 * ISC_R_NOTFOUND if the zone is not supported by the database.  If an
 * error occurs it should return a result code indicating the type of
 * error.
 */

typedef isc_result_t (*dns_sdlzauthorityfunc_t)(const char *zone,
						void *driverarg, void *dbdata,
						dns_sdlzlookup_t *lookup);
re_t *keystore, const dns_name_t *origin,
		    const char *policy, dns_rdataclass_t rdclass,
		    isc_mem_t *mctx, uint32_t alg, int size, int flags,
		    dst_key_t **dstkey);
/*%<
 * Create a DNSSEC key pair. Set keystore PKCS#11 URI.
 *
 * Requires:
 *
 *\li   'keystore' is a valid keystore.
 *
 *\li   'origin' is a valid DNS owner name.
 *
 *\li   'policy' is the name of the DNSSEC policy.
 *
 *\li   'mctx' is a valid memory context.
 *
 *\li	'dstkey' is not NULL and '*dstkey' is NULL.
 *
 */

isc_result_t
dns_keystorelist_find(dns_keystorelist_t *list, const char *name,
		      dns_keystore_t **kspp);
/*%<
 * Search for a keystore with name 'name' in 'list'.
 * If found, '*kspp' is (strongly) attached to it.
 *
 * Requires:
 *
 *\li   'kspp' points to a NULL dns_keystore_t *.
 *
 * Returns:
 *
 *\li   #ISC_R_SUCCESS          A matching keystore was found.
 *\li   #ISC_R_NOTFOUND         No matching keystore was found.
 */

#ifdef DNS_KEYSTORE_TRACE
/* Compatibility macros */
#define dns_keystore_attach/*%
 * Reference counting for dns_ntatable
 */

isc_result_t
dns_ntatable_add(dns_ntatable_t *ntatable, const dns_name_t *name, bool force,
		 isc_stdtime_t now, uint32_t lifetime);
/*%<
 * Add a negative trust anchor to 'ntatable' for name 'name',
 * which will expire at time 'now' + 'lifetime'.  If 'force' is true,
 * then the NTA will persist for the entire specified lifetime.
 * If it is false, then the name will be queried periodically and
 * validation will be attempted to see whether it's still bogus;
 * if validation is successful, the NTA will be allowed to expire
 * early and validation below the NTA will resume.
 *
 * Notes:
 *
 *\li   If an NTA already exists in the table, its expiry time
 *      is updated.
 *
 * Requires:
 *
 *\li	'ntatable' points to a valid ntatable.
 *
 *\li	'name' points to a valid name.
 *
 * Returns:
 *
 *\li	ISC_R_SUCCESS
 *
 *\li	Any other result indicates failure.
 */

isc_result_t
dns_ntatable_delete(dns_ntatable_t *ntatable, const dns_name_t *keyname);
/*%<
 * Delete olicy; /* DNS_RPZ_POLICY_GIVEN or override */
	uint16_t	 ede;	 /* Extended DNS Error */

	uint32_t min_update_interval;	/* minimal interval between
					 * updates */
	isc_ht_t	*nodes;		/* entries in zone */
	dns_rpz_zones_t *rpzs;		/* owner */
	isc_time_t	 lastupdated;	/* last time the zone was processed
					 * */
	bool		 updatepending; /* there is an update pending */
	bool		 updaterunning; /* there is an update running */
	isc_result_t	 updateresult;	/* result from the offloaded work */
	dns_db_t	*db;		/* zones database */
	dns_dbversion_t *dbversion;	/* version we will be updating to */
	dns_db_t	*updb;		/* zones database we're working on */
	dns_dbversion_t *updbversion;	/* version we're currently working
					 * on */
	bool	     addsoa;		/* add soa to the additional section */
	isc_timer_t *updatetimer;
};

/*
 * Radix tree node for response policy IP addresses
 */
typedef struct dns_rpz_cidr_node dns_rpz_cidr_node_t;

/*
 * Bitfields indicating which policy zones have policies of
 * which type.
 */
tyr within
 * a configurable amount of seconds (see isc_log_[sg]etduplicateinterval).
 * This function is otherwise identical to isc_log_vwrite().
 */
void
isc_log_vwrite1(isc_log_t *lctx, isc_logcategory_t *category,
		isc_logmodule_t *module, int level, const char *format,
		va_list args)

	ISC_FORMAT_PRINTF(5, 0);

void
isc_log_setdebuglevel(isc_log_t *lctx, unsigned int level);
/*%<
 * Set the debugging level used for logging.
 *
 * Notes:
 *\li	Setting the debugging level to 0 disables debugging log messages.
 *
 * Requires:
 *\li	lctx is a valid logging context.
 *
 * Ensures:
 *\li	The debugging level is set to the requested value.
 */

unsigned int
isc_log_getdebuglevel(isc_log_t *lctx);
/*%<
 * Get the current debugging level.
 *
 * Notes:
 *\li	This is provided so that a program can have a notion of
 *	"increment debugging level" or "decrement debugging level"
 *	without needing to keep track of what the current level is.
 *
 *\li	A return value of 0 indicates that debugging messages are disabled.
 *
 from NULL to point to the new
 *	categories array, and its "id" member set to UINT_MAX.
 *
 * Requires:
 *\li	lctx is a valid logging context.
 *\li	categories != NULL.
 *\li	categories[0].name != NULL.
 *
 * Ensures:
 * \li	There are references to each category in the logging context,
 * 	so they can be used with isc_log_usechannel() and isc_log_write().
 */

void
isc_log_registermodules(isc_log_t *lctx, isc_logmodule_t modules[]);
/*%<
 * Identify logging categories a library will use.
 *
 * Notes:
 *\li	A module should only be registered once, but no mechanism enforces
 *	this rule.
 *
 *\li	The end of the modules array is identified by a NULL name.
 *
 *\li	Because the name is used by #ISC_LOG_PRINTMODULE, it should not
 *	be altered or destroyed after isc_log_registermodules().
 *
 *\li	Because each element of the modules array is used by
 *	isc_log_modulebyname, it should not be altered or destroyed
 *	after registration.
 *
 *\li	The value of the id integer in each structure is overwritten
 *	by this i	Out of range
 */

uint32_t
isc_time_nanoseconds(const isc_time_t *t);
/*%<
 * Return the number of nanoseconds stored in a time structure.
 *
 * Notes:
 *\li	This is the number of nanoseconds in excess of the number
 *	of seconds since the epoch; it will always be less than one
 *	full second.
 *
 * Requires:
 *\li	't' is a valid pointer.
 *
 * Ensures:
 *\li	The returned value is less than 1*10^9.
 */

uint32_t
isc_time_miliseconds(const isc_time_t *t);
/*%<
 * Returns time 't' expressed as a number of milliseconds.
 *
 * Requires:
 *
 *\li	't' is a valid pointer.
 */

void
isc_time_formattimestamp(const isc_time_t *t, char *buf, unsigned int len);
/*%<
 * Format the time 't' into the buffer 'buf' of length 'len',
 * using a format like "30-Aug-2000 04:06:47.997" and the local time zone.
 * If the text does not fit in the buffer, the result is indeterminate,
 * but is always guaranteed to be null terminated.
 *
 *  Requires:
 *\li      'len' > 0
 *\li      'buf' points to an array of at least len chars
 *
_stats      isc_stats_t;	     /*%< Statistics */
typedef int_fast64_t	      isc_statscounter_t;
typedef atomic_int_fast64_t   isc_atomic_statscounter_t;
typedef struct isc_symtab     isc_symtab_t;	/*%< Symbol Table */
typedef struct isc_textregion isc_textregion_t; /*%< Text Region */
typedef struct isc_time	      isc_time_t;	/*%< Time */
typedef struct isc_timer      isc_timer_t;	/*%< Timer */
typedef struct isc_work	      isc_work_t;	/*%< Work offloaded to an
						 *   external thread */

#if HAVE_LIBNGHTTP2
typedef struct isc_nm_http_endpoints isc_nm_http_endpoints_t;
/*%< HTTP endpoints set */
#endif /* HAVE_LIBNGHTTP2 */

/*% Statistics formats (text file or XML) */
typedef enum {
	isc_statsformat_file,
	isc_statsformat_xml,
	isc_statsformat_json
} isc_statsformat_t;

typedef enum isc_nmsocket_type {
	isc_nm_nonesocket = 0,
	isc_nm_udpsocket = 1 << 1,
	isc_nm_tcpsocket = 1 << 2,
	isc_nm_tlssocket = 1 << 3,
	isc_nm_httpsocket = 1 << 4,
	isc_nm_streamdnssocket = 1 << 5,
	isc_nm_proxystreamsocket = 1 << 6,	#DNS_R_NOKEYMATCH (No matching keys found).
 *\li		#DNS_R_TOOMANYKEYS (More than one matching keys found).
 *\li		#DNS_R_KEYNOTACTIVE (Key is not active).
 *
 */

isc_result_t
dns_keymgr_status(dns_kasp_t *kasp, dns_dnsseckeylist_t *keyring,
		  isc_stdtime_t now, char *out, size_t out_len);
/*%<
 * Retrieve the status of given 'kasp' policy and keys in the
 * 'keyring' and store the printable output in the 'out' buffer.
 *
 *	Requires:
 *\li		'kasp' is not NULL.
 *\li		'keyring' is not NULL.
 *\li		'out' is not NULL.
 *
 *	Returns:
 *\li		ISC_R_SUCCESS on success.
 *\li		ISC_R_NOSPACE if the 'out' buffer is too small.
 *\li		ISC_R_FAILURE if other error occurred.
 *\li		Printable status in 'out'.
 *
 */

bool
dns_keymgr_key_may_be_purged(const dst_key_t *key, uint32_t after,
			     isc_stdtime_t now);
/*%<
 * Checks if the key files for 'key' may be removed from disk.
 *
 *     Requires:
 *\li          'key' is a valid key.
 *
 *     Returns:
 *\li          true if the key files may be purged, false otherw;
	dns_iptable_t	 *iptable;
	dns_aclelement_t *elements;
	bool		  has_negatives;
	unsigned int	  alloc;	 /*%< Elements allocated */
	unsigned int	  length;	 /*%< Elements initialized */
	char		 *name;		 /*%< Temporary use only */
	ISC_LINK(dns_acl_t) nextincache; /*%< Ditto */
	ISC_LIST(dns_acl_port_transports_t) ports_and_transports;
	size_t port_proto_entries;
};

struct dns_aclenv {
	unsigned int   magic;
	isc_mem_t     *mctx;
	isc_refcount_t references;

	dns_acl_t *localhost;
	dns_acl_t *localnets;

	bool match_mapped;
#if defined(HAVE_GEOIP2)
	dns_geoip_databases_t *geoip;
#endif /* HAVE_GEOIP2 */
};

#define DNS_ACL_MAGIC	 ISC_MAGIC('D', 'a', 'c', 'l')
#define DNS_ACL_VALID(a) ISC_MAGIC_VALID(a, DNS_ACL_MAGIC)

/***
 *** Functions
 ***/

ISC_LANG_BEGINDECLS

void
dns_acl_create(isc_mem_t *mctx, int n, dns_acl_t **target);
/*%<
 * Create a new ACL, including an IP table and an array with room
 * for 'n' ACL elements.  The elements are uninitialized and the
 * length is 0.
 */

isc_result_t
dns_acl_any(i*\li		The used space in 'target' is updated.
 *
 * Returns:
 *\li	#ISC_R_SUCCESS			on success
 *\li	#ISC_R_NOSPACE			target buffer is too small
 */

isc_result_t
dns_rdataclass_tounknowntext(dns_rdataclass_t rdclass, isc_buffer_t *target);
/*%<
 * Put textual RFC3597 CLASSXXXX representation of class 'rdclass' into
 * 'target'.
 *
 * Requires:
 *\li	'rdclass' is a valid class.
 *
 *\li	'target' is a valid text buffer.
 *
 * Ensures,
 *	if the result is success:
 *\li		The used space in 'target' is updated.
 *
 * Returns:
 *\li	#ISC_R_SUCCESS			on success
 *\li	#ISC_R_NOSPACE			target buffer is too small
 */

void
dns_rdataclass_format(dns_rdataclass_t rdclass, char *array, unsigned int size);
/*%<
 * Format a human-readable representation of the class 'rdclass'
 * into the character array 'array', which is of size 'size'.
 * The resulting string is guaranteed to be null-terminated.
 */

#define DNS_RDATACLASS_FORMATSIZE sizeof("CLASS65535")
/*%<
 * Minimum size of array to pass to dns_rdataclass_format().
 */base64_totext(isc_region_t *source, int wordlength, const char *wordbreak,
		  isc_buffer_t *target);
/*!<
 * \brief Convert data into base64 encoded text.
 *
 * Notes:
 *\li	The base64 encoded text in 'target' will be divided into
 *	words of at most 'wordlength' characters, separated by
 * 	the 'wordbreak' string.  No parentheses will surround
 *	the text.
 *
 * Requires:
 *\li	'source' is a region containing binary data
 *\li	'target' is a text buffer containing available space
 *\li	'wordbreak' points to a null-terminated string of
 *		zero or more whitespace characters
 *
 * Ensures:
 *\li	target will contain the base64 encoded version of the data
 *	in source.  The 'used' pointer in target will be advanced as
 *	necessary.
 */

isc_result_t
isc_base64_decodestring(const char *cstr, isc_buffer_t *target);
/*!<
 * \brief Decode a null-terminated base64 string.
 *
 * Requires:
 *\li	'cstr' is non-null.
 *\li	'target' is a valid buffer.
 *
 * Returns:
 *\li	#ISC_R_SUCCESS	-- the entire decoded representatios/forward.h */

#include <isc/lang.h>
#include <isc/mem.h>
#include <isc/refcount.h>
#include <isc/result.h>
#include <isc/sockaddr.h>

#include <dns/fixedname.h>
#include <dns/qp.h>
#include <dns/types.h>

/* Add -DDNS_FORWARD_TRACE=1 to CFLAGS for detailed reference tracing */

ISC_LANG_BEGINDECLS

struct dns_forwarder {
	isc_sockaddr_t addr;
	dns_name_t    *tlsname;
	ISC_LINK(dns_forwarder_t) link;
};

typedef ISC_LIST(struct dns_forwarder) dns_forwarderlist_t;

struct dns_forwarders {
	dns_forwarderlist_t fwdrs;
	dns_fwdpolicy_t	    fwdpolicy;
	isc_mem_t	   *mctx;
	isc_refcount_t	    references;
	dns_name_t	    name;
};

void
dns_fwdtable_create(isc_mem_t *mctx, dns_view_t *view,
		    dns_fwdtable_t **fwdtablep);
/*%<
 * Creates a new forwarding table.
 *
 * Requires:
 * \li 	mctx is a valid memory context.
 * \li	fwdtablep != NULL && *fwdtablep == NULL
 */

isc_result_t
dns_fwdtable_addfwd(dns_fwdtable_t *fwdtable, const dns_name_t *name,
		    dns_forwarderlist_t *fwdrs, dns_fwdpolicy_t policy);
isc_reC_R_NOMORE			There are no more nodes in the
 *					database.
 *
 *\li	Other results are possible, depending on the DB implementation.
 */

#define dns_dbiterator_current(iterator, nodep, name) \
	dns__dbiterator_current(iterator, nodep, name DNS__DB_FILELINE)
isc_result_t
dns__dbiterator_current(dns_dbiterator_t *iterator, dns_dbnode_t **nodep,
			dns_name_t *name DNS__DB_FLARG);
/*%<
 * Return the current node.
 *
 * Notes:
 *\li	If 'name' is not NULL, it will be set to the name of the node.
 *
 * Requires:
 *\li	'iterator' is a valid iterator.
 *
 *\li	nodep != NULL && *nodep == NULL
 *
 *\li	The node cursor of 'iterator' is at a valid location (i.e. the
 *	result of last call to a cursor movement command was ISC_R_SUCCESS).
 *
 *\li	'name' is NULL, or is a valid name with a dedicated buffer.
 *
 * Returns:
 *
 *\li	#ISC_R_SUCCESS
 *\li	#DNS_R_NEWORIGIN
 *      If this iterator was created with 'relative_names' set to true,
 *      then #DNS_R_NEWORIGIN will be returned when there is a change in
 *      oriegarding copyright ownership.
 */

/*
 * Copyright (C) 2001 Nominum, Inc.
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC AND NOMINUM DISCLAIMS ALL
 * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#pragma once

/*! \file isccc/symtype.h */

#define ISCCC_SYMTYPE_ZONESTATS	   0x0001
#define ISCCC_SYMTYPE_CCDUP	   0x0002
#define ISCCC_SYMTYPE_TELLSERVICE  0x0003
#define ISCCC_SYMTYPE_TELLRESPONSE 0x0004
/*
 * *%<
 * Start listening for raw messages over the TCP interface 'iface', using
 * net manager 'mgr'.
 *
 * On success, 'sockp' will be updated to contain a new listening TCP
 * socket.
 *
 * When connection is accepted on the socket, 'accept_cb' will be called with
 * 'accept_cbarg' as its argument. The callback is expected to start a read.
 *
 * If 'quota' is not NULL, then the socket is attached to the specified
 * quota. This allows us to enforce TCP client quota limits.
 *
 */

void
isc_nm_tcpconnect(isc_nm_t *mgr, isc_sockaddr_t *local, isc_sockaddr_t *peer,
		  isc_nm_cb_t connect_cb, void *connect_cbarg,
		  unsigned int timeout);
/*%<
 * Create a socket using netmgr 'mgr', bind it to the address 'local',
 * and connect it to the address 'peer'.
 *
 * When the connection is complete or has timed out, call 'cb' with
 * argument 'cbarg'.
 *
 * 'timeout' specifies the timeout interval in milliseconds.
 *
 * The connected socket can only be accessed via the handle passed to
 * 'cb'.
 */

isc_result_t
isc_nmetmgr_destroy(isc_nm_t **netmgrp);
/*%<
 * Similar to isc_nm_detach(), but requires all other references to be gone.
 */

void
isc_nm_attach(isc_nm_t *mgr, isc_nm_t **dst);
void
isc_nm_detach(isc_nm_t **mgr0);
/*%<
 * Attach/detach a network manager. When all references have been
 * released, the network manager is shut down, freeing all resources.
 */

void
isc_nmsocket_close(isc_nmsocket_t **sockp);
/*%<
 * isc_nmsocket_close() detaches a listening socket that was
 * created by isc_nm_listenudp(), isc_nm_listentcp(), or
 * isc_nm_listentcpdns(). Once there are no remaining child
 * sockets with active handles, the socket will be closed.
 */

void
isc_nmsocket_set_tlsctx(isc_nmsocket_t *listener, isc_tlsctx_t *tlsctx);
/*%<
 * Asynchronously replace the TLS context within the listener socket object.
 * The function is intended to be used during reconfiguration.
 *
 * Requires:
 * \li	'listener' is a pointer to a valid network manager listener socket
 object with TLS support;
 * \li	'tlsctx' is a valid pointe%<
 * Called when registering a new plugin.
 *
 * 'parameters' contains the plugin configuration text.
 *
 * '*instp' will be set to the module instance handle if the function
 * is successful.
 *
 * Returns:
 *\li	#ISC_R_SUCCESS
 *\li	#ISC_R_NOMEMORY
 *\li	Other errors are possible
 */

typedef void
ns_plugin_destroy_t(void **instp);
/*%<
 * Destroy a plugin instance.
 *
 * '*instp' must be set to NULL by the function before it returns.
 */

typedef isc_result_t
ns_plugin_check_t(const char *parameters, const void *cfg, const char *file,
		  unsigned long line, isc_mem_t *mctx, isc_log_t *lctx,
		  void *actx);
/*%<
 * Check the validity of 'parameters'.
 */

typedef int
ns_plugin_version_t(void);
/*%<
 * Return the API version number a plugin was compiled with.
 *
 * If the returned version number is no greater than
 * NS_PLUGIN_VERSION, and no less than NS_PLUGIN_VERSION - NS_PLUGIN_AGE,
 * then the module is API-compatible with named.
 */

/*%
 * Prototypes for API functions to be defined in each module.
_t value which will be returned by the
 *         function into which the hook is inserted if the action returns
 *         NS_HOOK_RETURN.
 *
 * In order for a hook action to be called for a given hook, a pointer to that
 * action function (along with an optional pointer to action-specific data) has
 * to be inserted into the relevant hook table entry for that hook using an
 * ns_hook_add() call.  If multiple actions are set up at a single hook point
 * (e.g. by multiple plugin modules), they are processed in FIFO order, that is
 * they are performed in the same order in which their relevant ns_hook_add()
 * calls were issued.  Since the configuration is loaded from a single thread,
 * this means that multiple actions at a single hook point are determined by
 * the order in which the relevant plugin modules were declared in the
 * configuration file(s).  The hook API currently does not support changing
 * this order.
 *
 * As an example, consider the following hypothetical function in query.c:
 *
 * --------r to a function without such
 * qualifier, and variable assignment from a const pointer to a non-const
 * pointer.
 *
 * As the macro may hide valid errors, their usage is not recommended
 * unless there is a well-thought reason for a cast.  A typical use case for
 * __UNCONST() involve an API that does not follow the so-called ``const
 * correctness'' even if it would be appropriate.
 */
#define UNCONST(ptr) ((void *)(uintptr_t)(ptr))

#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))

/*
 * Optional return values, or out-arguments
 */
#define SET_IF_NOT_NULL(obj, val) \
	if ((obj) != NULL) {      \
		*(obj) = (val);   \
	}

/*%
 * Get the allocation size for a struct with a flexible array member
 * containing `count` elements. The struct is identified by a pointer,
 * typically the one that points to (or will point to) the allocation.
 */
#define STRUCT_FLEX_SIZE(pointer, member, count) \
	(sizeof(*(pointer)) + sizeof(*(pointer)->member) * (count))

/*%
 * Use this in translation units that would otherwise bs.h>

/*! \file isc/util.h
 * NOTE:
 *
 * This file is not to be included from any <isc/???.h> (or other) library
 * files.
 *
 * \brief
 * Including this file puts several macros in your name space that are
 * not protected (as all the other ISC functions/macros do) by prepending
 * ISC_ or isc_ to the name.
 */

#include <isc/attributes.h>

/***
 *** Clang Compatibility Macros
 ***/

#if !defined(__has_feature)
#define __has_feature(x) 0
#endif /* if !defined(__has_feature) */

/***
 *** General Macros.
 ***/

/*%
 * Legacy way how to hide unused function arguments, don't use in
 * the new code, rather use the ISC_ATTR_UNUSED macro that expands
 * to either C23's [[maybe_unused]] or __attribute__((__unused__)).
 *
 * \code
 * int
 * foo(ISC_ATTR_UNUSED char *bar) {
 *         ...;
 * }
 * \endcode
 */
#define UNUSED(x) (void)(x)

#if __GNUC__ >= 8 && !defined(__clang__)
#define ISC_NONSTRING __attribute__((nonstring))
#else /* if __GNUC__ >= 8 && !defined(__clang__) */
#define ISC_NONSTRING
#endif /* __GNUCe
 * is not found ISC_R_FILENOTFOUND is returned with the structure initialized
 * as if file contained only:
 *
 *	nameserver ::1
 *	nameserver 127.0.0.1
 *
 * Notes:
 *
 *\li	Currently, only the following options are supported:
 *	nameserver, domain, search, sortlist, ndots, and options.
 *	In addition, 'sortlist' is not actually effective; it's parsed, but
 *	the application cannot use the configuration.
 *
 * Returns:
 * \li	ISC_R_SUCCESS on success
 * \li  ISC_R_FILENOTFOUND if the file was not found. *confp will be valid.
 * \li  other on error.
 *
 * Requires:
 *
 *\li	'mctx' is a valid memory context.
 *
 *\li	'filename' != NULL
 *
 *\li	'confp' != NULL && '*confp' == NULL
 */

void
irs_resconf_destroy(irs_resconf_t **confp);
/*%<
 * Destroy the resconf object.
 *
 * Requires:
 *
 *\li	'*confp' is a valid resconf object.
 *
 * Ensures:
 *
 *\li	*confp == NULL
 */

isc_sockaddrlist_t *
irs_resconf_getnameservers(irs_resconf_t *conf);
/*%<
 * Return a list of name server addresses stored in 'conf'.
 *
 *\li	'name' is valid.
 */

void
dns_adb_setcookie(dns_adb_t *adb, dns_adbaddrinfo_t *addr,
		  const unsigned char *cookie, size_t len);
/*%<
 * Record the COOKIE associated with this address.  If
 * cookie is NULL or len is zero the recorded COOKIE is cleared.
 *
 * Requires:
 *\li	'adb' is valid.
 *\li	'addr' is valid.
 */

size_t
dns_adb_getcookie(dns_adbaddrinfo_t *addr, unsigned char *cookie, size_t len);
/*
 * If 'cookie' is not NULL, then retrieve the saved COOKIE value and store it
 * in 'cookie' which has size 'len'.
 *
 * Requires:
 *\li	'addr' is valid.
 *
 * Returns:
 *	The size of the cookie or zero if it doesn't exist, or when 'cookie' is
 *      not NULL and it doesn't fit in the buffer.
 */

void
dns_adb_setquota(dns_adb_t *adb, uint32_t quota, uint32_t freq, double low,
		 double high, double discount);
/*%<
 * Set the baseline ADB quota, and configure parameters for the
 * quota adjustment algorithm.
 *
 * If the number of fetches currently waiting for responses from this
 * address exceeds resolver().
 *
 * Requires:
 *
 *\li	'mem' must be a valid memory context.
 *
 *\li	'view' be a pointer to a valid view.
 *
 *\li	'newadb' != NULL && '*newadb' == NULL.
 */

#if DNS_ADB_TRACE
#define dns_adb_ref(ptr)   dns_adb__ref(ptr, __func__, __FILE__, __LINE__)
#define dns_adb_unref(ptr) dns_adb__unref(ptr, __func__, __FILE__, __LINE__)
#define dns_adb_attach(ptr, ptrp) \
	dns_adb__attach(ptr, ptrp, __func__, __FILE__, __LINE__)
#define dns_adb_detach(ptrp) dns_adb__detach(ptrp, __func__, __FILE__, __LINE__)
ISC_REFCOUNT_TRACE_DECL(dns_adb);
#else
ISC_REFCOUNT_DECL(dns_adb);
#endif

void
dns_adb_shutdown(dns_adb_t *adb);
/*%<
 * Shutdown 'adb'.
 *
 * Requires:
 *
 * \li	'*adb' is a valid dns_adb_t.
 */

isc_result_t
dns_adb_createfind(dns_adb_t *adb, isc_loop_t *loop, isc_job_cb cb, void *cbarg,
		   const dns_name_t *name, const dns_name_t *qname,
		   dns_rdatatype_t qtype, unsigned int options,
		   isc_stdtime_t now, dns_name_t *target, in_port_t port,
		   unsigned int depth, isc_counter_t *qc, isc_eyctx_create(isc_mem_t *mctx, dns_tkeyctx_t **tctxp);
/*%<
 *	Create an empty TKEY context.
 *
 * 	Requires:
 *\li		'mctx' is not NULL
 *\li		'tctx' is not NULL
 *\li		'*tctx' is NULL
 *
 *	Returns
 *\li		#ISC_R_SUCCESS
 *\li		#ISC_R_NOMEMORY
 *\li		return codes from dns_name_fromtext()
 */

void
dns_tkeyctx_destroy(dns_tkeyctx_t **tctxp);
/*%<
 *      Frees all data associated with the TKEY context
 *
 * 	Requires:
 *\li		'tctx' is not NULL
 *\li		'*tctx' is not NULL
 */

isc_result_t
dns_tkey_processquery(dns_message_t *msg, dns_tkeyctx_t *tctx,
		      dns_tsigkeyring_t *ring);
/*%<
 *	Processes a query containing a TKEY record, adding or deleting TSIG
 *	keys if necessary, and modifies the message to contain the response.
 *
 *	Requires:
 *\li		'msg' is a valid message
 *\li		'tctx' is a valid TKEY context
 *\li		'ring' is a valid TSIG keyring
 *
 *	Returns
 *\li		#ISC_R_SUCCESS	msg was updated (the TKEY operation succeeded,
 *				or msg now includes a TKEY with an error set)
 *		DNS_R_FORMERR	the packet called immediately after the create method is called. The driver
 * may call configuration functions during the configure call
 */

typedef bool (*dns_dlzssumatch_t)(const dns_name_t    *signer,
				  const dns_name_t    *name,
				  const isc_netaddr_t *tcpaddr,
				  dns_rdatatype_t type, const dst_key_t *key,
				  void *driverarg, void *dbdata);
/*%<
 * Method prototype.  Drivers implementing the DLZ interface may
 * optionally supply a ssumatch method. If supplied, this will be
 * called to authorize update requests
 */

/*% the methods supplied by a DLZ driver */
typedef struct dns_dlzmethods {
	dns_dlzcreate_t	      create;
	dns_dlzdestroy_t      destroy;
	dns_dlzfindzone_t     findzone;
	dns_dlzallowzonexfr_t allowzonexfr;
	dns_dlzconfigure_t    configure;
	dns_dlzssumatch_t     ssumatch;
} dns_dlzmethods_t;

/*% information about a DLZ driver */
struct dns_dlzimplementation {
	const char	       *name;
	const dns_dlzmethods_t *methods;
	isc_mem_t	       *mctx;
	void		       *driverarg;
	ISC_LINK(dns_dlude <stdbool.h>

#include <isc/lang.h>

#include <dns/clientinfo.h>
#include <dns/name.h>
#include <dns/types.h>
#include <dns/view.h>

#include <dst/dst.h>

ISC_LANG_BEGINDECLS

/***
 *** Types
 ***/

#define DNS_DLZ_MAGIC	   ISC_MAGIC('D', 'L', 'Z', 'D')
#define DNS_DLZ_VALID(dlz) ISC_MAGIC_VALID(dlz, DNS_DLZ_MAGIC)

typedef isc_result_t (*dns_dlzallowzonexfr_t)(void *driverarg, void *dbdata,
					      isc_mem_t		   *mctx,
					      dns_rdataclass_t	    rdclass,
					      const dns_name_t	   *name,
					      const isc_sockaddr_t *clientaddr,
					      dns_db_t		  **dbp);

/*%<
 * Method prototype.  Drivers implementing the DLZ interface MUST
 * supply an allow zone transfer method.  This method is called when
 * the DNS server is performing a zone transfer query.  The driver's
 * method should return ISC_R_SUCCESS and a database pointer to the
 * name server if the zone is supported by the database, and zone
 * transfer is allowed.  If the view's transfer acl should be used,
 * then the driver's methore.
 */

void
dns_remote_mark(dns_remote_t *remote, bool good);
/*%<
 *	Mark the current address 'good' (or not good if 'good' is
 *	'false').
 *
 *	Requires:
 *		'remote' is a valid remote structure.
 *		The current address index is lower than the address count.
 */

bool
dns_remote_done(dns_remote_t *remote);
/*%<
 *	Return 'true' if we iterated over all addresses, 'false' otherwise.
 *
 *	Requires:
 *		'remote' is a valid remote structure.
 */

ISC_LANG_ENDDECLS
/*
 * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
 *
 * SPDX-License-Identifier: MPL-2.0
 *
 * 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.
 */

#pragma once

#undef DNS_DB_NODETRACE

#if DNS_DB_NODETRACE

#define DNS__DB_FILELINE   , __func__, __FILE__, __LINE__
#definst isc_proxy2_tlv_type_t tlv_type,
				    const char *restrict str);
/*!<
 * \brief Append the string as TLV data to PROXYv2 header and update the
 * length field within the header accordingly.
 *
 * Requires:
 *\li	'outbuf' is not NULL;
 *\li	used region within 'outbuf' is more or equal
 *to 'ISC_PROXY2_HEADER_SIZE';
 *\li	'data' is not NULL.
 *
 * Return values:
 *\li	'ISC_R_SUCCESS' - iteration over the data was successful;
 *\li	'ISC_R_NOSPACE' - not enough data in the output buffer.
 *\li	'ISC_R_RANGE' - too much data for PROXYv2 header.
 */

isc_result_t
isc_proxy2_make_tls_subheader(isc_buffer_t *restrict outbuf,
			      const uint8_t client_flags,
			      const bool    client_cert_verified,
			      const isc_region_t *restrict tls_subtlvs_data);
/*!<
 * \brief Create TLS (ISC_PROXY2_TLV_TYPE_TLS) TLV subheader which
 * can later be added to the PROXYv2 header TLV data.
 *
 * Arguments:
 *\li	'client_flags' - TLS client flags (see
 'isc_proxy2_tls_client_flags_t' enumeration for more details);
 *\lttached memory context, free the memory consumed by the object.
 *
 * Requires:
 *\li	'handler' is not NULL;
 *\li	'handler' is not pointing to NULL.
 */

void
isc_proxy2_handler_setcb(isc_proxy2_handler_t *restrict handler,
			 isc_proxy2_handler_cb_t cb, void *cbarg);
/*!<
 * \brief Change the data processing callback and its argument within the
 * given 'isc_proxy2_handler_t' object.
 *
 * Arguments:
 *\li	'handler' - PROXYv2 handler object;
 *\li	'cb' - new data processing callback;
 *\li	'cbarg' - new data processing callback argument.
 *
 * Requires:
 *\li	'handler' is not NULL;
 *\li	'cb' is not NULL.
 */

isc_result_t
isc_proxy2_handler_push_data(isc_proxy2_handler_t *restrict handler,
			     const void *restrict buf,
			     const unsigned int buf_size);
/*!<
 * \brief Push new data to the given 'isc_proxy2_handler_t'
 * object. Call the callback passing a status and a result of data
 * processing to it.
 *
 * To avoid erroneously recursive usage of the object, it is forbidden to call
 * this functist isc_sockaddr_t *restrict dst_addr,
					const isc_region_t *restrict tlv_data,
					const isc_region_t *restrict extra,
					void *cbarg);
/*!<
 * PROXYv2 data processing callback.
 *
 * Arguments:
 *\li	'result' - error status code;
 *\li	'cmd' - PROXYv2 command;
 *\li	'socktype' - PROXYv2 addresses socket type
 *(SOCK_STREAM, SOCK_DGRAM, or '0' for "unspecified" (SOCK_UNSPEC)).
 *\li	'src_addr' - original source address extracted from the PROXYv2 header;
 *\li	'dst_addr' - original destination address extracted from the PROXYv2
 *header;
 *\li	'tlv_data' - TLV-data extracted from the header;
 *\li	'extra_data' - extra unprocessed data past the PROXYv2 header. It is
 *not a part of the header, but it is fine to receive this when reading data
 *over TCP-based transports. In general, needs to be passed to the upper
 *level as is;
 *\li	'cbarg' - opaque pointer to user supplied data.
 *
 * The user-provided data processing callback function can get the
 * following error status codes:
 * \li	'ISC_R_SUCCESS' _t;

ISC_LANG_BEGINDECLS

/***
 ***	Functions
 ***/

uint32_t
dns_update_soaserial(uint32_t serial, dns_updatemethod_t method,
		     dns_updatemethod_t *used);
/*%<
 * Return the next serial number after 'serial', depending on the
 * update method 'method':
 *
 *\li	* dns_updatemethod_increment increments the serial number by one
 *\li	* dns_updatemethod_date sets the serial number to YYYYMMDD00
 *\li	* dns_updatemethod_unixtime sets the serial number to the current
 *	  time (seconds since UNIX epoch)
 *\li	* dns_updatemethod_none just returns the given serial
 *
 * NOTE: The dns_updatemethod_increment will be used if dns_updatemethod_date or
 * dns_updatemethod_unixtime is used and the new serial number would be lower
 * than current serial number.
 *
 * Sets *used to the method that was used.
 */

isc_result_t
dns_update_signatures(dns_update_log_t *log, dns_zone_t *zone, dns_db_t *db,
		      dns_dbversion_t *oldver, dns_dbversion_t *newver,
		      dns_diff_t *diff, uint32_t sigvalidityinterval);

isc_r once

/*****
***** Module Info
*****/

/*! \file dns/rdatasetiter.h
 * \brief
 * The DNS Rdataset Iterator interface allows iteration of all of the
 * rdatasets at a node.
 *
 * The dns_rdatasetiter_t type is like a "virtual class".  To actually use
 * it, an implementation of the class is required.  This implementation is
 * supplied by the database.
 *
 * It is the client's responsibility to call dns_rdataset_disassociate()
 * on all rdatasets returned.
 *
 * XXX more XXX
 *
 * MP:
 *\li	The iterator itself is not locked.  The caller must ensure
 *	synchronization.
 *
 *\li	The iterator methods ensure appropriate database locking.
 *
 * Reliability:
 *\li	No anticipated impact.
 *
 * Resources:
 *\li	TBS
 *
 * Security:
 *\li	No anticipated impact.
 *
 * Standards:
 *\li	None.
 */

/*****
***** Imports
*****/

#include <isc/lang.h>
#include <isc/magic.h>
#include <isc/stdtime.h>

#include <dns/types.h>

ISC_LANG_BEGINDECLS

/*****
***** Types
*****/

typedef struct dns_rdatasetitermethods {
	void (*destroyle, const char *filename,
		dns_masterformat_t format, dns_masterrawheader_t *header);

/*%<
 * Dump the database 'db' to the file 'filename' in the specified format by
 * 'format'.  If the format is dns_masterformat_text (the RFC1035 format),
 * 'style' specifies the file style (e.g., &dns_master_style_default).
 *
 * If 'format' is dns_masterformat_raw, then 'header' can contain
 * information to be written to the file header.
 *
 * Temporary dynamic memory may be allocated from 'mctx'.
 *
 * Returns:
 *\li	ISC_R_SUCCESS
 *\li	ISC_R_NOMEMORY
 *\li	Any database or rrset iterator error.
 *\li	Any dns_rdata_totext() error code.
 */
/*@}*/

isc_result_t
dns_master_rdatasettotext(const dns_name_t	   *owner_name,
			  dns_rdataset_t	   *rdataset,
			  const dns_master_style_t *style, dns_indent_t *indent,
			  isc_buffer_t *target);
/*%<
 * Convert 'rdataset' to text format, storing the result in 'target'.
 *
 * Notes:
 *\li	The rdata cursor position will be changed.
 *
 * Requires:
 *\li	'rdataset' is a valid notaset;
	dns_rdataset_t	*zsigrdataset;

	dns_rpz_st_t *rpz_st; /* RPZ state */
	dns_zone_t   *zone;   /* zone to search */

	dns_view_t *view; /* client view */

	isc_result_t result; /* query result */
	int	     line;   /* line to report error */
};

typedef isc_result_t (*ns_query_starthookasync_t)(query_ctx_t *qctx,
						  isc_mem_t *mctx, void *arg,
						  isc_loop_t *loop,
						  isc_job_cb cb, void *evarg,
						  ns_hookasync_t **ctxp);

/*
 * The following functions are expected to be used only within query.c
 * and query modules.
 */

isc_result_t
ns_query_done(query_ctx_t *qctx);
/*%<
 * Finalize this phase of the query process:
 *
 * - Clean up.
 * - If we have an answer ready (positive or negative), send it.
 * - If we need to restart for a chaining query, call ns__query_start() again.
 * - If we've started recursion, then just clean up; things will be
 *   restarted via fetch_callback()/query_resume().
 */

isc_result_t
ns_query_recurse(ns_client_t *client, dns_rdatatype_t qtype, dns_name_t *qn);
/*%
 * Clean up the magic number and the dynamic buffer associated with a command
 * channel message.
 *
 * Requires:
 *
 *\li	"ccmsg" to be valid.
 */

void
isccc_ccmsg_toregion(isccc_ccmsg_t *ccmsg, isccc_region_t *ccregion);

ISC_LANG_ENDDECLS
/*
 * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
 *
 * SPDX-License-Identifier: MPL-2.0
 *
 * 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.
 */

#pragma once

#include <inttypes.h>
#include <string.h>

#include <isc/magic.h>
#include <isc/mutex.h>
#include <isc/net.h>
#include <isc/refcount.h>
#include <isc/types.h>

#define NETADD