chiark / gitweb /
src/adns.h, src/types.c: Now adns_rr_addr can hold a sockaddr_in6.
[adns.git] / src / adns.h
1 /*
2  * adns.h
3  * - adns user-visible API
4  */
5 /*
6  *
7  *  This file is
8  *    Copyright (C) 1997-2000,2003,2006 Ian Jackson
9  *
10  *  It is part of adns, which is
11  *    Copyright (C) 1997-2000,2003,2006 Ian Jackson
12  *    Copyright (C) 1999-2000,2003,2006 Tony Finch
13  *    Copyright (C) 1991 Massachusetts Institute of Technology
14  *
15  *  This program is free software; you can redistribute it and/or modify
16  *  it under the terms of the GNU General Public License as published by
17  *  the Free Software Foundation; either version 2, or (at your option)
18  *  any later version.
19  *  
20  *  This program is distributed in the hope that it will be useful,
21  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
22  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23  *  GNU General Public License for more details.
24  *
25  * 
26  *  For the benefit of certain LGPL'd `omnibus' software which
27  *  provides a uniform interface to various things including adns, I
28  *  make the following additional licence.  I do this because the GPL
29  *  would otherwise force either the omnibus software to be GPL'd or
30  *  the adns-using part to be distributed separately.
31  *  
32  *  So: you may also redistribute and/or modify adns.h (but only the
33  *  public header file adns.h and not any other part of adns) under the
34  *  terms of the GNU Library General Public License as published by the
35  *  Free Software Foundation; either version 2 of the License, or (at
36  *  your option) any later version.
37  *  
38  *  Note that adns itself is GPL'd.  Authors of adns-using applications
39  *  with GPL-incompatible licences, and people who distribute adns with
40  *  applications where the whole distribution is not GPL'd, are still
41  *  likely to be in violation of the GPL.  Anyone who wants to do this
42  *  should contact Ian Jackson.  Please note that to avoid encouraging
43  *  people to infringe the GPL as it applies to the body of adns, Ian
44  *  thinks that if you take advantage of the special exception to
45  *  redistribute just adns.h under the LGPL, you should retain this
46  *  paragraph in its place in the appropriate copyright statements.
47  *
48  *
49  *  You should have received a copy of the GNU General Public License,
50  *  or the GNU Library General Public License, as appropriate, along
51  *  with this program; if not, write to the Free Software Foundation,
52  *  Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
53  *
54  *
55  *  $Id$
56  */
57
58 #ifndef ADNS_H_INCLUDED
59 #define ADNS_H_INCLUDED
60
61 #include <stdio.h>
62 #include <stdarg.h>
63
64 #include <sys/types.h>
65 #include <sys/socket.h>
66 #include <netinet/in.h>
67 #include <sys/time.h>
68 #include <unistd.h>
69
70 #ifdef __cplusplus
71 extern "C" { /* I really dislike this - iwj. */
72 #endif
73
74 /* All struct in_addr anywhere in adns are in NETWORK byte order. */
75
76 typedef struct adns__state *adns_state;
77 typedef struct adns__query *adns_query;
78
79 typedef enum { /* In general, or together the desired flags: */
80  adns_if_none=        0x0000,/* no flags.  nicer than 0 for some compilers */
81  adns_if_noenv=       0x0001,/* do not look at environment */
82  adns_if_noerrprint=  0x0002,/* never print to stderr (_debug overrides) */
83  adns_if_noserverwarn=0x0004,/* do not warn to stderr about duff servers etc */
84  adns_if_debug=       0x0008,/* enable all output to stderr plus debug msgs */
85  adns_if_logpid=      0x0080,/* include pid in diagnostic output */
86  adns_if_noautosys=   0x0010,/* do not make syscalls at every opportunity */
87  adns_if_eintr=       0x0020,/* allow _wait and _synchronous to return EINTR */
88  adns_if_nosigpipe=   0x0040,/* applic has SIGPIPE ignored, do not protect */
89  adns_if_checkc_entex=0x0100,/* consistency checks on entry/exit to adns fns */
90  adns_if_checkc_freq= 0x0300 /* consistency checks very frequently (slow!) */
91 } adns_initflags;
92
93 typedef enum { /* In general, or together the desired flags: */
94  adns_qf_none=           0x00000000,/* no flags */
95  adns_qf_search=         0x00000001,/* use the searchlist */
96  adns_qf_usevc=          0x00000002,/* use a virtual circuit (TCP conn) */
97  adns_qf_owner=          0x00000004,/* fill in the owner field in the answer */
98  adns_qf_quoteok_query=  0x00000010,/* allow special chars in query domain */
99  adns_qf_quoteok_cname=  0x00000000,/*  ... in CNAME we go via (now default) */
100  adns_qf_quoteok_anshost=0x00000040,/*  ... in things supposedly hostnames */
101  adns_qf_quotefail_cname=0x00000080,/* refuse if quote-req chars in CNAME we go via */
102  adns_qf_cname_loose=    0x00000100,/* allow refs to CNAMEs - without, get _s_cname */
103  adns_qf_cname_forbid=   0x00000200,/* don't follow CNAMEs, instead give _s_cname */
104  adns__qf_internalmask=  0x0ff00000
105 } adns_queryflags;
106
107 typedef enum {
108  adns_rrt_typemask=  0x0ffff,
109  adns_rrt_reprmask= 0xffffff,
110  adns__qtf_deref_bit=0x10000,/* internal version of ..._deref below */
111  adns__qtf_mail822=  0x20000,/* return mailboxes in RFC822 rcpt field fmt   */
112
113  adns__qtf_bigaddr=0x1000000,/* use the new larger sockaddr union */
114
115  adns__qtf_deref=    adns__qtf_deref_bit|adns__qtf_bigaddr
116                             ,/* dereference domains; perhaps get extra data */
117
118  adns_r_unknown=     0x40000,
119    /* To use this, ask for records of type   <rr-type-code>|adns_r_unknown.
120     * adns will not process the RDATA - you'll get adns_rr_byteblocks,
121     * where the int is the length and the unsigned char* points to the
122     * data.  String representation of the RR data (by adns_rrinfo) is as in
123     * RFC3597.  adns_rr_info will not return the type name in *rrtname_r
124     * (due to memory management problems); *fmtname_r will be set to
125     * "unknown".
126     *
127     * Do not specify adns_r_unknown along with a known RR type which
128     * requires domain name uncompression (see RFC3597 s4); domain names
129     * will not be uncompressed and the resulting data would be useless.
130     * Asking for meta-RR types via adns_r_unknown will not work properly
131     * either and may make adns complain about server misbehaviour, so don't
132     * do that.
133     *
134     * Don't forget adns_qf_quoteok if that's what you want. */
135
136  adns_r_none=             0,
137                      
138  adns_r_a=                1,
139                      
140  adns_r_ns_raw=           2,
141  adns_r_ns=                  adns_r_ns_raw|adns__qtf_deref,
142                      
143  adns_r_cname=            5,
144                      
145  adns_r_soa_raw=          6,
146  adns_r_soa=                 adns_r_soa_raw|adns__qtf_mail822, 
147                      
148  adns_r_ptr_raw=         12, /* do not mind PTR with wrong or missing A */
149  adns_r_ptr=                 adns_r_ptr_raw|adns__qtf_deref,
150                      
151  adns_r_hinfo=           13,  
152                      
153  adns_r_mx_raw=          15,
154  adns_r_mx=                  adns_r_mx_raw|adns__qtf_deref,
155                      
156  adns_r_txt=             16,
157                      
158  adns_r_rp_raw=          17,
159  adns_r_rp=                  adns_r_rp_raw|adns__qtf_mail822,
160
161  /* For SRV records, query domain without _qf_quoteok_query must look
162   * as expected from SRV RFC with hostname-like Name.  _With_
163   * _quoteok_query, any query domain is allowed. */
164  adns_r_srv_raw=         33,
165  adns_r_srv=                 adns_r_srv_raw|adns__qtf_deref,
166                      
167  adns_r_addr=                adns_r_a|adns__qtf_deref
168  
169 } adns_rrtype;
170
171 /*
172  * In queries without qf_quoteok_*, all domains must have standard
173  * legal syntax, or you get adns_s_querydomainvalid (if the query
174  * domain contains bad characters) or adns_s_answerdomaininvalid (if
175  * the answer contains bad characters).
176  * 
177  * In queries _with_ qf_quoteok_*, domains in the query or response
178  * may contain any characters, quoted according to RFC1035 5.1.  On
179  * input to adns, the char* is a pointer to the interior of a "
180  * delimited string, except that " may appear in it unquoted.  On
181  * output, the char* is a pointer to a string which would be legal
182  * either inside or outside " delimiters; any character which isn't
183  * legal in a hostname (ie alphanumeric or hyphen) or one of _ / +
184  * (the three other punctuation characters commonly abused in domain
185  * names) will be quoted, as \X if it is a printing ASCII character or
186  * \DDD otherwise.
187  *
188  * If the query goes via a CNAME then the canonical name (ie, the
189  * thing that the CNAME record refers to) is usually allowed to
190  * contain any characters, which will be quoted as above.  With
191  * adns_qf_quotefail_cname you get adns_s_answerdomaininvalid when
192  * this happens.  (This is a change from version 0.4 and earlier, in
193  * which failing the query was the default, and you had to say
194  * adns_qf_quoteok_cname to avoid this; that flag is now deprecated.)
195  *
196  * In version 0.4 and earlier, asking for _raw records containing
197  * mailboxes without specifying _qf_quoteok_anshost was silly.  This
198  * is no longer the case.  In this version only parts of responses
199  * that are actually supposed to be hostnames will be refused by
200  * default if quote-requiring characters are found.
201  */
202
203 /*
204  * If you ask for an RR which contains domains which are actually
205  * encoded mailboxes, and don't ask for the _raw version, then adns
206  * returns the mailbox formatted suitably for an RFC822 recipient
207  * header field.  The particular format used is that if the mailbox
208  * requires quoting according to the rules in RFC822 then the
209  * local-part is quoted in double quotes, which end at the next
210  * unescaped double quote (\ is the escape char, and is doubled, and
211  * is used to escape only \ and ").  If the local-part is legal
212  * without quoting according to RFC822, it is presented as-is.  In any
213  * case the local-part is followed by an @ and the domain.  The domain
214  * will not contain any characters not legal in hostnames.
215  *
216  * Unquoted local-parts may contain any printing 7-bit ASCII
217  * except the punctuation characters ( ) < > @ , ; : \ " [ ]
218  * I.e. they may contain alphanumerics, and the following
219  * punctuation characters:  ! # % ^ & * - _ = + { } .
220  *
221  * adns will reject local parts containing control characters (byte
222  * values 0-31, 127-159, and 255) - these appear to be legal according
223  * to RFC822 (at least 0-127) but are clearly a bad idea.  RFC1035
224  * syntax does not make any distinction between a single RFC822
225  * quoted-string containing full stops, and a series of quoted-strings
226  * separated by full stops; adns will return anything that isn't all
227  * valid atoms as a single quoted-string.  RFC822 does not allow
228  * high-bit-set characters at all, but adns does allow them in
229  * local-parts, treating them as needing quoting.
230  *
231  * If you ask for the domain with _raw then _no_ checking is done
232  * (even on the host part, regardless of adns_qf_quoteok_anshost), and
233  * you just get the domain name in master file format.
234  *
235  * If no mailbox is supplied the returned string will be `.' in either
236  * case.
237  */
238
239 typedef enum {
240  adns_s_ok,
241
242  /* locally induced errors */
243  adns_s_nomemory,
244  adns_s_unknownrrtype,
245  adns_s_systemfail,
246
247  adns_s_max_localfail= 29,
248  
249  /* remotely induced errors, detected locally */
250  adns_s_timeout,
251  adns_s_allservfail,
252  adns_s_norecurse,
253  adns_s_invalidresponse,
254  adns_s_unknownformat,
255
256  adns_s_max_remotefail= 59,
257  
258  /* remotely induced errors, reported by remote server to us */
259  adns_s_rcodeservfail,
260  adns_s_rcodeformaterror,
261  adns_s_rcodenotimplemented,
262  adns_s_rcoderefused,
263  adns_s_rcodeunknown,
264
265  adns_s_max_tempfail= 99,
266
267  /* remote configuration errors */
268  adns_s_inconsistent, /* PTR gives domain whose A does not exist and match */
269  adns_s_prohibitedcname, /* CNAME, but eg A expected (not if _qf_loosecname) */
270  adns_s_answerdomaininvalid,
271  adns_s_answerdomaintoolong,
272  adns_s_invaliddata,
273  
274  adns_s_max_misconfig= 199,
275
276  /* permanent problems with the query */
277  adns_s_querydomainwrong,
278  adns_s_querydomaininvalid,
279  adns_s_querydomaintoolong,
280  
281  adns_s_max_misquery= 299,
282
283  /* permanent errors */
284  adns_s_nxdomain,
285  adns_s_nodata,
286
287  adns_s_max_permfail= 499
288  
289 } adns_status;
290
291 typedef union {
292   struct sockaddr sa;
293   struct sockaddr_in inet;
294 } adns_sockaddr_v4only;
295
296 typedef union {
297   struct sockaddr sa;
298   struct sockaddr_in inet;
299   struct sockaddr_in6 inet6;
300 } adns_sockaddr;
301
302 typedef struct {
303   int len;
304   adns_sockaddr addr;
305 } adns_rr_addr;
306
307 typedef struct {
308   /* the old v4-only structure; handy if you have complicated binary
309    * compatibility problems. */
310   int len;
311   adns_sockaddr_v4only addr;
312 } adns_rr_addr_v4only;
313
314 typedef struct {
315   char *host;
316   adns_status astatus;
317   int naddrs; /* temp fail => -1, perm fail => 0, s_ok => >0 */
318   adns_rr_addr *addrs;
319 } adns_rr_hostaddr;
320
321 typedef struct {
322   char *(array[2]);
323 } adns_rr_strpair;
324
325 typedef struct {
326   int i;
327   adns_rr_hostaddr ha;
328 } adns_rr_inthostaddr;
329
330 typedef struct {
331   /* Used both for mx_raw, in which case i is the preference and str
332    * the domain, and for txt, in which case each entry has i for the
333    * `text' length, and str for the data (which will have had an extra
334    * nul appended so that if it was plain text it is now a
335    * null-terminated string).
336    */
337   int i;
338   char *str;
339 } adns_rr_intstr;
340
341 typedef struct {
342   adns_rr_intstr array[2];
343 } adns_rr_intstrpair;
344
345 typedef struct {
346   char *mname, *rname;
347   unsigned long serial, refresh, retry, expire, minimum;
348 } adns_rr_soa;
349
350 typedef struct {
351   int priority, weight, port;
352   char *host;
353 } adns_rr_srvraw;
354
355 typedef struct {
356   int priority, weight, port;
357   adns_rr_hostaddr ha;
358 } adns_rr_srvha;
359
360 typedef struct {
361   int len;
362   unsigned char *data;
363 } adns_rr_byteblock;
364
365 typedef struct {
366   adns_status status;
367   char *cname; /* always NULL if query was for CNAME records */
368   char *owner; /* only set if req'd in query flags; maybe 0 on error anyway */
369   adns_rrtype type; /* guaranteed to be same as in query */
370   time_t expires;/*abs time.  def only if _s_ok, nxdomain or nodata. NOT TTL!*/
371   int nrrs, rrsz; /* nrrs is 0 if an error occurs */
372   union {
373     void *untyped;
374     unsigned char *bytes;
375     char *(*str);                    /* ns_raw, cname, ptr, ptr_raw */
376     adns_rr_intstr *(*manyistr);     /* txt (list strs ends with i=-1, str=0)*/
377     adns_rr_addr *addr;              /* addr */
378     struct in_addr *inaddr;          /* a */
379     adns_rr_hostaddr *hostaddr;      /* ns */
380     adns_rr_intstrpair *intstrpair;  /* hinfo */
381     adns_rr_strpair *strpair;        /* rp, rp_raw */
382     adns_rr_inthostaddr *inthostaddr;/* mx */
383     adns_rr_intstr *intstr;          /* mx_raw */
384     adns_rr_soa *soa;                /* soa, soa_raw */
385     adns_rr_srvraw *srvraw;          /* srv_raw */
386     adns_rr_srvha *srvha;/* srv */
387     adns_rr_byteblock *byteblock;    /* ...|unknown */
388   } rrs;
389 } adns_answer;
390
391 /* Memory management:
392  *  adns_state and adns_query are actually pointers to malloc'd state;
393  *  On submission questions are copied, including the owner domain;
394  *  Answers are malloc'd as a single piece of memory; pointers in the
395  *  answer struct point into further memory in the answer.
396  * query_io:
397  *  Must always be non-null pointer;
398  *  If *query_io is 0 to start with then any query may be returned;
399  *  If *query_io is !0 adns_query then only that query may be returned.
400  *  If the call is successful, *query_io, *answer_r, and *context_r
401  *  will all be set.
402  * Errors:
403  *  Return values are 0 or an errno value.
404  *
405  *  For _init, _init_strcfg, _submit and _synchronous, system errors
406  *  (eg, failure to create sockets, malloc failure, etc.) return errno
407  *  values.  EINVAL from _init et al means the configuration file
408  *  is erroneous and cannot be parsed.
409  * 
410  *  For _wait and _check failures are reported in the answer
411  *  structure, and only 0, ESRCH or (for _check) EAGAIN is
412  *  returned: if no (appropriate) requests are done adns_check returns
413  *  EAGAIN; if no (appropriate) requests are outstanding both
414  *  adns_query and adns_wait return ESRCH.
415  *
416  *  Additionally, _wait can return EINTR if you set adns_if_eintr.
417  *
418  *  All other errors (nameserver failure, timed out connections, &c)
419  *  are returned in the status field of the answer.  After a
420  *  successful _wait or _check, if status is nonzero then nrrs will be
421  *  0, otherwise it will be >0.  type will always be the type
422  *  requested.
423  */
424
425 /* Threads:
426  *  adns does not use any static modifiable state, so it
427  *   is safe to call adns_init several times and then use the
428  *   resulting adns_states concurrently.
429  *  However, it is NOT safe to make simultaneous calls into
430  *   adns using the same adns_state; a single adns_state must be used
431  *   only by one thread at a time.  You can solve this problem by
432  *   having one adns_state per thread, or if that isn't feasible, you
433  *   could maintain a pool of adns_states.  Unfortunately neither of
434  *   these approaches has optimal performance.
435  */
436
437 int adns_init(adns_state *newstate_r, adns_initflags flags,
438               FILE *diagfile /*0=>stderr*/);
439
440 int adns_init_strcfg(adns_state *newstate_r, adns_initflags flags,
441                      FILE *diagfile /*0=>discard*/, const char *configtext);
442
443 typedef void adns_logcallbackfn(adns_state ads, void *logfndata,
444                                 const char *fmt, va_list al);
445   /* Will be called perhaps several times for each message; when the
446    * message is complete, the string implied by fmt and al will end in
447    * a newline.  Log messages start with `adns debug:' or `adns
448    * warning:' or `adns:' (for errors), or `adns debug [PID]:'
449    * etc. if adns_if_logpid is set. */
450
451 int adns_init_logfn(adns_state *newstate_r, adns_initflags flags,
452                     const char *configtext /*0=>use default config files*/,
453                     adns_logcallbackfn *logfn /*0=>logfndata is a FILE* */,
454                     void *logfndata /*0 with logfn==0 => discard*/);
455
456 /* Configuration:
457  *  adns_init reads /etc/resolv.conf, which is expected to be (broadly
458  *  speaking) in the format expected by libresolv, and then
459  *  /etc/resolv-adns.conf if it exists.  adns_init_strcfg is instead
460  *  passed a string which is interpreted as if it were the contents of
461  *  resolv.conf or resolv-adns.conf.  In general, configuration which
462  *  is set later overrides any that is set earlier.
463  *
464  * Standard directives understood in resolv[-adns].conf:
465  * 
466  *  nameserver <address>
467  *   Must be followed by the IP address of a nameserver.  Several
468  *   nameservers may be specified, and they will be tried in the order
469  *   found.  There is a compiled in limit, currently 5, on the number
470  *   of nameservers.  (libresolv supports only 3 nameservers.)
471  *
472  *  search <domain> ...
473  *   Specifies the search list for queries which specify
474  *   adns_qf_search.  This is a list of domains to append to the query
475  *   domain.  The query domain will be tried as-is either before all
476  *   of these or after them, depending on the ndots option setting
477  *   (see below).
478  *
479  *  domain <domain>
480  *   This is present only for backward compatibility with obsolete
481  *   versions of libresolv.  It should not be used, and is interpreted
482  *   by adns as if it were `search' - note that this is subtly
483  *   different to libresolv's interpretation of this directive.
484  *
485  *  sortlist <addr>/<mask> ...
486  *   Should be followed by a sequence of IP-address and netmask pairs,
487  *   separated by spaces.  They may be specified as
488  *   eg. 172.30.206.0/24 or 172.30.206.0/255.255.255.0.  Currently up
489  *   to 15 pairs may be specified (but note that libresolv only
490  *   supports up to 10).
491  *
492  *  options
493  *   Should followed by one or more options, separated by spaces.
494  *   Each option consists of an option name, followed by optionally
495  *   a colon and a value.  Options are listed below.
496  *
497  * Non-standard directives understood in resolv[-adns].conf:
498  *
499  *  clearnameservers
500  *   Clears the list of nameservers, so that further nameserver lines
501  *   start again from the beginning.
502  *
503  *  include <filename>
504  *   The specified file will be read.
505  *
506  * Additionally, adns will ignore lines in resolv[-adns].conf which
507  * start with a #.
508  *
509  * Standard options understood:
510  *
511  *  debug
512  *   Enables debugging output from the resolver, which will be written
513  *   to stderr.
514  *
515  *  ndots:<count>
516  *   Affects whether queries with adns_qf_search will be tried first
517  *   without adding domains from the searchlist, or whether the bare
518  *   query domain will be tried last.  Queries which contain at least
519  *   <count> dots will be tried bare first.  The default is 1.
520  *
521  * Non-standard options understood:
522  *
523  *  adns_checkc:none
524  *  adns_checkc:entex
525  *  adns_checkc:freq
526  *   Changes the consistency checking frequency; this overrides the
527  *   setting of adns_if_check_entex, adns_if_check_freq, or neither,
528  *   in the flags passed to adns_init.
529  * 
530  * There are a number of environment variables which can modify the
531  * behaviour of adns.  They take effect only if adns_init is used, and
532  * the caller of adns_init can disable them using adns_if_noenv.  In
533  * each case there is both a FOO and an ADNS_FOO; the latter is
534  * interpreted later so that it can override the former.  Unless
535  * otherwise stated, environment variables are interpreted after
536  * resolv[-adns].conf are read, in the order they are listed here.
537  *
538  *  RES_CONF, ADNS_RES_CONF
539  *   A filename, whose contets are in the format of resolv.conf.
540  *
541  *  RES_CONF_TEXT, ADNS_RES_CONF_TEXT
542  *   A string in the format of resolv.conf.
543  *
544  *  RES_OPTIONS, ADNS_RES_OPTIONS
545  *   These are parsed as if they appeared in the `options' line of a
546  *   resolv.conf.  In addition to being parsed at this point in the
547  *   sequence, they are also parsed at the very beginning before
548  *   resolv.conf or any other environment variables are read, so that
549  *   any debug option can affect the processing of the configuration.
550  *
551  *  LOCALDOMAIN, ADNS_LOCALDOMAIN
552  *   These are interpreted as if their contents appeared in a `search'
553  *   line in resolv.conf.
554  */
555
556 int adns_synchronous(adns_state ads,
557                      const char *owner,
558                      adns_rrtype type,
559                      adns_queryflags flags,
560                      adns_answer **answer_r);
561
562 /* NB: if you set adns_if_noautosys then _submit and _check do not
563  * make any system calls; you must use some of the asynch-io event
564  * processing functions to actually get things to happen.
565  */
566
567 int adns_submit(adns_state ads,
568                 const char *owner,
569                 adns_rrtype type,
570                 adns_queryflags flags,
571                 void *context,
572                 adns_query *query_r);
573
574 /* The owner should be quoted in master file format. */
575
576 int adns_check(adns_state ads,
577                adns_query *query_io,
578                adns_answer **answer_r,
579                void **context_r);
580
581 int adns_wait(adns_state ads,
582               adns_query *query_io,
583               adns_answer **answer_r,
584               void **context_r);
585
586 /* same as adns_wait but uses poll(2) internally */
587 int adns_wait_poll(adns_state ads,
588                    adns_query *query_io,
589                    adns_answer **answer_r,
590                    void **context_r);
591
592 void adns_cancel(adns_query query);
593
594 /* The adns_query you get back from _submit is valid (ie, can be
595  * legitimately passed into adns functions) until it is returned by
596  * adns_check or adns_wait, or passed to adns_cancel.  After that it
597  * must not be used.  You can rely on it not being reused until the
598  * first adns_submit or _transact call using the same adns_state after
599  * it became invalid, so you may compare it for equality with other
600  * query handles until you next call _query or _transact.
601  *
602  * _submit and _synchronous return ENOSYS if they don't understand the
603  * query type.
604  */
605
606 int adns_submit_reverse(adns_state ads,
607                         const struct sockaddr *addr,
608                         adns_rrtype type,
609                         adns_queryflags flags,
610                         void *context,
611                         adns_query *query_r);
612 /* type must be _r_ptr or _r_ptr_raw.  _qf_search is ignored.
613  * addr->sa_family must be AF_INET or you get ENOSYS.
614  */
615
616 int adns_submit_reverse_any(adns_state ads,
617                             const struct sockaddr *addr,
618                             const char *rzone,
619                             adns_rrtype type,
620                             adns_queryflags flags,
621                             void *context,
622                             adns_query *query_r);
623 /* For RBL-style reverse `zone's; look up
624  *   <reversed-address>.<zone>
625  * Any type is allowed.  _qf_search is ignored.
626  * addr->sa_family must be AF_INET or you get ENOSYS.
627  */
628
629 void adns_finish(adns_state ads);
630 /* You may call this even if you have queries outstanding;
631  * they will be cancelled.
632  */
633
634
635 void adns_forallqueries_begin(adns_state ads);
636 adns_query adns_forallqueries_next(adns_state ads, void **context_r);
637 /* Iterator functions, which you can use to loop over the outstanding
638  * (submitted but not yet successfuly checked/waited) queries.
639  *
640  * You can only have one iteration going at once.  You may call _begin
641  * at any time; after that, an iteration will be in progress.  You may
642  * only call _next when an iteration is in progress - anything else
643  * may coredump.  The iteration remains in progress until _next
644  * returns 0, indicating that all the queries have been walked over,
645  * or ANY other adns function is called with the same adns_state (or a
646  * query in the same adns_state).  There is no need to explicitly
647  * finish an iteration.
648  *
649  * context_r may be 0.  *context_r may not be set when _next returns 0.
650  */
651
652 void adns_checkconsistency(adns_state ads, adns_query qu);
653 /* Checks the consistency of adns's internal data structures.
654  * If any error is found, the program will abort().
655  * You may pass 0 for qu; if you pass non-null then additional checks
656  * are done to make sure that qu is a valid query.
657  */
658
659 /*
660  * Example expected/legal calling sequence for submit/check/wait:
661  *  adns_init
662  *  adns_submit 1
663  *  adns_submit 2
664  *  adns_submit 3
665  *  adns_wait 1
666  *  adns_check 3 -> EAGAIN
667  *  adns_wait 2
668  *  adns_wait 3
669  *  ....
670  *  adns_finish
671  */
672
673 /*
674  * Entrypoints for generic asynch io:
675  * (these entrypoints are not very useful except in combination with *
676  * some of the other I/O model calls which can tell you which fds to
677  * be interested in):
678  *
679  * Note that any adns call may cause adns to open and close fds, so
680  * you must call beforeselect or beforepoll again just before
681  * blocking, or you may not have an up-to-date list of it's fds.
682  */
683
684 int adns_processany(adns_state ads);
685 /* Gives adns flow-of-control for a bit.  This will never block, and
686  * can be used with any threading/asynch-io model.  If some error
687  * occurred which might cause an event loop to spin then the errno
688  * value is returned.
689  */
690
691 int adns_processreadable(adns_state ads, int fd, const struct timeval *now);
692 int adns_processwriteable(adns_state ads, int fd, const struct timeval *now);
693 int adns_processexceptional(adns_state ads, int fd, const struct timeval *now);
694 /* Gives adns flow-of-control so that it can process incoming data
695  * from, or send outgoing data via, fd.  Very like _processany.  If it
696  * returns zero then fd will no longer be readable or writeable
697  * (unless of course more data has arrived since).  adns will _only_
698  * use that fd and only in the manner specified, regardless of whether
699  * adns_if_noautosys was specified.
700  *
701  * adns_processexceptional should be called when select(2) reports an
702  * exceptional condition, or poll(2) reports POLLPRI.
703  *
704  * It is fine to call _processreabable or _processwriteable when the
705  * fd is not ready, or with an fd that doesn't belong to adns; it will
706  * then just return 0.
707  *
708  * If some error occurred which might prevent an event loop to spin
709  * then the errno value is returned.
710  */
711
712 void adns_processtimeouts(adns_state ads, const struct timeval *now);
713 /* Gives adns flow-of-control so that it can process any timeouts
714  * which might have happened.  Very like _processreadable/writeable.
715  *
716  * now may be 0; if it isn't, *now must be the current time, recently
717  * obtained from gettimeofday.
718  */
719
720 void adns_firsttimeout(adns_state ads,
721                        struct timeval **tv_mod, struct timeval *tv_buf,
722                        struct timeval now);
723 /* Asks adns when it would first like the opportunity to time
724  * something out.  now must be the current time, from gettimeofday.
725  * 
726  * If tv_mod points to 0 then tv_buf must be non-null, and
727  * _firsttimeout will fill in *tv_buf with the time until the first
728  * timeout, and make *tv_mod point to tv_buf.  If adns doesn't have
729  * anything that might need timing out it will leave *tv_mod as 0.
730  *
731  * If *tv_mod is not 0 then tv_buf is not used.  adns will update
732  * *tv_mod if it has any earlier timeout, and leave it alone if it
733  * doesn't.
734  *
735  * This call will not actually do any I/O, or change the fds that adns
736  * is using.  It always succeeds and never blocks.
737  */
738
739 void adns_globalsystemfailure(adns_state ads);
740 /* If serious problem(s) happen which globally affect your ability to
741  * interact properly with adns, or adns's ability to function
742  * properly, you or adns can call this function.
743  *
744  * All currently outstanding queries will be made to fail with
745  * adns_s_systemfail, and adns will close any stream sockets it has
746  * open.
747  *
748  * This is used by adns, for example, if gettimeofday() fails.
749  * Without this the program's event loop might start to spin !
750  *
751  * This call will never block.
752  */
753
754 /*
755  * Entrypoints for select-loop based asynch io:
756  */
757
758 void adns_beforeselect(adns_state ads, int *maxfd, fd_set *readfds,
759                        fd_set *writefds, fd_set *exceptfds,
760                        struct timeval **tv_mod, struct timeval *tv_buf,
761                        const struct timeval *now);
762 /* Find out file descriptors adns is interested in, and when it would
763  * like the opportunity to time something out.  If you do not plan to
764  * block then tv_mod may be 0.  Otherwise, tv_mod and tv_buf are as
765  * for adns_firsttimeout.  readfds, writefds, exceptfds and maxfd_io may
766  * not be 0.
767  *
768  * If tv_mod is 0 on entry then this will never actually do any I/O,
769  * or change the fds that adns is using or the timeouts it wants.  In
770  * any case it won't block, and it will set the timeout to zero if a
771  * query finishes in _beforeselect.
772  */
773
774 void adns_afterselect(adns_state ads, int maxfd, const fd_set *readfds,
775                       const fd_set *writefds, const fd_set *exceptfds,
776                       const struct timeval *now);
777 /* Gives adns flow-of-control for a bit; intended for use after
778  * select.  This is just a fancy way of calling adns_processreadable/
779  * writeable/timeouts as appropriate, as if select had returned the
780  * data being passed.  Always succeeds.
781  */
782
783 /*
784  * Example calling sequence:
785  *
786  *  adns_init _noautosys
787  *  loop {
788  *   adns_beforeselect
789  *   select
790  *   adns_afterselect
791  *   ...
792  *   adns_submit / adns_check
793  *   ...
794  *  }
795  */
796
797 /*
798  * Entrypoints for poll-loop based asynch io:
799  */
800
801 struct pollfd;
802 /* In case your system doesn't have it or you forgot to include
803  * <sys/poll.h>, to stop the following declarations from causing
804  * problems.  If your system doesn't have poll then the following
805  * entrypoints will not be defined in libadns.  Sorry !
806  */
807
808 int adns_beforepoll(adns_state ads, struct pollfd *fds,
809                     int *nfds_io, int *timeout_io,
810                     const struct timeval *now);
811 /* Finds out which fd's adns is interested in, and when it would like
812  * to be able to time things out.  This is in a form suitable for use
813  * with poll(2).
814  * 
815  * On entry, usually fds should point to at least *nfds_io structs.
816  * adns will fill up to that many structs will information for poll,
817  * and record in *nfds_io how many structs it filled.  If it wants to
818  * listen for more structs then *nfds_io will be set to the number
819  * required and _beforepoll will return ERANGE.
820  *
821  * You may call _beforepoll with fds==0 and *nfds_io 0, in which case
822  * adns will fill in the number of fds that it might be interested in
823  * in *nfds_io, and always return either 0 (if it is not interested in
824  * any fds) or ERANGE (if it is).
825  *
826  * NOTE that (unless now is 0) adns may acquire additional fds
827  * from one call to the next, so you must put adns_beforepoll in a
828  * loop, rather than assuming that the second call (with the buffer
829  * size requested by the first) will not return ERANGE.
830  *
831  * adns only ever sets POLLIN, POLLOUT and POLLPRI in its pollfd
832  * structs, and only ever looks at those bits.  POLLPRI is required to
833  * detect TCP Urgent Data (which should not be used by a DNS server)
834  * so that adns can know that the TCP stream is now useless.
835  *
836  * In any case, *timeout_io should be a timeout value as for poll(2),
837  * which adns will modify downwards as required.  If the caller does
838  * not plan to block then *timeout_io should be 0 on entry, or
839  * alternatively, timeout_io may be 0.  (Alternatively, the caller may
840  * use _beforeselect with timeout_io==0 to find out about file
841  * descriptors, and use _firsttimeout is used to find out when adns
842  * might want to time something out.)
843  *
844  * adns_beforepoll will return 0 on success, and will not fail for any
845  * reason other than the fds buffer being too small (ERANGE).
846  *
847  * This call will never actually do any I/O.  If you supply the
848  * current time it will not change the fds that adns is using or the
849  * timeouts it wants.
850  *
851  * In any case this call won't block.
852  */
853
854 #define ADNS_POLLFDS_RECOMMENDED 2
855 /* If you allocate an fds buf with at least RECOMMENDED entries then
856  * you are unlikely to need to enlarge it.  You are recommended to do
857  * so if it's convenient.  However, you must be prepared for adns to
858  * require more space than this.
859  */
860
861 void adns_afterpoll(adns_state ads, const struct pollfd *fds, int nfds,
862                     const struct timeval *now);
863 /* Gives adns flow-of-control for a bit; intended for use after
864  * poll(2).  fds and nfds should be the results from poll().  pollfd
865  * structs mentioning fds not belonging to adns will be ignored.
866  */
867
868
869 adns_status adns_rr_info(adns_rrtype type,
870                          const char **rrtname_r, const char **fmtname_r,
871                          int *len_r,
872                          const void *datap, char **data_r);
873 /*
874  * Get information about a query type, or convert reply data to a
875  * textual form.  type must be specified, and the official name of the
876  * corresponding RR type will be returned in *rrtname_r, and
877  * information about the processing style in *fmtname_r.  The length
878  * of the table entry in an answer for that type will be returned in
879  * in *len_r.  Any or all of rrtname_r, fmtname_r and len_r may be 0.
880  * If fmtname_r is non-null then *fmtname_r may be null on return,
881  * indicating that no special processing is involved.
882  *
883  * data_r be must be non-null iff datap is.  In this case *data_r will
884  * be set to point to a string pointing to a representation of the RR
885  * data in master file format.  (The owner name, timeout, class and
886  * type will not be present - only the data part of the RR.)  The
887  * memory will have been obtained from malloc() and must be freed by
888  * the caller.
889  *
890  * Usually this routine will succeed.  Possible errors include:
891  *  adns_s_nomemory
892  *  adns_s_rrtypeunknown
893  *  adns_s_invaliddata (*datap contained garbage)
894  * If an error occurs then no memory has been allocated,
895  * and *rrtname_r, *fmtname_r, *len_r and *data_r are undefined.
896  *
897  * There are some adns-invented data formats which are not official
898  * master file formats.  These include:
899  *
900  * Mailboxes if __qtf_mail822: these are just included as-is.
901  *
902  * Addresses (adns_rr_addr): these may be of pretty much any type.
903  * The representation is in two parts: first, a word for the address
904  * family (ie, in AF_XXX, the XXX), and then one or more items for the
905  * address itself, depending on the format.  For an IPv4 address the
906  * syntax is INET followed by the dotted quad (from inet_ntoa).
907  * Currently only IPv4 is supported.
908  *
909  * Text strings (as in adns_rr_txt) appear inside double quotes, and
910  * use \" and \\ to represent " and \, and \xHH to represent
911  * characters not in the range 32-126.
912  *
913  * Hostname with addresses (adns_rr_hostaddr): this consists of the
914  * hostname, as usual, followed by the adns_status value, as an
915  * abbreviation, and then a descriptive string (encoded as if it were
916  * a piece of text), for the address lookup, followed by zero or more
917  * addresses enclosed in ( and ).  If the result was a temporary
918  * failure, then a single ?  appears instead of the ( ).  If the
919  * result was a permanent failure then an empty pair of parentheses
920  * appears (which a space in between).  For example, one of the NS
921  * records for greenend.org.uk comes out like
922  *  ns.chiark.greenend.org.uk ok "OK" ( INET 195.224.76.132 )
923  * an MX referring to a nonexistent host might come out like:
924  *  50 sun2.nsfnet-relay.ac.uk nxdomain "No such domain" ( )
925  * and if nameserver information is not available you might get:
926  *  dns2.spong.dyn.ml.org timeout "DNS query timed out" ?
927  */
928
929 const char *adns_strerror(adns_status st);
930 const char *adns_errabbrev(adns_status st);
931 const char *adns_errtypeabbrev(adns_status st);
932 /* Like strerror but for adns_status values.  adns_errabbrev returns
933  * the abbreviation of the error - eg, for adns_s_timeout it returns
934  * "timeout".  adns_errtypeabbrev returns the abbreviation of the
935  * error class: ie, for values up to adns_s_max_XXX it will return the
936  * string XXX.  You MUST NOT call these functions with status values
937  * not returned by the same adns library.
938  */
939
940 #ifdef __cplusplus
941 } /* end of extern "C" */
942 #endif
943 #endif