xref: /freebsd/contrib/unbound/libunbound/unbound.h (revision 87c1627502a5dde91e5284118eec8682b60f27a2)
1 /*
2  * unbound.h - unbound validating resolver public API
3  *
4  * Copyright (c) 2007, NLnet Labs. All rights reserved.
5  *
6  * This software is open source.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  *
15  * Redistributions in binary form must reproduce the above copyright notice,
16  * this list of conditions and the following disclaimer in the documentation
17  * and/or other materials provided with the distribution.
18  *
19  * Neither the name of the NLNET LABS nor the names of its contributors may
20  * be used to endorse or promote products derived from this software without
21  * specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
25  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
27  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33  * POSSIBILITY OF SUCH DAMAGE.
34  */
35 
36 /**
37  * \file
38  *
39  * This file contains functions to resolve DNS queries and
40  * validate the answers. Synchonously and asynchronously.
41  *
42  * Several ways to use this interface from an application wishing
43  * to perform (validated) DNS lookups.
44  *
45  * All start with
46  *	ctx = ub_ctx_create();
47  *	err = ub_ctx_add_ta(ctx, "...");
48  *	err = ub_ctx_add_ta(ctx, "...");
49  *	... some lookups
50  *	... call ub_ctx_delete(ctx); when you want to stop.
51  *
52  * Application not threaded. Blocking.
53  *	int err = ub_resolve(ctx, "www.example.com", ...
54  *	if(err) fprintf(stderr, "lookup error: %s\n", ub_strerror(err));
55  *	... use the answer
56  *
57  * Application not threaded. Non-blocking ('asynchronous').
58  *      err = ub_resolve_async(ctx, "www.example.com", ... my_callback);
59  *	... application resumes processing ...
60  *	... and when either ub_poll(ctx) is true
61  *	... or when the file descriptor ub_fd(ctx) is readable,
62  *	... or whenever, the app calls ...
63  *	ub_process(ctx);
64  *	... if no result is ready, the app resumes processing above,
65  *	... or process() calls my_callback() with results.
66  *
67  *      ... if the application has nothing more to do, wait for answer
68  *      ub_wait(ctx);
69  *
70  * Application threaded. Blocking.
71  *	Blocking, same as above. The current thread does the work.
72  *	Multiple threads can use the *same context*, each does work and uses
73  *	shared cache data from the context.
74  *
75  * Application threaded. Non-blocking ('asynchronous').
76  *	... setup threaded-asynchronous config option
77  *	err = ub_ctx_async(ctx, 1);
78  *	... same as async for non-threaded
79  *	... the callbacks are called in the thread that calls process(ctx)
80  *
81  * If no threading is compiled in, the above async example uses fork(2) to
82  * create a process to perform the work. The forked process exits when the
83  * calling process exits, or ctx_delete() is called.
84  * Otherwise, for asynchronous with threading, a worker thread is created.
85  *
86  * The blocking calls use shared ctx-cache when threaded. Thus
87  * ub_resolve() and ub_resolve_async() && ub_wait() are
88  * not the same. The first makes the current thread do the work, setting
89  * up buffers, etc, to perform the work (but using shared cache data).
90  * The second calls another worker thread (or process) to perform the work.
91  * And no buffers need to be set up, but a context-switch happens.
92  */
93 #ifndef _UB_UNBOUND_H
94 #define _UB_UNBOUND_H
95 
96 #ifdef __cplusplus
97 extern "C" {
98 #endif
99 
100 /**
101  * The validation context is created to hold the resolver status,
102  * validation keys and a small cache (containing messages, rrsets,
103  * roundtrip times, trusted keys, lameness information).
104  *
105  * Its contents are internally defined.
106  */
107 struct ub_ctx;
108 
109 /**
110  * The validation and resolution results.
111  * Allocated by the resolver, and need to be freed by the application
112  * with ub_resolve_free().
113  */
114 struct ub_result {
115 	/** The original question, name text string. */
116 	char* qname;
117 	/** the type asked for */
118 	int qtype;
119 	/** the class asked for */
120 	int qclass;
121 
122 	/**
123 	 * a list of network order DNS rdata items, terminated with a
124 	 * NULL pointer, so that data[0] is the first result entry,
125 	 * data[1] the second, and the last entry is NULL.
126 	 * If there was no data, data[0] is NULL.
127 	 */
128 	char** data;
129 
130 	/** the length in bytes of the data items, len[i] for data[i] */
131 	int* len;
132 
133 	/**
134 	 * canonical name for the result (the final cname).
135 	 * zero terminated string.
136 	 * May be NULL if no canonical name exists.
137 	 */
138 	char* canonname;
139 
140 	/**
141 	 * DNS RCODE for the result. May contain additional error code if
142 	 * there was no data due to an error. 0 (NOERROR) if okay.
143 	 */
144 	int rcode;
145 
146 	/**
147 	 * The DNS answer packet. Network formatted. Can contain DNSSEC types.
148 	 */
149 	void* answer_packet;
150 	/** length of the answer packet in octets. */
151 	int answer_len;
152 
153 	/**
154 	 * If there is any data, this is true.
155 	 * If false, there was no data (nxdomain may be true, rcode can be set).
156 	 */
157 	int havedata;
158 
159 	/**
160 	 * If there was no data, and the domain did not exist, this is true.
161 	 * If it is false, and there was no data, then the domain name
162 	 * is purported to exist, but the requested data type is not available.
163 	 */
164 	int nxdomain;
165 
166 	/**
167 	 * True, if the result is validated securely.
168 	 * False, if validation failed or domain queried has no security info.
169 	 *
170 	 * It is possible to get a result with no data (havedata is false),
171 	 * and secure is true. This means that the non-existance of the data
172 	 * was cryptographically proven (with signatures).
173 	 */
174 	int secure;
175 
176 	/**
177 	 * If the result was not secure (secure==0), and this result is due
178 	 * to a security failure, bogus is true.
179 	 * This means the data has been actively tampered with, signatures
180 	 * failed, expected signatures were not present, timestamps on
181 	 * signatures were out of date and so on.
182 	 *
183 	 * If !secure and !bogus, this can happen if the data is not secure
184 	 * because security is disabled for that domain name.
185 	 * This means the data is from a domain where data is not signed.
186 	 */
187 	int bogus;
188 
189 	/**
190 	 * If the result is bogus this contains a string (zero terminated)
191 	 * that describes the failure.  There may be other errors as well
192 	 * as the one described, the description may not be perfectly accurate.
193 	 * Is NULL if the result is not bogus.
194 	 */
195 	char* why_bogus;
196 
197 	/**
198 	 * TTL for the result, in seconds.  If the security is bogus, then
199 	 * you also cannot trust this value.
200 	 */
201 	int ttl;
202 };
203 
204 /**
205  * Callback for results of async queries.
206  * The readable function definition looks like:
207  * void my_callback(void* my_arg, int err, struct ub_result* result);
208  * It is called with
209  *	void* my_arg: your pointer to a (struct of) data of your choice,
210  *		or NULL.
211  *	int err: if 0 all is OK, otherwise an error occured and no results
212  *	     are forthcoming.
213  *	struct result: pointer to more detailed result structure.
214  *		This structure is allocated on the heap and needs to be
215  *		freed with ub_resolve_free(result);
216  */
217 typedef void (*ub_callback_t)(void*, int, struct ub_result*);
218 
219 /**
220  * Create a resolving and validation context.
221  * The information from /etc/resolv.conf and /etc/hosts is not utilised by
222  * default. Use ub_ctx_resolvconf and ub_ctx_hosts to read them.
223  * @return a new context. default initialisation.
224  * 	returns NULL on error.
225  */
226 struct ub_ctx* ub_ctx_create(void);
227 
228 /**
229  * Destroy a validation context and free all its resources.
230  * Outstanding async queries are killed and callbacks are not called for them.
231  * @param ctx: context to delete.
232  */
233 void ub_ctx_delete(struct ub_ctx* ctx);
234 
235 /**
236  * Set an option for the context.
237  * @param ctx: context.
238  * @param opt: option name from the unbound.conf config file format.
239  *	(not all settings applicable). The name includes the trailing ':'
240  *	for example ub_ctx_set_option(ctx, "logfile:", "mylog.txt");
241  * 	This is a power-users interface that lets you specify all sorts
242  * 	of options.
243  * 	For some specific options, such as adding trust anchors, special
244  * 	routines exist.
245  * @param val: value of the option.
246  * @return: 0 if OK, else error.
247  */
248 int ub_ctx_set_option(struct ub_ctx* ctx, char* opt, char* val);
249 
250 /**
251  * Get an option from the context.
252  * @param ctx: context.
253  * @param opt: option name from the unbound.conf config file format.
254  *	(not all settings applicable). The name excludes the trailing ':'
255  *	for example ub_ctx_get_option(ctx, "logfile", &result);
256  * 	This is a power-users interface that lets you specify all sorts
257  * 	of options.
258  * @param str: the string is malloced and returned here. NULL on error.
259  * 	The caller must free() the string.  In cases with multiple
260  * 	entries (auto-trust-anchor-file), a newline delimited list is
261  * 	returned in the string.
262  * @return 0 if OK else an error code (malloc failure, syntax error).
263  */
264 int ub_ctx_get_option(struct ub_ctx* ctx, char* opt, char** str);
265 
266 /**
267  * setup configuration for the given context.
268  * @param ctx: context.
269  * @param fname: unbound config file (not all settings applicable).
270  * 	This is a power-users interface that lets you specify all sorts
271  * 	of options.
272  * 	For some specific options, such as adding trust anchors, special
273  * 	routines exist.
274  * @return: 0 if OK, else error.
275  */
276 int ub_ctx_config(struct ub_ctx* ctx, char* fname);
277 
278 /**
279  * Set machine to forward DNS queries to, the caching resolver to use.
280  * IP4 or IP6 address. Forwards all DNS requests to that machine, which
281  * is expected to run a recursive resolver. If the proxy is not
282  * DNSSEC-capable, validation may fail. Can be called several times, in
283  * that case the addresses are used as backup servers.
284  *
285  * To read the list of nameservers from /etc/resolv.conf (from DHCP or so),
286  * use the call ub_ctx_resolvconf.
287  *
288  * @param ctx: context.
289  *	At this time it is only possible to set configuration before the
290  *	first resolve is done.
291  * @param addr: address, IP4 or IP6 in string format.
292  * 	If the addr is NULL, forwarding is disabled.
293  * @return 0 if OK, else error.
294  */
295 int ub_ctx_set_fwd(struct ub_ctx* ctx, char* addr);
296 
297 /**
298  * Read list of nameservers to use from the filename given.
299  * Usually "/etc/resolv.conf". Uses those nameservers as caching proxies.
300  * If they do not support DNSSEC, validation may fail.
301  *
302  * Only nameservers are picked up, the searchdomain, ndots and other
303  * settings from resolv.conf(5) are ignored.
304  *
305  * @param ctx: context.
306  *	At this time it is only possible to set configuration before the
307  *	first resolve is done.
308  * @param fname: file name string. If NULL "/etc/resolv.conf" is used.
309  * @return 0 if OK, else error.
310  */
311 int ub_ctx_resolvconf(struct ub_ctx* ctx, char* fname);
312 
313 /**
314  * Read list of hosts from the filename given.
315  * Usually "/etc/hosts".
316  * These addresses are not flagged as DNSSEC secure when queried for.
317  *
318  * @param ctx: context.
319  *	At this time it is only possible to set configuration before the
320  *	first resolve is done.
321  * @param fname: file name string. If NULL "/etc/hosts" is used.
322  * @return 0 if OK, else error.
323  */
324 int ub_ctx_hosts(struct ub_ctx* ctx, char* fname);
325 
326 /**
327  * Add a trust anchor to the given context.
328  * The trust anchor is a string, on one line, that holds a valid DNSKEY or
329  * DS RR.
330  * @param ctx: context.
331  *	At this time it is only possible to add trusted keys before the
332  *	first resolve is done.
333  * @param ta: string, with zone-format RR on one line.
334  * 	[domainname] [TTL optional] [type] [class optional] [rdata contents]
335  * @return 0 if OK, else error.
336  */
337 int ub_ctx_add_ta(struct ub_ctx* ctx, char* ta);
338 
339 /**
340  * Add trust anchors to the given context.
341  * Pass name of a file with DS and DNSKEY records (like from dig or drill).
342  * @param ctx: context.
343  *	At this time it is only possible to add trusted keys before the
344  *	first resolve is done.
345  * @param fname: filename of file with keyfile with trust anchors.
346  * @return 0 if OK, else error.
347  */
348 int ub_ctx_add_ta_file(struct ub_ctx* ctx, char* fname);
349 
350 /**
351  * Add trust anchors to the given context.
352  * Pass the name of a bind-style config file with trusted-keys{}.
353  * @param ctx: context.
354  *	At this time it is only possible to add trusted keys before the
355  *	first resolve is done.
356  * @param fname: filename of file with bind-style config entries with trust
357  * 	anchors.
358  * @return 0 if OK, else error.
359  */
360 int ub_ctx_trustedkeys(struct ub_ctx* ctx, char* fname);
361 
362 /**
363  * Set debug output (and error output) to the specified stream.
364  * Pass NULL to disable. Default is stderr.
365  * @param ctx: context.
366  * @param out: FILE* out file stream to log to.
367  * 	Type void* to avoid stdio dependency of this header file.
368  * @return 0 if OK, else error.
369  */
370 int ub_ctx_debugout(struct ub_ctx* ctx, void* out);
371 
372 /**
373  * Set debug verbosity for the context
374  * Output is directed to stderr.
375  * @param ctx: context.
376  * @param d: debug level, 0 is off, 1 is very minimal, 2 is detailed,
377  *	and 3 is lots.
378  * @return 0 if OK, else error.
379  */
380 int ub_ctx_debuglevel(struct ub_ctx* ctx, int d);
381 
382 /**
383  * Set a context behaviour for asynchronous action.
384  * @param ctx: context.
385  * @param dothread: if true, enables threading and a call to resolve_async()
386  *	creates a thread to handle work in the background.
387  *	If false, a process is forked to handle work in the background.
388  *	Changes to this setting after async() calls have been made have
389  *	no effect (delete and re-create the context to change).
390  * @return 0 if OK, else error.
391  */
392 int ub_ctx_async(struct ub_ctx* ctx, int dothread);
393 
394 /**
395  * Poll a context to see if it has any new results
396  * Do not poll in a loop, instead extract the fd below to poll for readiness,
397  * and then check, or wait using the wait routine.
398  * @param ctx: context.
399  * @return: 0 if nothing to read, or nonzero if a result is available.
400  * 	If nonzero, call ctx_process() to do callbacks.
401  */
402 int ub_poll(struct ub_ctx* ctx);
403 
404 /**
405  * Wait for a context to finish with results. Calls ub_process() after
406  * the wait for you. After the wait, there are no more outstanding
407  * asynchronous queries.
408  * @param ctx: context.
409  * @return: 0 if OK, else error.
410  */
411 int ub_wait(struct ub_ctx* ctx);
412 
413 /**
414  * Get file descriptor. Wait for it to become readable, at this point
415  * answers are returned from the asynchronous validating resolver.
416  * Then call the ub_process to continue processing.
417  * This routine works immediately after context creation, the fd
418  * does not change.
419  * @param ctx: context.
420  * @return: -1 on error, or file descriptor to use select(2) with.
421  */
422 int ub_fd(struct ub_ctx* ctx);
423 
424 /**
425  * Call this routine to continue processing results from the validating
426  * resolver (when the fd becomes readable).
427  * Will perform necessary callbacks.
428  * @param ctx: context
429  * @return: 0 if OK, else error.
430  */
431 int ub_process(struct ub_ctx* ctx);
432 
433 /**
434  * Perform resolution and validation of the target name.
435  * @param ctx: context.
436  *	The context is finalized, and can no longer accept config changes.
437  * @param name: domain name in text format (a zero terminated text string).
438  * @param rrtype: type of RR in host order, 1 is A (address).
439  * @param rrclass: class of RR in host order, 1 is IN (for internet).
440  * @param result: the result data is returned in a newly allocated result
441  * 	structure. May be NULL on return, return value is set to an error
442  * 	in that case (out of memory).
443  * @return 0 if OK, else error.
444  */
445 int ub_resolve(struct ub_ctx* ctx, char* name, int rrtype,
446 	int rrclass, struct ub_result** result);
447 
448 /**
449  * Perform resolution and validation of the target name.
450  * Asynchronous, after a while, the callback will be called with your
451  * data and the result.
452  * @param ctx: context.
453  *	If no thread or process has been created yet to perform the
454  *	work in the background, it is created now.
455  *	The context is finalized, and can no longer accept config changes.
456  * @param name: domain name in text format (a string).
457  * @param rrtype: type of RR in host order, 1 is A.
458  * @param rrclass: class of RR in host order, 1 is IN (for internet).
459  * @param mydata: this data is your own data (you can pass NULL),
460  * 	and is passed on to the callback function.
461  * @param callback: this is called on completion of the resolution.
462  * 	It is called as:
463  * 	void callback(void* mydata, int err, struct ub_result* result)
464  * 	with mydata: the same as passed here, you may pass NULL,
465  * 	with err: is 0 when a result has been found.
466  * 	with result: a newly allocated result structure.
467  *		The result may be NULL, in that case err is set.
468  *
469  * 	If an error happens during processing, your callback will be called
470  * 	with error set to a nonzero value (and result==NULL).
471  * @param async_id: if you pass a non-NULL value, an identifier number is
472  *	returned for the query as it is in progress. It can be used to
473  *	cancel the query.
474  * @return 0 if OK, else error.
475  */
476 int ub_resolve_async(struct ub_ctx* ctx, char* name, int rrtype,
477 	int rrclass, void* mydata, ub_callback_t callback, int* async_id);
478 
479 /**
480  * Cancel an async query in progress.
481  * Its callback will not be called.
482  *
483  * @param ctx: context.
484  * @param async_id: which query to cancel.
485  * @return 0 if OK, else error.
486  * This routine can return an error if the async_id passed does not exist
487  * or has already been delivered. If another thread is processing results
488  * at the same time, the result may be delivered at the same time and the
489  * cancel fails with an error.  Also the cancel can fail due to a system
490  * error, no memory or socket failures.
491  */
492 int ub_cancel(struct ub_ctx* ctx, int async_id);
493 
494 /**
495  * Free storage associated with a result structure.
496  * @param result: to free
497  */
498 void ub_resolve_free(struct ub_result* result);
499 
500 /**
501  * Convert error value to a human readable string.
502  * @param err: error code from one of the ub_val* functions.
503  * @return pointer to constant text string, zero terminated.
504  */
505 const char* ub_strerror(int err);
506 
507 /**
508  * Debug routine.  Print the local zone information to debug output.
509  * @param ctx: context.  Is finalized by the routine.
510  * @return 0 if OK, else error.
511  */
512 int ub_ctx_print_local_zones(struct ub_ctx* ctx);
513 
514 /**
515  * Add a new zone with the zonetype to the local authority info of the
516  * library.
517  * @param ctx: context.  Is finalized by the routine.
518  * @param zone_name: name of the zone in text, "example.com"
519  *	If it already exists, the type is updated.
520  * @param zone_type: type of the zone (like for unbound.conf) in text.
521  * @return 0 if OK, else error.
522  */
523 int ub_ctx_zone_add(struct ub_ctx* ctx, char *zone_name, char *zone_type);
524 
525 /**
526  * Remove zone from local authority info of the library.
527  * @param ctx: context.  Is finalized by the routine.
528  * @param zone_name: name of the zone in text, "example.com"
529  *	If it does not exist, nothing happens.
530  * @return 0 if OK, else error.
531  */
532 int ub_ctx_zone_remove(struct ub_ctx* ctx, char *zone_name);
533 
534 /**
535  * Add localdata to the library local authority info.
536  * Similar to local-data config statement.
537  * @param ctx: context.  Is finalized by the routine.
538  * @param data: the resource record in text format, for example
539  *	"www.example.com IN A 127.0.0.1"
540  * @return 0 if OK, else error.
541  */
542 int ub_ctx_data_add(struct ub_ctx* ctx, char *data);
543 
544 /**
545  * Remove localdata from the library local authority info.
546  * @param ctx: context.  Is finalized by the routine.
547  * @param data: the name to delete all data from, like "www.example.com".
548  * @return 0 if OK, else error.
549  */
550 int ub_ctx_data_remove(struct ub_ctx* ctx, char *data);
551 
552 /**
553  * Get a version string from the libunbound implementation.
554  * @return a static constant string with the version number.
555  */
556 const char* ub_version(void);
557 
558 #ifdef __cplusplus
559 }
560 #endif
561 
562 #endif /* _UB_UNBOUND_H */
563