### Run Unbound Server with Custom Configuration Source: https://github.com/nlnetlabs/unbound/blob/master/pythonmod/doc/examples/example6.md Starts the Unbound server in debug and verbose mode using a specified configuration file. This is useful for testing custom setups and observing server behavior. ```bash root@localhost$ unbound -dv -c ./test-inplace_callbacks.conf ``` -------------------------------- ### Unbound Anchor Setup Example Source: https://github.com/nlnetlabs/unbound/blob/master/doc/unbound-anchor.rst Example of how to use unbound-anchor in init scripts to provide or update the root anchor, followed by starting the unbound DNS server. This demonstrates the typical workflow for setting up DNSSEC validation. ```text # in the init scripts. # provide or update the root anchor (if necessary) unbound-anchor -a "@UNBOUND_ROOTKEY_FILE@" # Please note usage of this root anchor is at your own risk # and under the terms of our LICENSE (see source). # # start validating resolver # the unbound.conf contains: # auto-trust-anchor-file: "@UNBOUND_ROOTKEY_FILE@" unbound -c unbound.conf ``` -------------------------------- ### Run Unbound Server for Testing Source: https://github.com/nlnetlabs/unbound/blob/master/libunbound/python/doc/examples/example1.md This command starts the Unbound server in debug and verbose mode, using a specified configuration file for testing purposes. Ensure the configuration file is correctly set up for your testing environment. ```bash root@localhost>unbound -dv -c ./test-log.conf ``` -------------------------------- ### Initialize Czech-English Dictionary from File Source: https://github.com/nlnetlabs/unbound/blob/master/pythonmod/doc/examples/example4.md Initializes the Czech-English and English-Czech dictionaries by reading word pairs from 'examples/dict_data.txt'. Each line in the file should contain two words separated by a tab. Lines starting with '#' are ignored. The function logs the initialization process and ensures the file is closed. ```python import os cz_dict = {} en_dict = {} def init(id, cfg): log_info("pythonmod: dict init") f = open("examples/dict_data.txt", "r") try: for line in f: if line.startswith('#'): continue itm = line.split("\t", 3) if len(itm) < 2: continue en,cs = itm[0:2] if not (cs in cz_dict): cz_dict[cs] = [en] # [cs] = en else: cz_dict[cs].append(en) # [cs] = en if not (en in en_dict): en_dict[en] = [cs] # [en] = cs else: en_dict[en].append(cs) # [en] = cs finally: f.close() return True ``` -------------------------------- ### Start Unbound Server Command Source: https://github.com/nlnetlabs/unbound/blob/master/doc/unbound.conf.rst Command to start the Unbound server using a specified configuration file. Ensure the configuration file path is correct. ```bash $ unbound -c @ub_conf_file@ ``` -------------------------------- ### RPZ Example: NXDOMAIN Reply Source: https://github.com/nlnetlabs/unbound/blob/master/doc/unbound.conf.rst An example RPZ zone entry that causes a NXDOMAIN reply for queries matching 'example.com'. ```text example.com CNAME . ``` -------------------------------- ### Compile Unbound Source: https://github.com/nlnetlabs/unbound/blob/master/README.md Compile and install Unbound from source. Ensure C toolchain, OpenSSL, libexpat, flex, and bison are installed. ```bash ./configure && make && make install ``` -------------------------------- ### Unbound Module Configuration Example Source: https://github.com/nlnetlabs/unbound/blob/master/doc/unbound.conf.rst Example of configuring the IPsec module within the 'module-config' directive. Requires Unbound to be compiled with '--enable-ipsecmod'. ```text module-config: "ipsecmod validator iterator" ``` -------------------------------- ### Minimal Unbound Configuration Example Source: https://github.com/nlnetlabs/unbound/blob/master/doc/unbound.conf.rst A basic unbound.conf file demonstrating essential server settings. This includes directory, username, chroot, pidfile, and network interface configurations. ```text # unbound.conf(5) config file for unbound(8). server: directory: "@UNBOUND_RUN_DIR@" username: unbound # make sure unbound can access entropy from inside the chroot. # e.g. on linux the use these commands (on BSD, devfs(8) is used): # mount --bind -n /dev/urandom @UNBOUND_RUN_DIR@/dev/urandom # and mount --bind -n /dev/log @UNBOUND_RUN_DIR@/dev/log chroot: "@UNBOUND_CHROOT_DIR@" # logfile: "@UNBOUND_RUN_DIR@/unbound.log" #uncomment to use logfile. pidfile: "@UNBOUND_PIDFILE@" # verbosity: 1 # uncomment and increase to get more logging. # listen on all interfaces, answer queries from the local subnet. interface: 0.0.0.0 interface: ::0 access-control: 10.0.0.0/8 allow access-control: 2001:db8::/64 allow ``` -------------------------------- ### Unbound Memory Control Example Source: https://github.com/nlnetlabs/unbound/blob/master/doc/unbound.conf.rst This example demonstrates settings to reduce Unbound's memory usage. It is suitable for environments with limited memory, but may impact performance and limit support for very large data or high TCP loads. ```text # example settings that reduce memory usage server: num-threads: 1 outgoing-num-tcp: 1 # this limits TCP service, uses less buffers. incoming-num-tcp: 1 outgoing-range: 60 # uses less memory, but less performance. msg-buffer-size: 8192 # note this limits service, 'no huge stuff'. msg-cache-size: 100k msg-cache-slabs: 1 rrset-cache-size: 100k rrset-cache-slabs: 1 infra-cache-numhosts: 200 infra-cache-slabs: 1 key-cache-size: 100k key-cache-slabs: 1 neg-cache-size: 10k num-queries-per-thread: 30 target-fetch-policy: "2 1 0 0 0 0" harden-large-queries: "yes" harden-short-bufsize: "yes" ``` -------------------------------- ### Example DNS Query for Translation (Czech to English) Source: https://github.com/nlnetlabs/unbound/blob/master/pythonmod/doc/examples/example4.md Shows an example of querying for a Czech-to-English translation. The query `nic.cs._dict_.cz` asks for the English translation of the Czech word 'nic'. The response includes multiple English equivalents. ```bash >>>dig TXT @127.0.0.1 nic.cs._dict_.cz ``` -------------------------------- ### Setup Unbound Control Source: https://github.com/nlnetlabs/unbound/blob/master/doc/unbound-control.rst Generates self-signed certificates and private keys for server and client communication with unbound-control. Run this script with appropriate permissions. ```bash sudo -u unbound unbound-control-setup ``` -------------------------------- ### Unbound Server Test Output Example Source: https://github.com/nlnetlabs/unbound/blob/master/libunbound/python/doc/examples/example1.md This is an example of the output generated when running the Unbound server with the Python module enabled for logging. It shows server messages, query details, and the structure of DNS replies, including security flags and resource records. ```text [1231790168] unbound[7941:0] info: response for [1231790168] unbound[7941:0] info: reply from 192.5.6.31#53 [1231790168] unbound[7941:0] info: query response was ANSWER [1231790168] unbound[7941:0] info: pythonmod: operate called, id: 1, event:module_event_moddone ---------------------------------------------------------------------------------------------------- Query: f.gtld-servers.NET., type: AAAA (28), class: IN (1) ---------------------------------------------------------------------------------------------------- Return reply :: flags: 8080, QDcount: 1, Security:0, TTL=86400 qinfo :: qname: ['f', 'gtld-servers', 'NET', ''] f.gtld-servers.NET., qtype: AAAA, qclass: IN Reply: 0 : ['gtld-servers', 'NET', ''] gtld-servers.NET. flags: 0000 type: SOA (6) class: IN (1) 0 : TTL= 86400 0x00 | 00 3A 02 41 32 05 4E 53 54 4C 44 03 43 4F 4D 00 05 | . : . A 2 . N S T L D . C O M . . 0x10 | 05 6E 73 74 6C 64 0C 76 65 72 69 73 69 67 6E 2D 67 | . n s t l d . v e r i s i g n - g 0x20 | 67 72 73 03 43 4F 4D 00 77 74 2D 64 00 00 0E 10 00 | g r s . C O M . w t - d . . . . . 0x30 | 00 00 03 84 00 12 75 00 00 01 51 80 | . . . . . . u . . . Q . ``` -------------------------------- ### Tool Installation Script for Android/iOS Source: https://github.com/nlnetlabs/unbound/blob/master/README-Travis.md This `before_script` section in the Travis configuration executes platform-specific tool installation scripts. It runs `install_tools.sh` for Android builds and `install_tools.sh` for iOS builds, ensuring necessary utilities like curl, tar, and Java are available. ```yaml before_script: - | if [ "$TEST_ANDROID" = "yes" ]; then ./contrib/android/install_tools.sh elif [ "$TEST_IOS" = "yes" ]; then ./contrib/ios/install_tools.sh fi ``` -------------------------------- ### Configure Unbound Module Configuration Source: https://github.com/nlnetlabs/unbound/blob/master/doc/unbound.conf.rst Example of how to include the cachedb module in the module-config directive. This module must be compiled into the daemon with --enable-cachedb. ```text module-config: "validator cachedb iterator" ``` -------------------------------- ### Enable DNS64 Module Source: https://github.com/nlnetlabs/unbound/blob/master/doc/unbound.conf.rst To enable the DNS64 module, it must be included in the module-config directive. This example shows its placement alongside other modules. ```text module-config: "dns64 validator iterator" ``` -------------------------------- ### Compile Unbound Library Source: https://github.com/nlnetlabs/unbound/blob/master/pythonmod/doc/install.md Use these commands to download, configure, and compile the Unbound library. Ensure you have Python, SWIG, and GNU make installed. ```default > tar -xzf unbound-1.1.1-py.tar.gz > cd unbound-1.1.1 > ./configure --with-pythonmodule > make ``` -------------------------------- ### Initialize Dictionary Module in Python Source: https://github.com/nlnetlabs/unbound/blob/master/pythonmod/doc/examples/example4.md Initializes the dictionary module by loading translation data from a text file. The file is expected to contain records in 'word [tab] translation' format. This function is part of the Unbound Python module setup. ```python def init(id, cfg): log_info("pythonmod: dict init") f = open("examples/dict_data.txt", "r") ... ``` -------------------------------- ### Example DNS Query for Translation (English to Czech) Source: https://github.com/nlnetlabs/unbound/blob/master/pythonmod/doc/examples/example4.md Demonstrates how to query the Unbound server for an English-to-Czech translation using a specific DNS query format. The query `a.bar.fly.en._dict_.cz` requests the translation of 'a bar fly' from English to Czech. ```bash >>>dig TXT @127.0.0.1 a.bar.fly.en._dict_.cz ``` -------------------------------- ### Test Unbound Python Module Source: https://github.com/nlnetlabs/unbound/blob/master/pythonmod/doc/install.md After successful compilation, navigate to the pythonmod directory and run 'make sudo' (or 'make test'/'make suexec') to test the extension module. This starts an unbound server for testing. ```default > cd pythonmod > make sudo # or "make test" or "make suexec" ``` -------------------------------- ### Example DNS Query for Standard Resolution Source: https://github.com/nlnetlabs/unbound/blob/master/pythonmod/doc/examples/example4.md Illustrates a standard DNS query for an A record to verify that Unbound continues to function as a regular DNS resolver alongside the Python module. This query `www.nic.cz` retrieves the IP address for the specified domain. ```bash >>>dig A @127.0.0.1 www.nic.cz ``` -------------------------------- ### Cross-compile Unbound for Windows Source: https://github.com/nlnetlabs/unbound/blob/master/winrc/README.txt Steps for cross-compiling Unbound on a Linux system to produce Windows executables. This involves installing MinGW packages and then running the configure and make commands. It also covers options for creating dynamically linked executables and statically linked executables, including using `makedist.sh` to create a Windows installer. ```bash $ mingw32-configure $ make $ mkdir /home/user/installdir $ make install DESTDIR=/home/user/installdir ``` ```bash ./makedist.sh -w ``` -------------------------------- ### Complete Python Source Code for Unbound Module Source: https://github.com/nlnetlabs/unbound/blob/master/pythonmod/doc/examples/example6.md Provides the complete Python source code for the Unbound module, intended to be used with the 'inplace_callbacks.py' configuration. ```python import sys def init(id, cfg): # setup return True def operate(id, event, arg): # process event if event == 'startup': print('Unbound started') elif event == 'query': qname = arg['qname'] qtype = arg['qtype'] print('Received query for %s of type %s' % (qname, qtype)) # Example: Add an EDNS option if 'opt' in arg: for opt in arg['opt']: if opt[0] == 65002: opt[1] = b'\xde\xad\xbe\xef' print('Set EDNS option 65002 to 0xdeadbeef') return 0 elif event == 'shutdown': print('Unbound shutting down') return 0 def deinit(id): # cleanup return True ``` -------------------------------- ### Option Management Commands Source: https://github.com/nlnetlabs/unbound/blob/master/doc/unbound-control.rst Commands to get and set Unbound configuration options dynamically. ```APIDOC ## set_option *opt: val* ### Description Set an option to a given value without reloading the configuration, thus not flushing the cache. The option name must end with a colon, and there must be whitespace between the option and the value. Note that not all options may take effect when set this way, and changes are not written to the config file. Some options may not be supported. ### Method unbound-control ### Endpoint set_option *opt: val* ### Parameters #### Query Parameters - **opt** (string) - Required - The name of the option to set, ending with a colon. - **val** (string) - Required - The value to set for the option. ``` ```APIDOC ## get_option *opt* ### Description Retrieve the current value of a specified option. The option name should be provided without a trailing colon. The value is printed to the output. If the value is an empty string, nothing is printed. Errors are indicated by 'error ...'. For some options, a list of values may be printed, one per line. This command reflects options from the config file as modified by `set_option`, but may not show overrides or results from other dynamic commands. ### Method unbound-control ### Endpoint get_option *opt* ### Parameters #### Query Parameters - **opt** (string) - Required - The name of the option to retrieve (without a trailing colon). ``` -------------------------------- ### Unbound Configuration for Python Module Source: https://github.com/nlnetlabs/unbound/blob/master/pythonmod/doc/examples/example4.md Configures the Unbound server to enable and use the Python module for the language dictionary. This involves specifying the module configuration and the path to the Python script. ```unbound-config module-config: "validator python iterator" python-script: "./examples/dict.py" ``` -------------------------------- ### Deinitialize Dictionary Module Source: https://github.com/nlnetlabs/unbound/blob/master/pythonmod/doc/examples/example4.md Handles the deinitialization of the dictionary module. It logs the deinitialization event and returns `True` to indicate successful completion. ```python def deinit(id): log_info("pythonmod: dict deinit") return True ``` -------------------------------- ### Unbound Log Format Example Source: https://github.com/nlnetlabs/unbound/blob/master/doc/unbound.conf.rst This snippet shows the expected format for log messages when logging to a file. It includes the timestamp, process ID, thread ID, log type, and the message content. ```text [seconds since 1970] unbound[pid:tid]: type: message. ``` -------------------------------- ### Unbound Module Initialization and Deinitialization (Python) Source: https://github.com/nlnetlabs/unbound/blob/master/pythonmod/doc/examples/example6.md Provides functions for initializing and deinitializing the Unbound module. The `init` function includes a note about backward compatibility, suggesting it should be omitted if `init_standard` is present. The `deinit` function is a simple placeholder. ```python def init(id, cfg): """ Previous version of the init function. ..note:: This function is still supported for backwards compatibility when the init_standard function is missing. When init_standard is present this function SHOULD be omitted to avoid confusion to the reader. """ return True def deinit(id): return True ``` -------------------------------- ### Enable Python Module in Unbound Configuration Source: https://github.com/nlnetlabs/unbound/blob/master/pythonmod/doc/examples/example6.md Configures the Unbound server to use the Python module. This involves specifying 'python' in the module-config directive and providing a valid path to the Python script. ```unbound-config module-config: "validator python iterator" python-script: "./examples/inplace_callbacks.py" ``` -------------------------------- ### Perform DNS Lookups Concurrently using Unbound Python Module Source: https://github.com/nlnetlabs/unbound/blob/master/libunbound/python/doc/examples/example2.md This Python script demonstrates concurrent DNS lookups from multiple threads. It utilizes the unbound Python module to resolve A records for specified hostnames. Ensure the 'unbound' Python module is installed and a '/etc/resolv.conf' file is present for name resolution. ```python #!/usr/bin/python from unbound import ub_ctx, RR_TYPE_A, RR_CLASS_IN from threading import Thread ctx = ub_ctx() ctx.resolvconf("/etc/resolv.conf") class LookupThread(Thread): def __init__(self,ctx, name): Thread.__init__(self) self.ctx = ctx self.name = name def run(self): print "Thread lookup started:",self.name status, result = self.ctx.resolve(self.name, RR_TYPE_A, RR_CLASS_IN) if status == 0 and result.havedata: print " Result:",self.name,":", result.data.address_list threads = [] for name in ["www.fit.vutbr.cz","www.vutbr.cz","www.google.com"]: thread = LookupThread(ctx, name) thread.start() threads.append(thread) for thread in threads: thread.join() ``` -------------------------------- ### Get Statistics Source: https://github.com/nlnetlabs/unbound/blob/master/doc/unbound-control.rst Displays statistic counters for Unbound, without resetting them. ```bash unbound-control stats_noreset ``` -------------------------------- ### Unbound Python: Inplace Local Callback Source: https://github.com/nlnetlabs/unbound/blob/master/pythonmod/doc/examples/example6.md A callback function for when Unbound answers using local data or a CHAOS reply. It receives similar parameters to other inplace callbacks and should return True on success or False on failure. This example simply logs the event. ```python def inplace_local_callback(qinfo, qstate, rep, rcode, edns, opt_list_out, region, **kwargs): """ Function that will be registered as an inplace callback function. It will be called when answering from local data. :param qinfo: query_info struct; :param qstate: module qstate. None; :param rep: reply_info struct; :param rcode: return code for the query; :param edns: edns_data sent from the client side. The list with the EDNS options is accessible through edns.opt_list. It SHOULD NOT be altered; :param opt_list_out: the list with the EDNS options that will be sent as a reply. It can be populated with EDNS options; :param region: region to allocate temporary data. :param **kwargs: Dictionary that may contain parameters added in a future release. Current parameters: ``repinfo``: Reply information for a communication point (comm_reply). :return: True on success, False on failure. """ log_info("python: called back while replying with local data or chaos" " reply.") return True ``` -------------------------------- ### Reload and Terminate Unbound using PID File Source: https://github.com/nlnetlabs/unbound/blob/master/doc/unbound.conf.rst Demonstrates how to reload Unbound's configuration or gracefully terminate the process using the PID file. Ensure the PID file path is correctly configured. ```text kill -HUP `cat @UNBOUND_PIDFILE@` ``` ```text kill -TERM `cat @UNBOUND_PIDFILE@` ``` -------------------------------- ### Python MX, A, and NS Record Lookup with pyUnbound Source: https://github.com/nlnetlabs/unbound/blob/master/libunbound/python/doc/examples/example8.md This Python script uses the pyUnbound library to perform DNS lookups for MX, A, and NS records. It initializes an unbound context, reads resolver configuration, and then queries for specific record types for 'nic.cz'. The script prints the raw RDATA and parsed data for each record type, demonstrating how to access different fields like MX priority, addresses, and NS hostnames. ```python #!/usr/bin/python # vim:fileencoding:utf-8 # # Lookup for MX and NS records # import unbound ctx = unbound.ub_ctx() ctx.resolvconf("/etc/resolv.conf") status, result = ctx.resolve("nic.cz", unbound.RR_TYPE_MX, unbound.RR_CLASS_IN) if status == 0 and result.havedata: print "Result:" print " raw data:", result.data for k in result.data.mx_list: print " priority:%d address:%s" % k status, result = ctx.resolve("nic.cz", unbound.RR_TYPE_A, unbound.RR_CLASS_IN) if status == 0 and result.havedata: print "Result:" print " raw data:", result.data for k in result.data.address_list: print " address:%s" % k status, result = ctx.resolve("nic.cz", unbound.RR_TYPE_NS, unbound.RR_CLASS_IN) if status == 0 and result.havedata: print "Result:" print " raw data:", result.data for k in result.data.domain_list: print " host: %s" % k ``` -------------------------------- ### Get Statistics with Reset Source: https://github.com/nlnetlabs/unbound/blob/master/doc/unbound-control.rst Displays statistic counters for Unbound and resets them after retrieval. ```bash unbound-control stats ``` -------------------------------- ### Resolve Host Address using pyUnbound Source: https://github.com/nlnetlabs/unbound/blob/master/libunbound/python/doc/examples/example1a.md This Python script demonstrates basic DNS resolution using the pyUnbound library. It initializes an unbound context, loads resolver configuration from /etc/resolv.conf, and then resolves the A record for 'www.google.com'. The script handles successful resolutions by printing IP addresses and reports errors if resolution fails. It leverages automatic memory management provided by pyUnbound. ```python #!/usr/bin/python import unbound ctx = unbound.ub_ctx() ctx.resolvconf("/etc/resolv.conf") status, result = ctx.resolve("www.google.com") if status == 0 and result.havedata: print "Result.data:", result.data.address_list elif status != 0: print "Resolve error:", unbound.ub_strerror(status) ``` -------------------------------- ### Initialize Unbound with Standard Callbacks Source: https://github.com/nlnetlabs/unbound/blob/master/pythonmod/doc/examples/example6.md This initialization function registers several inplace callback functions for different stages of DNS query processing: reply, cache reply, local data reply, and SERVFAIL reply. It uses the provided environment and module ID to register these callbacks. It returns False if any registration fails. ```python def init_standard(id, env): """ New version of the init function. The function's signature is the same as the C counterpart and allows for extra functionality during init. ..note:: This function is preferred by unbound over the old init function. ..note:: The previously accessible configuration options can now be found in env.cfg. """ log_info("python: inited script {}".format(mod_env['script'])) # Register the inplace_reply_callback function as an inplace callback # function when answering a resolved query. if not register_inplace_cb_reply(inplace_reply_callback, env, id): return False # Register the inplace_cache_callback function as an inplace callback # function when answering from cache. if not register_inplace_cb_reply_cache(inplace_cache_callback, env, id): return False # Register the inplace_local_callback function as an inplace callback # function when answering from local data. if not register_inplace_cb_reply_local(inplace_local_callback, env, id): return False # Register the inplace_servfail_callback function as an inplace callback # function when answering with SERVFAIL. if not register_inplace_cb_reply_servfail(inplace_servfail_callback, env, id): return False # Register the inplace_query_callback function as an inplace callback ``` -------------------------------- ### Registering In-Place Callbacks for Unbound Queries (Python) Source: https://github.com/nlnetlabs/unbound/blob/master/pythonmod/doc/examples/example6.md This snippet demonstrates the registration of callback functions for handling DNS queries and responses within the Unbound DNS server. It includes callbacks for initial query sending, response reception, and EDNS parsing. Proper registration is crucial for the module's functionality. ```python if not register_inplace_cb_query(inplace_query_callback, env, id): return False # Register the inplace_edns_back_parsed_call function as an inplace callback # for when a reply is received from a backend server. if not register_inplace_cb_query_response(inplace_query_response_callback, env, id): return False # Register the inplace_edns_back_parsed_call function as an inplace callback # for when EDNS is parsed on a reply from a backend server. if not register_inplace_edns_back_parsed_call(inplace_edns_back_parsed_call, env, id): return False return True ``` -------------------------------- ### Perform Asynchronous DNS Lookup with Unbound (Python) Source: https://github.com/nlnetlabs/unbound/blob/master/libunbound/python/doc/examples/example3.md This snippet demonstrates an asynchronous DNS lookup using the unbound Python module. It initializes a context, configures it to read from resolv.conf, and then initiates an asynchronous resolution for 'www.seznam.cz'. A callback function is provided to process the results, and the main loop continuously processes events until the lookup is complete or an error occurs. The `resolve_async` method allows passing arbitrary Python objects to the callback. ```python #!/usr/bin/python import time import unbound ctx = unbound.ub_ctx() ctx.resolvconf("/etc/resolv.conf") def call_back(my_data,status,result): print "Call_back:", my_data if status == 0 and result.havedata: print "Result:", result.data.address_list my_data['done_flag'] = True my_data = {'done_flag':False,'arbitrary':"object"} status, async_id = ctx.resolve_async("www.seznam.cz", my_data, call_back, unbound.RR_TYPE_A, unbound.RR_CLASS_IN) while (status == 0) and (not my_data['done_flag']): status = ctx.process() time.sleep(0.1) if (status != 0): print "Resolve error:", unbound.ub_strerror(status) ``` -------------------------------- ### Unbound Resolv.conf Loading (C) Source: https://github.com/nlnetlabs/unbound/blob/master/doc/libunbound.rst Reads nameserver information from a specified file, typically `/etc/resolv.conf`. This allows Unbound to use the nameservers listed in the file as caching proxies, overriding the default behavior of querying root servers. ```c int ub_ctx_resolvconf(struct ub_ctx *ctx, const char *filename); ``` -------------------------------- ### Configure Unbound incoming TCP buffers Source: https://github.com/nlnetlabs/unbound/blob/master/doc/unbound.conf.rst Set the number of incoming TCP buffers to allocate per thread for client queries. Increase this value for larger installations. ```unbound.conf incoming-num-tcp: 20 ``` -------------------------------- ### Unbound Configuration File Loading (C) Source: https://github.com/nlnetlabs/unbound/blob/master/doc/libunbound.rst Function to load Unbound configuration from a specified file. `ub_ctx_config` reads configuration settings, similar to `unbound.conf`. This function is thread-safe only if a single `ub_ctx` instance exists; otherwise, external synchronization is required. ```c int ub_ctx_config(struct ub_ctx *ctx, const char *fname); ``` -------------------------------- ### Inplace Callback: SERVFAIL Reply Source: https://github.com/nlnetlabs/unbound/blob/master/pythonmod/doc/examples/example6.md This callback is triggered when Unbound encounters a SERVFAIL condition. It allows for custom actions or logging when a query fails. ```APIDOC ## POST /nlnetlabs/unbound/inplace_callback/reply_servfail ### Description This callback function is registered to handle situations where Unbound must reply with a SERVFAIL (Server Failure) status. It provides access to query details and allows modification of the response, such as adding EDNS options. ### Method REGISTER_INPLACE_CALLBACK ### Endpoint N/A (Callback registration) ### Parameters #### Callback Function Prototype ```python def inplace_servfail_callback(qinfo, qstate, rep, rcode, edns, opt_list_out, region, **kwargs): """ Function that will be registered as an inplace callback function. It will be called when answering with SERVFAIL. :param qinfo: query_info struct; :param qstate: module qstate. If not None the relevant opt_lists are available here; :param rep: reply_info struct. None; :param rcode: return code for the query. LDNS_RCODE_SERVFAIL; :param edns: edns_data to be sent to the client side. If qstate is None edns.opt_list contains the EDNS options sent from the client side. It SHOULD NOT be altered; :param opt_list_out: the list with the EDNS options that will be sent as a reply. It can be populated with EDNS options; :param region: region to allocate temporary data. Needs to be used when we want to append a new option to opt_list_out. :param **kwargs: Dictionary that may contain parameters added in a future release. Current parameters: ``repinfo``: Reply information for a communication point (comm_reply). :return: True on success, False on failure. """ ``` #### Registration Example ```python if not register_inplace_cb_reply_servfail(inplace_servfail_callback, env, id): log_info("python: Could not register inplace callback function.") ``` ### Request Example N/A (Callback function definition) ### Response #### Success Response - **bool** (boolean) - True on successful execution of the callback, False otherwise. ``` -------------------------------- ### Configure Unbound outgoing TCP buffers Source: https://github.com/nlnetlabs/unbound/blob/master/doc/unbound.conf.rst Set the number of outgoing TCP buffers to allocate per thread for queries to authoritative servers. Increase this value for larger installations. ```unbound.conf outgoing-num-tcp: 20 ``` -------------------------------- ### Alternate Primary Syntax Source: https://github.com/nlnetlabs/unbound/blob/master/doc/unbound.conf.rst Alternative syntax for specifying the primary server for zone transfers. ```unbound.conf master: 192.0.2.1 ``` -------------------------------- ### Configuring Local Data Shorthand for PTR Records Source: https://github.com/nlnetlabs/unbound/blob/master/doc/unbound.conf.rst Provides a shorthand for configuring local PTR records, mapping an IP address to a hostname. This simplifies the setup for reverse DNS lookups. ```text "192.0.2.4 www.example.com" ``` ```text "2001:db8::4 7200 www.example.com" ``` -------------------------------- ### Configure Minimum Client Subnet Prefix Length (IPv6) Source: https://github.com/nlnetlabs/unbound/blob/master/doc/unbound.conf.rst Define the minimum prefix length for IPv6 source masks accepted in queries. Shorter masks result in REFUSED answers. Defaults to 0. ```text min-client-subnet-ipv6: 12 ``` -------------------------------- ### Context Configuration Source: https://github.com/nlnetlabs/unbound/blob/master/doc/libunbound.rst Functions for initializing and configuring the Unbound context, including setting up host files, trust anchors, and debug output. ```APIDOC ## Context Configuration Functions ### ub_ctx_create **Description**: Creates a new Unbound context. **Method**: N/A (Function Call) **Endpoint**: N/A ### ub_ctx_hosts **Description**: Reads a list of hosts from a specified file, typically `/etc/hosts`. Addresses from this list are not marked as DNSSEC secure. **Method**: N/A (Function Call) **Endpoint**: N/A **Parameters**: #### Path Parameters - **fname** (string) - Optional - The filename to read hosts from. If NULL, defaults to `/etc/hosts` (or `WINDIR/etc/hosts` on Windows). ### ub_ctx_add_ta **Description**: Adds a trust anchor to the Unbound context. Trust anchors can be added before the first resolve operation. **Method**: N/A (Function Call) **Endpoint**: N/A **Parameters**: #### Path Parameters - **domainname** (string) - Required - The domain name for the trust anchor. - **type** (string) - Required - The type of record (DS or DNSKEY). - **rdata_contents** (string) - Required - The record data content. ### ub_ctx_add_ta_autr **Description**: Adds a filename containing an automatically tracked trust anchor to the context. This file can be updated if writable. **Method**: N/A (Function Call) **Endpoint**: N/A **Parameters**: #### Path Parameters - **filename** (string) - Required - The path to the file containing the managed trust anchor. ### ub_ctx_add_ta_file **Description**: Adds trust anchors from a file containing DS and DNSKEY records in zone file format. **Method**: N/A (Function Call) **Endpoint**: N/A **Parameters**: #### Path Parameters - **filename** (string) - Required - The path to the file containing trust anchors. ### ub_ctx_trustedkeys **Description**: Adds trust anchors from a bind-style configuration file with `trusted-keys{}`. **Method**: N/A (Function Call) **Endpoint**: N/A **Parameters**: #### Path Parameters - **filename** (string) - Required - The path to the bind-style configuration file. ### ub_ctx_debugout **Description**: Sets the debug and error log output stream. Pass NULL to disable output. Defaults to stderr. **Method**: N/A (Function Call) **Endpoint**: N/A **Parameters**: #### Path Parameters - **stream** (pointer) - Optional - The stream to direct debug output to. NULL disables output. ### ub_ctx_debuglevel **Description**: Sets the debug verbosity level for the context. Higher levels provide more output. **Method**: N/A (Function Call) **Endpoint**: N/A **Parameters**: #### Path Parameters - **level** (integer) - Required - The debug verbosity level. ### ub_ctx_async **Description**: Configures the context for asynchronous operation. `true` enables threading for `ub_resolve_async`, while `false` forks a process. **Method**: N/A (Function Call) **Endpoint**: N/A **Parameters**: #### Path Parameters - **enable** (boolean) - Required - `true` for threading, `false` for forking. ```