### Install and Setup apkg Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/build.md Install the apkg tool using pip and run its system setup command. This tool is used for upstream packaging and dependency management. ```bash pip3 install apkg ``` ```bash apkg system-setup ``` -------------------------------- ### Configure and Enable Config Tests Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/build.md Enables configuration tests during the Meson setup and installs the project. Multiple dependencies are required for these tests. ```bash $ meson configure build_dir -Dconfig_tests=enabled $ ninja install -C build_dir $ meson test -C build_dir --suite config ``` -------------------------------- ### Enable and Start Knot Resolver Service Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/deployment-systemd.md Use this command to enable the Knot Resolver service to start on boot and start it immediately. Assumes the service file is already installed. ```bash systemctl enable --now knot-resolver.service ``` -------------------------------- ### Configure Unusual Network Listen Examples Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/config-network-server.md Examples demonstrating custom ports, XDP protocol, and Unix domain sockets for listening. ```yaml network: # some unusual examples listen: - interface: '::1' port: 3535 - interface: eth0 port: 5335 # custom port number, default is 53 for XDP kind: xdp - unix-socket: /tmp/kres-socket # bind to unix domain socked ``` -------------------------------- ### Configure and Install Knot Resolver Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/build.md Sets up a build directory and installs Knot Resolver to a specified prefix. Use this for initial compilation and installation. ```bash $ meson setup build_dir --prefix=/tmp/kr $ ninja -C build_dir $ ninja install -C build_dir ``` -------------------------------- ### Example FORWARD Usage Source: https://github.com/cz-nic/knot-resolver/blob/master/modules/policy/README.rst Example of using the FORWARD action to direct all queries to public resolvers. ```APIDOC ## policy.add(policy.all(policy.FORWARD({'2001:148f:fffe::1', '2001:148f:ffff::1', '185.43.135.1', '193.14.47.1'}))) ### Description Forwards all queries to the specified public resolvers. ``` -------------------------------- ### Basic TLS Forwarding Example Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/modules-policy.rst A minimal example demonstrating TLS forwarding to a single server authenticated by its certificate pin. ```lua policy.TLS_FORWARD({{'192.0.2.1', pin_sha256='YQ=='}}) ``` -------------------------------- ### Custom RESTful Service Example Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/modules-http-custom-services.rst This example demonstrates how to create a custom RESTful service at '/service'. It handles different HTTP methods (GET, POST) and allows custom responses, including error codes and custom headers. ```APIDOC ## Custom RESTful Service '/service' ### Description This service handles requests to '/service' and can respond differently based on the HTTP method. It supports GET to retrieve a value and POST to update it, with error handling for invalid requests or unsupported methods. ### Method GET, POST, others (returns 405) ### Endpoint /service ### Parameters #### Query Parameters - **path** (string) - Description: The path requested, used as a key in the GET response. #### Request Body (for POST) - **data** (string) - Required - The data to be posted, expected to be a number. ### Request Example (GET) ```bash curl https://localhost:8453/service/some/path ``` ### Response Example (GET) ```json {"key":"/service/some/path","value":42} ``` ### Request Example (POST) ```bash curl -X POST -d "100" https://localhost:8453/service ``` ### Response Example (POST Success) ```json {"message":"Value updated"} ``` ### Response Example (POST Error - Invalid Data) ``` HTTP/1.1 500 Internal Server Error Content-Type: text/plain Not a good request ``` ### Response Example (Unsupported Method) ``` HTTP/1.1 405 Method Not Allowed Content-Type: text/plain Cannot do that ``` ``` ```APIDOC ## Custom Response Headers Example ### Description This example shows how to send custom headers and binary data in a response, disabling the default HTTP handler's response generation. ### Method Any (demonstrated with a generic handler) ### Endpoint (Assumed to be registered via `http.config`) ### Parameters None ### Request Example (Not applicable for response header generation itself) ### Response Example ``` HTTP/1.1 200 OK content-type: binary/octet-stream [binary-data] ``` ``` -------------------------------- ### Configuration File Syntax Examples Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/config-lua-overview.md Examples of valid configuration lines in Knot Resolver's configuration file, including variable assignments, command calls, and comments. ```APIDOC ## Configuration File Syntax ### Description Examples of valid configuration lines in Knot Resolver's configuration file. ### Syntax Examples - `group.option = 123456` - `group.option = "string value"` - `group.command(123456, "string value")` - `group.command({ key1 = "value1", key2 = 222, key3 = "third value" })` - `globalcommand(a_parameter_1, a_parameter_2, a_parameter_3, etc)` - `-- any text after -- sign is ignored till end of line` ``` -------------------------------- ### Install lua-http with Homebrew Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/modules-http.rst Instructions for installing the lua-http module on macOS using Homebrew, including OpenSSL setup. ```bash $ brew update $ brew install openssl $ brew link openssl --force # Override system OpenSSL ``` -------------------------------- ### Start Knot Resolver Service Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/upgrading-to-6.md Use `systemctl start knot-resolver` to start the main Knot Resolver service. This replaces the older method of starting individual `kresd@1` instances. ```bash systemctl start knot-resolver ``` ```bash systemctl start kresd@1 ``` -------------------------------- ### Start Knot Resolver Service with systemd Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/gettingstarted-startup.md Use this command to start the Knot Resolver service. Ensure you have the necessary permissions. ```bash sudo systemctl start knot-resolver.service ``` -------------------------------- ### Start Multiple kresd Instances Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/systemd-multiinst.rst Use systemctl to start multiple kresd instances, each identified by a number. Brace expansion can be used for a concise command. ```bash $ systemctl start kresd@1.service $ systemctl start kresd@2.service $ systemctl start kresd@3.service $ systemctl start kresd@4.service ``` ```bash $ systemctl start kresd@{1..4}.service ``` -------------------------------- ### Start Knot Resolver Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/user/upgrading-to-6.md Use this command to start the Knot Resolver service. ```bash systemctl start knot-resolver ``` -------------------------------- ### TLS Forwarding Examples Source: https://github.com/cz-nic/knot-resolver/blob/master/modules/policy/README.rst Examples demonstrating various TLS forwarding configurations, including adding a policy, single server authentication with pin_sha256 or hostname, non-standard ports, multiple pins, and multiple servers with different authentication methods. ```lua modules = { 'policy' } -- forward all queries over TLS to the specified server policy.add(policy.all(policy.TLS_FORWARD({{'192.0.2.1', pin_sha256='YQ=='}}))) ``` ```lua -- for brevity, other TLS examples omit policy.add(policy.all()) -- single server authenticated using its certificate pin_sha256 policy.TLS_FORWARD({{'192.0.2.1', pin_sha256='YQ=='}}) -- pin_sha256 is base64-encoded ``` ```lua -- single server authenticated using hostname and system-wide CA certificates policy.TLS_FORWARD({{'192.0.2.1', hostname='res.example.com'}}) ``` ```lua -- single server using non-standard port policy.TLS_FORWARD({{'192.0.2.1@443', pin_sha256='YQ=='}}) -- use @ or # to specify port ``` ```lua -- single server with multiple valid pins (e.g. anycast) policy.TLS_FORWARD({{'192.0.2.1', pin_sha256={'YQ==', 'Wg=='}}) ``` ```lua -- multiple servers, each with own authenticator policy.TLS_FORWARD({ -- please note that { here starts list of servers {'192.0.2.1', pin_sha256='Wg=='}, -- server must present certificate issued by specified CA and hostname must match {'2001:DB8::d0c', hostname='res.example.com', ca_file='/etc/knot-resolver/tlsca.crt'} }) ``` -------------------------------- ### Example NS Record Configuration Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/modules-experimental_dot_auth.rst This example shows how NS records should be configured to leverage the experimental DoT auto-discovery. It includes NS records pointing to specially formatted names and their corresponding A/AAAA glue records. ```dns ;; QUESTION SECTION: ;example.com. IN NS ;; AUTHORITY SECTION: example.com. 3600 IN NS dot-tpwxmgqdaurcqxqsckxvdq5sty3opxlgcbjj43kumdq62kpqr72a.a.example.com. example.com. 3600 IN NS dot-tpwxmgqdaurcqxqsckxvdq5sty3opxlgcbjj43kumdq62kpqr72a.b.example.com. ;; ADDITIONAL SECTION: dot-tpwxmgqdaurcqxqsckxvdq5sty3opxlgcbjj43kumdq62kpqr72a.a.example.com. 3600 IN A 192.0.2.1 dot-tpwxmgqdaurcqxqsckxvdq5sty3opxlgcbjj43kumdq62kpqr72a.b.example.com. 3600 IN AAAA 2001:DB8::1 ``` -------------------------------- ### Lua Etcd Configuration Example Source: https://github.com/cz-nic/knot-resolver/blob/master/modules/etcd/README.rst Example of how etcd configuration values translate to Lua variables. This shows the declarative style configuration. ```lua net = { '127.0.0.1' } cache.size = 10000000 ``` -------------------------------- ### Install Manager from Source Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/build.md Installs the Knot Resolver manager component. Navigate to the manager directory before running this command. ```bash cd manager python3 setup.py install ``` -------------------------------- ### Install Documentation Dependencies Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/README.md Install required Python packages for building documentation using pip. Alternatively, use the provided requirements file. ```sh pip install -U Sphinx sphinx-tabs sphinx_rtd_theme breathe # Alternatively pip install -r doc/requirements.txt ``` -------------------------------- ### Build and Install Knot Resolver with apkg Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/build.md After setting up apkg and cloning the repository, use apkg commands to build dependencies, build the package, and install it. apkg handles dependency resolution automatically. ```bash apkg build-dep ``` ```bash apkg build ``` ```bash apkg install ``` -------------------------------- ### Install lua-http from LuaRocks Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/modules-http.rst Instructions for installing the lua-http module directly from LuaRocks for specific Lua versions. ```bash $ luarocks --lua-version 5.1 install http ``` -------------------------------- ### Install Manager Dependencies with Poetry Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/manager-dev-env.md Installs all project dependencies, including optional ones, into a new virtual environment managed by Poetry. Omit --all-extras to exclude optional dependencies. ```bash poetry install --all-extras ``` -------------------------------- ### DAF Lua API Examples Source: https://github.com/cz-nic/knot-resolver/blob/master/modules/daf/README.rst Examples of how to use the DAF Lua API to add, modify, and manage firewall rules. ```APIDOC ## DAF Lua API ### Description This section demonstrates how to use the DAF Lua API to configure DNS filtering rules. ### Methods - `daf.add(rule_string)`: Adds a new firewall rule. - `daf.disable(rule_id)`: Disables a rule by its ID. - `daf.enable(rule_id)`: Enables a disabled rule by its ID. - `daf.del(rule_id)`: Deletes a rule by its ID. - `daf.clear()`: Removes all rules. - `daf.rules`: A variable to inspect active rules. ### Rule String Format Rules consist of filters (e.g., `qname = example.com`, `src = 192.0.2.0/24`) combined with operators (`=`, `~`, `AND`, `OR`) and actions (`deny`, `reroute`, `rewrite`, `mirror`, `forward`, `truncate`). ### Example Usage ```lua -- Block all queries with QNAME = example.com daf.add('qname = example.com deny') -- Block queries from a specific subnet and matching a QNAME regex daf.add('qname ~ %w+.example.com AND src = 192.0.2.0/24 deny') -- Reroute traffic from a subnet to a specific IP daf.add('src = 127.0.0.0/8 reroute 192.0.2.0/24-127.0.0.0') -- Rewrite DNS answers for a specific domain daf.add('src = 127.0.0.0/8 rewrite example.com A 127.0.0.2') -- Mirror queries to a logger daf.add('qname ~ %w+.example.com mirror 127.0.0.2') -- Forward queries from a subnet to a specific address and port daf.add('src = 127.0.0.1/8 forward 127.0.0.1@5335') -- Disable rule with ID 2 daf.disable(2) -- Delete rule with ID 2 daf.del(2) -- Clear all rules daf.clear() ``` ### Inspecting Rules ```text -- Show active rules > daf.rules [ 1 => { [rule] => { [count] => 42 [id] => 1 [cb] => function: 0x1a3eda38 } [info] => qname = example.com AND src = 127.0.0.1/8 deny [policy] => function: 0x1a3eda38 } ] ``` ``` -------------------------------- ### DAF Lua API Examples Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/modules-daf.rst Examples of how to use the DAF Lua API to add, disable, enable, delete, and clear firewall rules. ```APIDOC ## DAF Lua API ### Description This section demonstrates the usage of the DAF module's Lua API for managing firewall rules. ### Methods - `daf.add(rule_string)`: Adds a new firewall rule. - `daf.disable(rule_id)`: Disables a firewall rule by its ID. - `daf.enable(rule_id)`: Enables a disabled firewall rule by its ID. - `daf.del(rule_id)`: Deletes a firewall rule by its ID. - `daf.clear()`: Deletes all firewall rules. ### Rule String Format Rules consist of filters (e.g., `qname = example.com`, `src = 127.0.0.1/8`) and actions (e.g., `deny`, `reroute`, `rewrite`, `mirror`, `forward`, `truncate`). Filters can be combined using `AND`/`OR`. ### Examples ```lua -- Block all queries with QNAME = example.com daf.add('qname = example.com deny') -- Block queries from a specific subnet and matching a regex daf.add('qname ~ %w+.example.com AND src = 192.0.2.0/24 deny') -- Reroute traffic from a subnet daf.add('src = 127.0.0.0/8 reroute 192.0.2.0/24-127.0.0.0') -- Rewrite DNS answers daf.add('src = 127.0.0.0/8 rewrite example.com A 127.0.0.2') -- Mirror queries daf.add('qname ~ %w+.example.com mirror 127.0.0.2') -- Forward queries daf.add('src = 127.0.0.1/8 forward 127.0.0.1@5335') -- Truncate queries daf.add('dst = 192.0.2.51 truncate') -- Disable rule with ID 2 daf.disable(2) -- Enable rule with ID 2 daf.enable(2) -- Delete rule with ID 2 daf.del(2) -- Clear all rules daf.clear() ``` ### Viewing Rules Use `daf.rules` to view active rules. ```text -- Show active rules > daf.rules [ [1] => { [rule] => { [count] => 42 [id] => 1 [cb] => function: 0x1a3eda38 } [info] => qname = example.com AND src = 127.0.0.1/8 deny [policy] => function: 0x1a3eda38 } [2] => { [rule] => { [suspended] => true [count] => 123522 [id] => 2 [cb] => function: 0x1a3ede88 } [info] => qname ~ %w+.facebook.com AND src = 127.0.0.1/8 deny... [policy] => function: 0x1a3ede88 } ] ``` ``` -------------------------------- ### Cache Management and Download Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/daemon-scripting.rst Example demonstrating how to download cache data from a parent server using third-party Lua libraries. ```APIDOC ## Cache Management and Download ### Description Example demonstrating how to download cache data from a parent server using third-party Lua libraries to avoid cold-cache starts. ### Code Example ```lua local http = require('socket.http') local ltn12 = require('ltn12') local cache_size = 100*MB local cache_path = '/var/cache/knot-resolver' cache.open(cache_size, 'lmdb://' .. cache_path) if cache.count() == 0 then cache.close() -- download cache from parent http.request { url = 'http://parent/data.mdb', sink = ltn12.sink.file(io.open(cache_path .. '/data.mdb', 'w')) } -- reopen cache with 100M limit cache.open(cache_size, 'lmdb://' .. cache_path) end ``` ``` -------------------------------- ### Get Network Configuration in YAML Format Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/manager-client.md Reads the current network configuration subtree from the resolver and exports it to a file in YAML format. Uses the 'get' command with a specified path and output format. ```bash $ kresctl config get --yaml -p /network ./network-config.yaml ``` -------------------------------- ### Build Project Documentation Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/README.md Set up the build directory with documentation enabled and then build the documentation using Meson and Ninja. Ensure git submodules are initialized if necessary. ```sh $ meson setup build_dir -Ddoc=enabled $ ninja -C build_dir doc ``` -------------------------------- ### Example View Module Configuration Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/modules-view.rst Demonstrates various configurations for the view module, including whitelisting by TSIG key, blocking local clients, dropping specific subnets, applying RPZ rules, and a final catch-all drop for IPv4. ```lua -- Load modules modules = { 'view' } -- Whitelist queries identified by TSIG key view:tsig('\5mykey', policy.all(policy.PASS)) -- Block local IPv4 clients (ACL like) view:addr('127.0.0.1', policy.all(policy.DENY)) -- Block local IPv6 clients (ACL like) view:addr('::1', policy.all(policy.DENY)) -- Drop queries with suffix match for remote client view:addr('10.0.0.0/8', policy.suffix(policy.DROP, policy.todnames({'xxx'}))) -- RPZ for subset of clients view:addr('192.168.1.0/24', policy.rpz(policy.PASS, 'whitelist.rpz')) -- Do not try this - it will pollute cache and surprise you! -- view:addr('10.0.0.0/8', policy.all(policy.FORWARD('2001:DB8::1'))) -- Drop all IPv4 that hasn't matched view:addr('0.0.0.0/0', policy.all(policy.DROP)) ``` -------------------------------- ### Get Metrics (Prometheus) Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/user/manager-api.md Provides metrics in Prometheus format. Requires the `prometheus-client` Python package to be installed. ```APIDOC ## GET /metrics/prometheus ### Description Provides metrics in Prometheus format. The `prometheus-client` Python package needs to be installed. If not installed, it returns 404 (Not Found). ### Method GET ### Endpoint /metrics/prometheus ### Response #### Success Response (200) Metrics in Prometheus format. #### Error Response (404) Returned if the `prometheus-client` Python package is not installed. ``` -------------------------------- ### List Available Build Options Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/build.md Displays all configurable build options for the project. Run this after creating a build directory to see available customizations. ```bash $ meson setup build_dir $ meson configure build_dir ``` -------------------------------- ### Customize Build with Options Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/build.md Sets up a build directory with a specific option enabled. Use `-Doption=value` syntax to customize build behavior. ```bash $ meson setup build_dir -Ddoc=enabled ``` -------------------------------- ### Get Resolver Metrics Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/user/manager-client.md Retrieve aggregated metrics from the running resolver. Metrics can be exported to a file or printed to stdout. Install 'prometheus-client' for Prometheus format. ```bash kresctl metrics ./kres-metrics.json ``` ```bash kresctl metrics --prometheus ``` -------------------------------- ### Add and Monitor a Mirroring Policy Rule Source: https://github.com/cz-nic/knot-resolver/blob/master/modules/policy/README.rst This example demonstrates adding a policy rule that mirrors all queries to a specified IP address. It also shows how to retrieve the rule's ID and match count for monitoring purposes. ```lua local rule = policy.add(policy.all(policy.MIRROR('127.0.0.2'))) print(string.format('id: %d, matched queries: %d', rule.id, rule.count)) ``` -------------------------------- ### Query Custom HTTP /health Endpoint Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/modules-http-custom-services.rst Examples of querying the custom '/health' HTTP endpoint using curl, demonstrating both a standard GET request and a WebSocket connection. ```bash $ curl -k https://localhost:8453/health {"state":"up","uptime":0} ``` ```bash $ curl -k -i -N -H "Connection: Upgrade" -H "Upgrade: websocket" -H "Host: localhost:8453/health" -H "Sec-Websocket-Key: nope" -H "Sec-Websocket-Version: 13" https://localhost:8453/health HTTP/1.1 101 Switching Protocols upgrade: websocket sec-websocket-accept: eg18mwU7CDRGUF1Q+EJwPM335eM= connection: upgrade ?["up"]?["up"]?["up"] ``` -------------------------------- ### Generate setup.py for Compatibility Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/manager-dev-env.md This command generates the setup.py file, which is necessary for backwards compatibility with older Python tooling that does not support PEP-517. ```bash poe gen-setuppy ``` -------------------------------- ### Query Custom HTTP Endpoint Source: https://github.com/cz-nic/knot-resolver/blob/master/modules/http/custom_services.rst Examples of how to query the custom '/health' HTTP endpoint using curl. Demonstrates both a standard GET request for JSON data and a WebSocket connection for streaming. ```bash $ curl -k https://localhost:8453/health {"state":"up","uptime":0} $ curl -k -i -N -H "Connection: Upgrade" -H "Upgrade: websocket" -H "Host: localhost:8453/health" -H "Sec-Websocket-Key: nope" -H "Sec-Websocket-Version: 13" https://localhost:8453/health HTTP/1.1 101 Switching Protocols upgrade: websocket sec-websocket-accept: eg18mwU7CDRGUF1Q+EJwPM335eM= connection: upgrade ?["up"]?["up"]?["up"] ``` -------------------------------- ### Install Knot Resolver for Postinstall Tests Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/build.md Installs Knot Resolver, which is a prerequisite for running postinstall tests. The installed `kresd` binary in `$PATH` will be tested. ```bash $ ninja install -C build_dir ``` -------------------------------- ### Start Knot Resolver Daemon with Systemd Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/deployment-advanced-no-manager.md Manually start a single instance of the Knot Resolver daemon using systemd integration. This is the older method for starting the single-threaded resolver. ```bash $ sudo systemctl start kresd@1.service ``` -------------------------------- ### Enable Documentation Build Option Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/build.md Configures the build to include documentation and then builds it. Ensure documentation dependencies are met before enabling. ```bash $ meson configure build_dir -Ddoc=enabled $ ninja -C build_dir doc ``` -------------------------------- ### Add and Monitor a Mirror Policy Rule Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/modules-policy.rst This example demonstrates adding a policy rule that mirrors all queries to a specific IP address. It also shows how to retrieve the rule's unique identifier and track the number of matched queries. ```lua -- mirror all queries, keep handle so we can retrieve information later local rule = policy.add(policy.all(policy.MIRROR('127.0.0.2'))) -- we can print statistics about this rule any time later print(string.format('id: %d, matched queries: %d', rule.id, rule.count) ``` -------------------------------- ### Install mmdblua from LuaRocks Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/modules-http.rst Instructions for installing the optional mmdblua module from LuaRocks, including downloading GeoLite2-City.mmdb. ```bash $ luarocks --lua-version 5.1 install --server=https://luarocks.org/dev mmdblua $ curl -O https://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz $ gzip -d GeoLite2-City.mmdb.gz ``` -------------------------------- ### Load and List Stats Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/modules-stats.rst Loads the stats module and demonstrates how to list all available metrics or filter them by a prefix. Also shows how to fetch frequent queries and upstream server statistics. ```none modules.load('stats') -- Enumerate metrics > stats.list() [answer.cached] => 486178 [iterator.tcp] => 490 [answer.noerror] => 507367 [answer.total] => 618631 [iterator.udp] => 102408 [query.concurrent] => 149 -- Query metrics by prefix > stats.list('iter') [iterator.udp] => 105104 [iterator.tcp] => 490 -- Fetch most common queries > stats.frequent() [1] => { [type] => 2 [count] => 4 [name] => cz. } -- Fetch most common queries (sorted by frequency) > table.sort(stats.frequent(), function (a, b) return a.count > b.count end) -- Show recently contacted authoritative servers > stats.upstreams() [2a01:618:404::1] => { [1] => 26 -- RTT } [128.241.220.33] => { [1] => 31 - RTT } ``` -------------------------------- ### Example DNSSEC Validation Failure Log Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/config-logging-bogus.md This is an example of the error message that will be logged when a DNSSEC validation fails. ```text [dnssec] validation failure: dnssec-failed.org. DNSKEY ``` -------------------------------- ### Set Custom Root Server Hints Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/modules-hints.rst Replace current root hints with a new set of root hints. This example demonstrates setting hints for 'l.root-servers.net.' and 'm.root-servers.net.' with their respective IP addresses. ```lua > hints.root({ ['l.root-servers.net.'] = '199.7.83.42', ['m.root-servers.net.'] = '202.12.27.33' }) ``` -------------------------------- ### Example STUB Usage Source: https://github.com/cz-nic/knot-resolver/blob/master/modules/policy/README.rst Example of using the STUB action to obtain answers for reverse queries from a specific IP address. ```APIDOC ## policy.add(policy.suffix(policy.STUB('192.0.2.1@5335'), {todname('1.168.192.in-addr.arpa')})) ### Description Answers for reverse queries about the 192.168.1.0/24 subnet are obtained from IP address 192.0.2.1 port 5335. This disables DNSSEC validation. ``` -------------------------------- ### Set Custom Root Hints Source: https://github.com/cz-nic/knot-resolver/blob/master/modules/hints/README.rst Replace current root hints with a new set. This example demonstrates setting hints for 'l.root-servers.net.' and 'm.root-servers.net.' and shows the expected output format. ```lua > hints.root({ ['l.root-servers.net.'] = '199.7.83.42', ['m.root-servers.net.'] = '202.12.27.33' }) [l.root-servers.net.] => { [1] => 199.7.83.42 } [m.root-servers.net.] => { [1] => 202.12.27.33 } ``` -------------------------------- ### Example Custom Action: Fake A Record Source: https://github.com/cz-nic/knot-resolver/blob/master/modules/policy/README.rst An example of a custom action function that generates a fake A record for a DNS query. ```APIDOC ## fake_A_record(state, req) ### Description Custom action which generates fake A record. ### Parameters - **state** (:c:type:`kr_layer_state`) - Request processing state. - **req** (:c:type:`kr_request`) - Current DNS request structure. ### Return Value - Returns :data:`kres.DONE` if the fake A record is successfully created. - Returns ``nil`` if the answer cannot be ensured. - Returns the original `state` if the query type is not A. ``` -------------------------------- ### Get Help for Meson Test Commands Source: https://github.com/cz-nic/knot-resolver/blob/master/tests/README.rst Display help information for the `meson test` command, listing available options and arguments for managing test execution. ```bash $ meson test -C build_dir --help ``` -------------------------------- ### Load and Configure HTTP Module Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/modules-http.rst Loads the HTTP module with default settings and optionally configures it with a GeoIP database. This is the initial setup for enabling HTTP services. ```lua modules.load('http') http.config({ geoip = 'GeoLite2-City.mmdb', -- e.g. https://dev.maxmind.com/geoip/geoip2/geolite2/ -- and install mmdblua library }) ``` -------------------------------- ### Enable DNS64 with Default Prefix Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/config-dns64.md Enable DNS64 using the default well-known prefix `64:ff9b::/96`. This is the simplest way to activate the feature. ```yaml dns64: enable: true ``` -------------------------------- ### View Configuration with Tags and Options Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/config-views.md Apply specific policy tags and options to views based on client subnets. This example applies 'malware' and 'localnames' tags and disables DNS64 for a specific IPv6 subnet. ```yaml views: # Apply `malware` and `localnames` rules to these clients and turn off dns64. # We'd also need to use these tags inside local-data: to really change anything. - subnets: [ 2001:db8:1::/56 ] tags: [ malware, localnames ] options: dns64: false ``` -------------------------------- ### Start Asynchronous Coroutine Source: https://github.com/cz-nic/knot-resolver/blob/master/daemon/bindings/event.rst Use `worker.coroutine` to start a new coroutine. The coroutine can perform I/O or run timers without blocking the main thread. ```lua worker.coroutine(function () for i = 0, 10 do print('executing', i) worker.sleep(1) end end) ``` -------------------------------- ### Add Whitelist and Blocklist Policies Source: https://github.com/cz-nic/knot-resolver/blob/master/modules/policy/README.rst Use policy.PASS for whitelisting specific domains and policy.DENY for blocking subdomains. Ensure more specific rules precede generic ones. ```lua -- Whitelist 'good.example.com' policy.add(policy.pattern(policy.PASS, todname('good.example.com.'))) -- Block all names below example.com policy.add(policy.suffix(policy.DENY, {todname('example.com.')})) ``` -------------------------------- ### Start Knot Resolver Service Source: https://github.com/cz-nic/knot-resolver/blob/master/README.md Use this command to start the Knot Resolver service using systemd. It requires no initial configuration to run on localhost. ```bash # systemctl start knot-resolver ``` -------------------------------- ### Slice Function Example Source: https://github.com/cz-nic/knot-resolver/blob/master/modules/policy/README.rst Demonstrates how to use the slice function to split the DNS namespace and forward different queries to different targets using policy.TLS_FORWARD. ```lua policy.slice(slice_func, action[, action[, ...]) ``` -------------------------------- ### Install PoeThePoet Globally Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/manager-dev-env.md Install PoeThePoet system-wide for easier command invocation. This allows you to run 'poe' commands without needing to specify the path. ```bash pip install poethepoet ``` -------------------------------- ### Configure Worker Processes Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/upgrading-to-6.md To start the resolver with multiple worker processes, set the `/workers` directive in the configuration file. Previously, this required manually starting multiple `kresd@` services. ```text set `/workers` to 4 in the config file ``` ```bash systemctl start kresd@{1,2,3,4} ``` -------------------------------- ### Start kresd Instances with Custom Names Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/systemd-multiinst.rst Start kresd instances using custom identifiers instead of numbers. These identifiers are exposed to kresd via the SYSTEMD_INSTANCE environment variable. ```bash $ systemctl start kresd@dns1 $ systemctl start kresd@dns2 $ systemctl start kresd@tls $ systemctl start kresd@doh ``` -------------------------------- ### Configure and Add Hints Source: https://github.com/cz-nic/knot-resolver/blob/master/modules/hints/README.rst Load hints after the iterator to ensure they take precedence. Add custom hosts files and override root hints. Custom hints can also be added directly. ```lua modules = { 'hints > iterate' } hints.add_hosts('hosts.custom') hints.root({ ['j.root-servers.net.'] = { '2001:503:c27::2:30', '192.58.128.30' } }) hints['foo.bar'] = '127.0.0.1' ``` -------------------------------- ### C Module Background Thread Example Source: https://github.com/cz-nic/knot-resolver/blob/master/modules/README.rst Demonstrates how a C module can create and manage a background thread for tasks like observing and publishing query resolution data. Ensure proper thread joining during deinitialization. ```c static void* observe(void *arg) { /* ... do some observing ... */ } int mymodule_init(struct kr_module *module) { /* Create a thread and start it in the background. */ pthread_t thr_id; int ret = pthread_create(&thr_id, NULL, &observe, NULL); if (ret != 0) { return kr_error(errno); } /* Keep it in the thread */ module->data = thr_id; return kr_ok(); } int mymodule_deinit(struct kr_module *module) { /* ... signalize cancellation ... */ void *res = NULL; pthread_t thr_id = (pthread_t) module->data; int ret = pthread_join(thr_id, res); if (ret != 0) { return kr_error(errno); } return kr_ok(); } ``` -------------------------------- ### Custom HTTP Endpoint Example Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/modules-http-custom-services.rst This example shows how to register a custom HTTP endpoint '/health' for the 'webmgmt' kind. It includes a Lua function to handle HTTP requests and a separate handler for WebSocket connections. ```APIDOC ## Custom HTTP Endpoint '/health' ### Description Registers a custom HTTP endpoint that responds with a JSON object indicating the service state and uptime. It also supports WebSocket connections for streaming status updates. ### Method GET, WebSocket ### Endpoint /health ### Parameters None ### Request Example (HTTP GET) ```bash curl -k https://localhost:8453/health ``` ### Response Example (HTTP GET) ```json {"state":"up","uptime":0} ``` ### Request Example (WebSocket) ```bash curl -k -i -N -H "Connection: Upgrade" -H "Upgrade: websocket" -H "Host: localhost:8453/health" -H "Sec-Websocket-Key: nope" -H "Sec-Websocket-Version: 13" https://localhost:8453/health ``` ### Response Example (WebSocket) ``` HTTP/1.1 101 Switching Protocols upgrade: websocket sec-websocket-accept: eg18mwU7CDRGUF1Q+EJwPM335eM= connection: upgrade ?["up"]?["up"]?["up"] ``` ``` -------------------------------- ### Run Unit Tests with Meson Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/build.md Compiles the project and then runs the unit test suite. Unit tests depend on cmocka and are enabled by default if cmocka is found. ```bash $ ninja -C build_dir $ meson test -C build_dir --suite unit ``` -------------------------------- ### Interactive Prompt Examples Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/dev/config-lua-overview.md Demonstrates interaction with Knot Resolver via its interactive prompt, including executing commands and observing output. ```APIDOC ## Interactive Configuration Examples ### Description Examples of interacting with Knot Resolver through its command-line interface, showing commands entered by the user and the resolver's responses. ### Interactive Prompt Usage ```lua > -- this is a comment entered into interactive prompt > -- comments have no effect here > -- the next line shows a command entered interactively and its output > log_level() 'notice' > -- the previous line without > character is output from log_level() command ``` ### Listing Loaded Modules ```lua > modules.list() { 'iterate', 'validate', 'cache', 'ta_update', 'ta_signal_query', 'policy', 'priming', 'detect_time_skew', 'detect_time_jump', 'ta_sentinel', 'edns_keepalive', 'refuse_nord', 'watchdog', } ``` ``` -------------------------------- ### Get Metrics (JSON) Source: https://github.com/cz-nic/knot-resolver/blob/master/doc/user/manager-api.md Provides aggregated metrics in JSON format. ```APIDOC ## GET /metrics/json ### Description Provides aggregated metrics in JSON format. ### Method GET ### Endpoint /metrics/json ### Response #### Success Response (200) Aggregated metrics in JSON format. ```