chiark / gitweb /
Support and test iteration; test return in different order.
[adns.git] / src / adns.h
1 /*
2  * adns.h
3  * - adns user-visible API (single-threaded, without any locking)
4  */
5 /*
6  *  This file is part of adns, which is Copyright (C) 1997-1999 Ian Jackson
7  *  
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 2, or (at your option)
11  *  any later version.
12  *  
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *  
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, write to the Free Software Foundation,
20  *  Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
21  *
22  *  $Id$
23  */
24
25 #ifndef ADNS_H_INCLUDED
26 #define ADNS_H_INCLUDED
27
28 #include <stdio.h>
29
30 #include <sys/socket.h>
31 #include <netinet/in.h>
32
33 /* All struct in_addr anywhere in adns are in NETWORK byte order. */
34
35 typedef struct adns__state *adns_state;
36 typedef struct adns__query *adns_query;
37
38 typedef enum {
39   adns_if_noenv=        0x0001, /* do not look at environment */
40   adns_if_noerrprint=   0x0002, /* never print output to stderr (_debug overrides) */
41   adns_if_noserverwarn= 0x0004, /* do not warn to stderr about duff nameservers etc */
42   adns_if_debug=        0x0008, /* enable all output to stderr plus debug msgs */
43   adns_if_noautosys=    0x0010, /* do not make syscalls at every opportunity */
44   adns_if_eintr=        0x0020, /* allow _wait and _synchronous to return EINTR */
45   adns_if_nosigpipe=    0x0040, /* applic has SIGPIPE set to SIG_IGN, do not protect */
46 } adns_initflags;
47
48 typedef enum {
49   adns_qf_search=          0x000001, /* use the searchlist */
50   adns_qf_usevc=           0x000002, /* use a virtual circuit (TCP connection) */
51   adns_qf_owner=           0x000004, /* fill in the owner field in the answer */
52   adns_qf_quoteok_query=   0x000010, /* allow quote-requiring chars in query domain */
53   adns_qf_quoteok_cname=   0x000020, /* allow ... in CNAME we go via */
54   adns_qf_quoteok_anshost= 0x000040, /* allow ... in answers expected to be hostnames */
55   adns_qf_cname_loose=     0x000100, /* allow refs to CNAMEs - without, get _s_cname */
56   adns_qf_cname_forbid=    0x000200, /* don't follow CNAMEs, instead give _s_cname */
57   adns__qf_internalmask=   0x0ff000
58 } adns_queryflags;
59
60 typedef enum {
61   adns__rrt_typemask=  0x0ffff,
62   adns__qtf_deref=     0x10000, /* dereference domains and perhaps produce extra data */
63   adns__qtf_mail822=   0x20000, /* make mailboxes be in RFC822 rcpt field format */
64   
65   adns_r_none=               0,
66   
67   adns_r_a=                  1,
68   
69   adns_r_ns_raw=             2,
70   adns_r_ns=                    adns_r_ns_raw|adns__qtf_deref,
71   
72   adns_r_cname=              5,
73   
74   adns_r_soa_raw=            6,
75   adns_r_soa=                   adns_r_soa_raw|adns__qtf_mail822, 
76   
77   adns_r_ptr_raw=           12,
78   adns_r_ptr=                   adns_r_ptr_raw|adns__qtf_deref,
79   
80   adns_r_hinfo=             13,  
81   
82   adns_r_mx_raw=            15,
83   adns_r_mx=                    adns_r_mx_raw|adns__qtf_deref,
84   
85   adns_r_txt=               16,
86   
87   adns_r_rp_raw=            17,
88   adns_r_rp=                    adns_r_rp_raw|adns__qtf_mail822,
89
90   adns_r_addr=                  adns_r_a|adns__qtf_deref
91   
92 } adns_rrtype;
93
94 /* In queries without qf_quoteok_*, all domains must have standard
95  * legal syntax.  In queries _with_ qf_quoteok_*, domains in the query
96  * or response may contain any characters, quoted according to RFC1035
97  * 5.1.  On input to adns, the char* is a pointer to the interior of a
98  * " delimited string, except that " may appear in it, and on output,
99  * the char* is a pointer to a string which would be legal either
100  * inside or outside " delimiters, and any characters not usually
101  * legal in domain names will be quoted as \X (if the character is
102  * 33-126 except \ and ") or \DDD.
103  *
104  * Do not ask for _raw records containing mailboxes without
105  * specifying _qf_anyquote.
106  */
107
108 typedef enum {
109   adns_s_ok,
110
111   /* locally induced errors */
112   adns_s_nomemory,
113   adns_s_unknownrrtype,
114   adns_s_systemfail,
115
116   adns_s_max_localfail= 29,
117   
118   /* remotely induced errors, detected locally */
119   adns_s_timeout,
120   adns_s_allservfail,
121   adns_s_norecurse,
122   adns_s_invalidresponse,
123   adns_s_unknownformat,
124
125   adns_s_max_remotefail= 59,
126   
127   /* remotely induced errors, reported by remote server to us */
128   adns_s_rcodeservfail,
129   adns_s_rcodeformaterror,
130   adns_s_rcodenotimplemented,
131   adns_s_rcoderefused,
132   adns_s_rcodeunknown,
133
134   adns_s_max_tempfail= 99,
135
136   /* remote configuration errors */
137   adns_s_inconsistent, /* PTR gives domain whose A does not exist and match */
138   adns_s_prohibitedcname, /* CNAME found where eg A expected (not if _qf_loosecname) */
139   adns_s_answerdomaininvalid,
140   adns_s_answerdomaintoolong,
141   adns_s_invaliddata,
142   
143   adns_s_max_misconfig= 199,
144
145   /* permanent problems with the query */
146   adns_s_querydomainwrong,
147   adns_s_querydomaininvalid,
148   adns_s_querydomaintoolong,
149   
150   adns_s_max_misquery= 299,
151
152   /* permanent errors */
153   adns_s_nxdomain,
154   adns_s_nodata,
155   
156 } adns_status;
157
158 typedef struct {
159   int len;
160   union {
161     struct sockaddr sa;
162     struct sockaddr_in inet;
163   } addr;
164 } adns_rr_addr;
165
166 typedef struct {
167   char *host;
168   adns_status astatus;
169   int naddrs; /* temp fail => -1, perm fail => 0, s_ok => >0 */
170   adns_rr_addr *addrs;
171 } adns_rr_hostaddr;
172
173 typedef struct {
174   char *(array[2]);
175 } adns_rr_strpair;
176
177 typedef struct {
178   int i;
179   adns_rr_hostaddr ha;
180 } adns_rr_inthostaddr;
181
182 typedef struct {
183   /* Used both for mx_raw, in which case i is the preference and str the domain,
184    * and for txt, in which case each entry has i for the `text' length,
185    * and str for the data (which will have had an extra nul appended
186    * so that if it was plain text it is now a null-terminated string).
187    */
188   int i;
189   char *str;
190 } adns_rr_intstr;
191
192 typedef struct {
193   adns_rr_intstr array[2];
194 } adns_rr_intstrpair;
195
196 typedef struct {
197   char *mname, *rname;
198   unsigned long serial, refresh, retry, expire, minimum;
199 } adns_rr_soa;
200
201 typedef struct {
202   adns_status status;
203   char *cname; /* always NULL if query was for CNAME records */
204   char *owner; /* only set if requested in query flags */
205   adns_rrtype type; /* guaranteed to be same as in query */
206   time_t expires; /* expiry time, defined only if _s_ok, nxdomain or nodata. NOT TTL! */
207   int nrrs, rrsz;
208   union {
209     void *untyped;
210     unsigned char *bytes;
211     char *(*str);                     /* ns_raw, cname, ptr, ptr_raw */
212     adns_rr_intstr *(*manyistr);      /* txt (list of strings ends with i=-1, str=0) */
213     adns_rr_addr *addr;               /* addr */
214     struct in_addr *inaddr;           /* a */
215     adns_rr_hostaddr *hostaddr;       /* ns */
216     adns_rr_intstrpair *intstrpair;   /* hinfo */
217     adns_rr_strpair *strpair;         /* rp, rp_raw */
218     adns_rr_inthostaddr *inthostaddr; /* mx */
219     adns_rr_intstr *intstr;           /* mx_raw */
220     adns_rr_soa *soa;                 /* soa, soa_raw */
221   } rrs;
222 } adns_answer;
223
224 /* Memory management:
225  *  adns_state and adns_query are actually pointers to malloc'd state;
226  *  On submission questions are copied, including the owner domain;
227  *  Answers are malloc'd as a single piece of memory; pointers in the
228  *  answer struct point into further memory in the answer.
229  * query_io:
230  *  Must always be non-null pointer;
231  *  If *query_io is 0 to start with then any query may be returned;
232  *  If *query_io is !0 adns_query then only that query may be returned.
233  *  If the call is successful, *query_io, *answer_r, and *context_r
234  *  will all be set.
235  * Errors:
236  *  Return values are 0 or an errno value.
237  *
238  *  For _init, _init_strcfg, _submit and _synchronous, system errors
239  *  (eg, failure to create sockets, malloc failure, etc.) return errno
240  *  values.
241  * 
242  *  For _wait and _check failures are reported in the answer
243  *  structure, and only 0, ESRCH or (for _check) EWOULDBLOCK is
244  *  returned: if no (appropriate) requests are done adns_check returns
245  *  EWOULDBLOCK; if no (appropriate) requests are outstanding both
246  *  adns_query and adns_wait return ESRCH.
247  *
248  *  Additionally, _wait can return EINTR if you set adns_if_eintr.
249  *
250  *  All other errors (nameserver failure, timed out connections, &c)
251  *  are returned in the status field of the answer.  After a
252  *  successful _wait or _check, if status is nonzero then nrrs will be
253  *  0, otherwise it will be >0.  type will always be the type
254  *  requested.
255  */
256
257 int adns_init(adns_state *newstate_r, adns_initflags flags,
258               FILE *diagfile /*0=>stderr*/);
259
260 int adns_init_strcfg(adns_state *newstate_r, adns_initflags flags,
261                      FILE *diagfile /*0=>discard*/, const char *configtext);
262
263 int adns_synchronous(adns_state ads,
264                      const char *owner,
265                      adns_rrtype type,
266                      adns_queryflags flags,
267                      adns_answer **answer_r);
268
269 /* NB: if you set adns_if_noautosys then _submit and _check do not
270  * make any system calls; you must use some of the asynch-io event
271  * processing functions to actually get things to happen.
272  */
273
274 int adns_submit(adns_state ads,
275                 const char *owner,
276                 adns_rrtype type,
277                 adns_queryflags flags,
278                 void *context,
279                 adns_query *query_r);
280
281 int adns_check(adns_state ads,
282                adns_query *query_io,
283                adns_answer **answer_r,
284                void **context_r);
285
286 int adns_wait(adns_state ads,
287               adns_query *query_io,
288               adns_answer **answer_r,
289               void **context_r);
290
291 void adns_cancel(adns_query query);
292
293 /* The adns_query you get back from _submit is valid (ie, can be
294  * legitimately passed into adns functions) until it is returned by
295  * adns_check or adns_wait, or passed to adns_cancel.  After that it
296  * must not be used.  You can rely on it not being reused until the
297  * first adns_submit or _transact call using the same adns_state after
298  * it became invalid, so you may compare it for equality with other
299  * query handles until you next call _query or _transact.
300  */
301
302 void adns_finish(adns_state ads);
303 /* You may call this even if you have queries outstanding;
304  * they will be cancelled.
305  */
306
307
308 void adns_forallqueries_begin(adns_state ads);
309 adns_query adns_forallqueries_next(adns_state ads, void **context_r);
310 /* Iterator functions, which you can use to loop over the outstanding
311  * (submitted but not yet successfuly checked/waited) queries.
312  *
313  * You can only have one iteration going at once.  You may call _begin
314  * at any time; after that, an iteration will be in progress.  You may
315  * only call _next when an iteration is in progress - anything else
316  * may coredump.  The iteration remains in progress until _next
317  * returns 0, indicating that all the queries have been walked over,
318  * or ANY other adns function is called with the same adns_state (or a
319  * query in the same adns_state).  There is no need to explicitly
320  * finish an iteration.
321  *
322  * context_r may be 0.  *context_r may not be set when _next returns 0.
323  */
324
325 /*
326  * Example expected/legal calling sequence for submit/check/wait:
327  *  adns_init
328  *  adns_submit 1
329  *  adns_submit 2
330  *  adns_submit 3
331  *  adns_wait 1
332  *  adns_check 3 -> EWOULDBLOCK
333  *  adns_wait 2
334  *  adns_wait 3
335  *  ....
336  *  adns_finish
337  */
338
339 /*
340  * Entrypoints for generic asynch io:
341  * (these entrypoints are not very useful except in combination with *
342  * some of the other I/O model calls which can tell you which fds to
343  * be interested in):
344  *
345  * Note that any adns call may cause adns to open and close fds, so
346  * you must call beforeselect or beforepoll again just before
347  * blocking, or you may not have an up-to-date list of it's fds.
348  */
349
350 int adns_processany(adns_state ads);
351 /* Gives adns flow-of-control for a bit.  This will never block, and
352  * can be used with any threading/asynch-io model.  If some error
353  * occurred which might cause an event loop to spin then the errno
354  * value is returned.
355  */
356
357 int adns_processreadable(adns_state ads, int fd, const struct timeval *now);
358 int adns_processwriteable(adns_state ads, int fd, const struct timeval *now);
359 int adns_processexceptional(adns_state ads, int fd, const struct timeval *now);
360 /* Gives adns flow-of-control so that it can process incoming data
361  * from, or send outgoing data via, fd.  Very like _processany.  If it
362  * returns zero then fd will no longer be readable or writeable
363  * (unless of course more data has arrived since).  adns will _only_
364  * that fd and only in the manner specified, regardless of whether
365  * adns_if_noautosys was specified.
366  *
367  * adns_processexceptional should be called when select(2) reports an
368  * exceptional condition, or poll(2) reports POLLPRI.
369  *
370  * It is fine to call _processreabable or _processwriteable when the
371  * fd is not ready, or with an fd that doesn't belong to adns; it will
372  * then just return 0.
373  *
374  * If some error occurred which might prevent an event loop to spin
375  * then the errno value is returned.
376  */
377
378 void adns_processtimeouts(adns_state ads, const struct timeval *now);
379 /* Gives adns flow-of-control so that it can process any timeouts
380  * which might have happened.  Very like _processreadable/writeable.
381  *
382  * now may be 0; if it isn't, *now must be the current time, recently
383  * obtained from gettimeofday.
384  */
385
386 void adns_firsttimeout(adns_state ads,
387                        struct timeval **tv_mod, struct timeval *tv_buf,
388                        struct timeval now);
389 /* Asks adns when it would first like the opportunity to time
390  * something out.  now must be the current time, from gettimeofday.
391  * 
392  * If tv_mod points to 0 then tv_buf must be non-null, and
393  * _firsttimeout will fill in *tv_buf with the time until the first
394  * timeout, and make *tv_mod point to tv_buf.  If adns doesn't have
395  * anything that might need timing out it will leave *tv_mod as 0.
396  *
397  * If *tv_mod is not 0 then tv_buf is not used.  adns will update
398  * *tv_mod if it has any earlier timeout, and leave it alone if it
399  * doesn't.
400  *
401  * This call will not actually do any I/O, or change the fds that adns
402  * is using.  It always succeeds and never blocks.
403  */
404
405 void adns_globalsystemfailure(adns_state ads);
406 /* If serious problem(s) happen which globally affect your ability to
407  * interact properly with adns, or adns's ability to function
408  * properly, you or adns can call this function.
409  *
410  * All currently outstanding queries will be made to fail with
411  * adns_s_systemfail, and adns will close any stream sockets it has
412  * open.
413  *
414  * This is used by adns, for example, if gettimeofday() fails.
415  * Without this the program's event loop might start to spin !
416  *
417  * This call will never block.
418  */
419
420 /*
421  * Entrypoints for select-loop based asynch io:
422  */
423
424 void adns_beforeselect(adns_state ads, int *maxfd, fd_set *readfds,
425                        fd_set *writefds, fd_set *exceptfds,
426                        struct timeval **tv_mod, struct timeval *tv_buf,
427                        const struct timeval *now);
428 /* Find out file descriptors adns is interested in, and when it would
429  * like the opportunity to time something out.  If you do not plan to
430  * block then tv_mod may be 0.  Otherwise, tv_mod and tv_buf are as
431  * for adns_firsttimeout.  readfds, writefds, exceptfds and maxfd_io may
432  * not be 0.
433  *
434  * If *now is not 0 then this will never actually do any I/O, or
435  * change the fds that adns is using or the timeouts it wants.  In any
436  * case it won't block.
437  */
438
439 void adns_afterselect(adns_state ads, int maxfd, const fd_set *readfds,
440                       const fd_set *writefds, const fd_set *exceptfds,
441                       const struct timeval *now);
442 /* Gives adns flow-of-control for a bit; intended for use after
443  * select.  This is just a fancy way of calling adns_processreadable/
444  * writeable/timeouts as appropriate, as if select had returned the
445  * data being passed.  Always succeeds.
446  */
447
448 /*
449  * Example calling sequence:
450  *
451  *  adns_init _noautosys
452  *  loop {
453  *   adns_beforeselect
454  *   select
455  *   adns_afterselect
456  *   ...
457  *   adns_submit / adns_check
458  *   ...
459  *  }
460  */
461
462 /*
463  * Entrypoints for poll-loop based asynch io:
464  */
465
466 struct pollfd;
467 /* In case your system doesn't have it or you forgot to include
468  * <sys/poll.h>, to stop the following declarations from causing
469  * problems.  If your system doesn't have poll then the following
470  * entrypoints will not be defined in libadns.  Sorry !
471  */
472
473 int adns_beforepoll(adns_state ads, struct pollfd *fds, int *nfds_io, int *timeout_io,
474                     const struct timeval *now);
475 /* Finds out which fd's adns is interested in, and when it would like
476  * to be able to time things out.  This is in a form suitable for use
477  * with poll(2).
478  * 
479  * On entry, usually fds should point to at least *nfds_io structs.
480  * adns will fill up to that many structs will information for poll,
481  * and record in *nfds_io how many structs it filled.  If it wants to
482  * listen for more structs then *nfds_io will be set to the number
483  * required and _beforepoll will return ERANGE.
484  *
485  * You may call _beforepoll with fds==0 and *nfds_io 0, in which case
486  * adns will fill in the number of fds that it might be interested in
487  * in *nfds_io, and always return either 0 (if it is not interested in
488  * any fds) or ERANGE (if it is).
489  *
490  * NOTE that (unless timeout_io is 0) adns may acquire additional fds
491  * from one call to the next, so you must put adns_beforepoll in a
492  * loop, rather than assuming that the second call (with the buffer
493  * size requested by the first) will not return ERANGE.
494  *
495  * adns only ever sets POLLIN, POLLOUT and POLLPRI in its pollfd
496  * structs, and only ever looks at those bits.  POLLPRI is required to
497  * detect TCP Urgent Data (which should not be used by a DNS server)
498  * so that adns can know that the TCP stream is now useless.
499  *
500  * In any case, *timeout_io should be a timeout value as for poll(2),
501  * which adns will modify downwards as required.  If the caller does
502  * not plan to block then *timeout_io should be 0 on entry, or
503  * alternatively, timeout_io may be 0.  (Alternatively, the caller may
504  * use _beforeselect with timeout_io==0 to find out about file
505  * descriptors, and use _firsttimeout is used to find out when adns
506  * might want to time something out.)
507  *
508  * adns_beforepoll will return 0 on success, and will not fail for any
509  * reason other than the fds buffer being too small (ERANGE).
510  *
511  * This call will never actually do any I/O, or change the fds that
512  * adns is using or the timeouts it wants; and in any case it won't
513  * block.
514  */
515
516 #define ADNS_POLLFDS_RECOMMENDED 2
517 /* If you allocate an fds buf with at least RECOMMENDED entries then
518  * you are unlikely to need to enlarge it.  You are recommended to do
519  * so if it's convenient.  However, you must be prepared for adns to
520  * require more space than this.
521  */
522
523 void adns_afterpoll(adns_state ads, const struct pollfd *fds, int nfds,
524                     const struct timeval *now);
525 /* Gives adns flow-of-control for a bit; intended for use after
526  * poll(2).  fds and nfds should be the results from poll().  pollfd
527  * structs mentioning fds not belonging to adns will be ignored.
528  */
529
530
531 adns_status adns_rr_info(adns_rrtype type,
532                          const char **rrtname_r, const char **fmtname_r,
533                          int *len_r,
534                          const void *datap, char **data_r);
535 /* Gets information in human-readable (but non-i18n) form
536  * for eg debugging purposes.  type must be specified,
537  * and the official name of the corresponding RR type will
538  * be returned in *rrtname_r, and information about the processing
539  * style in *fmtname_r.  The length of the table entry in an answer
540  * for that type will be returned in in *len_r.
541  * Any or all of rrtname_r, fmtname_r and len_r may be 0.
542  * If fmtname_r is non-null then *fmtname_r may be
543  * null on return, indicating that no special processing is
544  * involved.
545  *
546  * data_r be must be non-null iff datap is.  In this case
547  * *data_r will be set to point to a human-readable text
548  * string representing the RR data.  The text will have
549  * been obtained from malloc() and must be freed by the caller.
550  *
551  * Usually this routine will succeed.  Possible errors include:
552  *  adns_s_nomemory
553  *  adns_s_rrtypeunknown
554  *  adns_s_invaliddata (*datap contained garbage)
555  * If an error occurs then no memory has been allocated,
556  * and *rrtname_r, *fmtname_r, *len_r and *data_r are undefined.
557  */
558
559 const char *adns_strerror(adns_status st);
560 const char *adns_errabbrev(adns_status st);
561 /* Like strerror but for adns_status values.  adns_errabbrev returns
562  * the abbreviation of the error - eg, for adns_s_timeout it returns
563  * "timeout".  You MUST NOT call these functions with status values
564  * not returned by the same adns library.
565  */
566
567 #endif