chiark / gitweb /
malloc(0)->0 fixes.
[adns.git] / src / internal.h
1 /*
2  * internal.h
3  * - declarations of private objects with external linkage (adns__*)
4  * - definitons of internal macros
5  * - comments regarding library data structures
6  */
7 /*
8  *  This file is part of adns, which is Copyright (C) 1997, 1998 Ian Jackson
9  *  
10  *  This program is free software; you can redistribute it and/or modify
11  *  it under the terms of the GNU General Public License as published by
12  *  the Free Software Foundation; either version 2, or (at your option)
13  *  any later version.
14  *  
15  *  This program is distributed in the hope that it will be useful,
16  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *  GNU General Public License for more details.
19  *  
20  *  You should have received a copy of the GNU General Public License
21  *  along with this program; if not, write to the Free Software Foundation,
22  *  Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 
23  */
24
25 #ifndef ADNS_INTERNAL_H_INCLUDED
26 #define ADNS_INTERNAL_H_INCLUDED
27
28 #define PRINTFFORMAT(a,b) __attribute__((format(printf,a,b)))
29 typedef unsigned char byte;
30
31 #include <stdarg.h>
32 #include <assert.h>
33 #include <unistd.h>
34
35 #include <sys/time.h>
36
37 #include "adns.h"
38
39 /* Configuration and constants */
40
41 #define MAXSERVERS 5
42 #define UDPMAXRETRIES /*15*/5
43 #define UDPRETRYMS 2000
44 #define TCPMS 30000
45 #define LOCALRESOURCEMS 20
46
47 #define DNS_PORT 53
48 #define DNS_MAXUDP 512
49 #define DNS_MAXDOMAIN 255
50 #define DNS_HDRSIZE 12
51 #define DNS_CLASS_IN 1
52
53 typedef enum {
54   rcode_noerror,
55   rcode_formaterror,
56   rcode_servfail,
57   rcode_nxdomain,
58   rcode_notimp,
59   rcode_refused
60 } dns_rcode;
61
62 /* Shared data structures */
63
64 typedef union {
65   adns_status status;
66   char *cp;
67   adns_rrtype type;
68   int i;
69   struct in_addr ia;
70   unsigned long ul;
71 } rr_align;
72
73 typedef struct {
74   int used, avail;
75   byte *buf;
76 } vbuf;
77
78 typedef union {
79   void *ext;
80   int dmaddr_index;
81 } qcontext;
82
83 typedef struct {
84   adns_rrtype type;
85   const char *name;
86   int rrsz;
87
88   adns_status (*parse)(adns_query qu, int serv,
89                        const byte *dgram, int dglen, int cbyte, int max,
90                        void *store_r);
91   /* Parse one RR, in dgram of length dglen, starting at cbyte and
92    * extending until at most max.
93    *
94    * The RR should be stored at *store_r, of length qu->typei->rrsz.
95    *
96    * If there is an overrun which might indicate truncation, it should set
97    * *rdstart to -1; otherwise it may set it to anything else positive.
98    */
99
100   void (*makefinal)(adns_query qu, void *data);
101   /* Change memory management of *data.
102    * Previously, used alloc_interim, now use alloc_final.
103    */
104 } typeinfo;
105
106 typedef struct allocnode {
107   struct allocnode *next;
108 } allocnode;
109
110 union maxalign {
111   byte d[1];
112   struct in_addr ia;
113   long l;
114   void *p;
115   void (*fp)(void);
116   union maxalign *up;
117 } data;
118
119 struct adns__query {
120   adns_state ads;
121   enum { query_udp, query_tcpwait, query_tcpsent, query_child, query_done } state;
122   adns_query back, next, parent;
123   struct { adns_query head, tail; } children;
124   struct { adns_query back, next; } siblings;
125   struct allocnode *allocations;
126   int interim_allocd;
127   void *final_allocspace;
128   
129   const typeinfo *typei;
130   char *query_dgram;
131   int query_dglen;
132   
133   vbuf vb;
134   /* General-purpose messing-about buffer.
135    * Wherever a `big' interface is crossed, this may be corrupted/changed
136    * unless otherwise specified.
137    */
138
139   adns_answer *answer;
140   /* This is allocated when a query is submitted, to avoid being unable
141    * to relate errors to queries if we run out of memory.  During
142    * query processing status, rrs is 0.  cname is set if
143    * we found a cname (this corresponds to cname_dgram in the query
144    * structure).  type is set from the word go.  nrrs and rrs
145    * are set together, when we find how many rrs there are.
146    */
147   
148   byte *cname_dgram;
149   int cname_dglen, cname_begin;
150   /* If non-0, has been allocated using . */
151   
152   int id, flags, udpretries;
153   int udpnextserver;
154   unsigned long udpsent, tcpfailed; /* bitmap indexed by server */
155   struct timeval timeout;
156   qcontext context;
157
158   /* Possible states:
159    *
160    *  state   Queue   child  id   nextudpserver  sentudp     failedtcp
161    *                              
162    *  udp     NONE    null   >=0  0              zero        zero
163    *  udp     timew   null   >=0  any            nonzero     zero
164    *  udp     NONE    null   >=0  any            nonzero     zero
165    *                              
166    *  tcpwait timew   null   >=0  irrelevant     zero        any
167    *  tcpsent timew   null   >=0  irrelevant     zero        any
168    *                              
169    *  child   childw  set    >=0  irrelevant     irrelevant  irrelevant
170    *  done    output  null   -1   irrelevant     irrelevant  irrelevant
171    *
172    *                          +------------------------+
173    *             START -----> |      udp/NONE          |
174    *                          +------------------------+
175    *                         /                       |\  \
176    *        too big for UDP /             UDP timeout  \  \ send via UDP
177    *        do this ASAP!  /              more retries  \  \   do this ASAP!
178    *                     |_                  desired     \  _|
179    *              +---------------+                     +-----------+
180    *              | tcpwait/timew | ____                | udp/timew |
181    *              +---------------+     \               +-----------+
182    *                    |  ^             |                 | |
183    *     TCP conn'd;    |  | TCP died    |                 | |
184    *     send via TCP   |  | more        |     UDP timeout | |
185    *     do this ASAP!  |  | servers     |      no more    | |
186    *                    v  | to try      |      retries    | |
187    *              +---------------+      |      desired    | |
188    *              | tcpsent/timew | ____ |                 | |
189    *              +---------------+     \|                 | |
190    *                  \   \ TCP died     | TCP             | |
191    *                   \   \ no more     | timeout         / |
192    *                    \   \ servers    |                /  |
193    *                     \   \ to try    |               /   |
194    *                  got \   \          v             |_    / got
195    *                 reply \   _| +------------------+      / reply
196    *                        \     | done/output FAIL |     /
197    *                         \    +------------------+    /
198    *                          \                          /
199    *                           _|                      |_
200    *                             (..... got reply ....)
201    *                              /                   \
202    *        need child query/ies /                     \ no child query
203    *                            /                       \
204    *                          |_                         _|
205    *                +--------------+                   +----------------+
206    *                | child/childw | ----------------> | done/output OK |
207    *                +--------------+  children done    +----------------+
208    */
209 };
210
211 struct adns__state {
212   adns_initflags iflags;
213   FILE *diagfile;
214   struct { adns_query head, tail; } timew, childw, output;
215   int nextid, udpsocket, tcpsocket;
216   vbuf tcpsend, tcprecv;
217   int nservers, tcpserver;
218   enum adns__tcpstate { server_disconnected, server_connecting, server_ok } tcpstate;
219   struct timeval tcptimeout;
220   struct server {
221     struct in_addr addr;
222   } servers[MAXSERVERS];
223 };
224
225 /* From setup.c: */
226
227 int adns__setnonblock(adns_state ads, int fd); /* => errno value */
228
229 /* From general.c: */
230
231 void adns__vdiag(adns_state ads, const char *pfx, adns_initflags prevent,
232                  int serv, adns_query qu, const char *fmt, va_list al);
233
234 void adns__debug(adns_state ads, int serv, adns_query qu,
235                  const char *fmt, ...) PRINTFFORMAT(4,5);
236 void adns__warn(adns_state ads, int serv, adns_query qu,
237                 const char *fmt, ...) PRINTFFORMAT(4,5);
238 void adns__diag(adns_state ads, int serv, adns_query qu,
239                 const char *fmt, ...) PRINTFFORMAT(4,5);
240
241 int adns__vbuf_ensure(vbuf *vb, int want);
242 int adns__vbuf_appendstr(vbuf *vb, const char *data);
243 int adns__vbuf_append(vbuf *vb, const byte *data, int len);
244 /* 1=>success, 0=>realloc failed */
245 void adns__vbuf_appendq(vbuf *vb, const byte *data, int len);
246 void adns__vbuf_init(vbuf *vb);
247 void adns__vbuf_free(vbuf *vb);
248
249 const char *adns__diag_domain(adns_state ads, int serv, adns_query qu, vbuf *vb,
250                               int flags, const byte *dgram, int dglen, int cbyte);
251 /* Unpicks a domain in a datagram and returns a string suitable for
252  * printing it as.  Never fails - if an error occurs, it will
253  * return some kind of string describing the error.
254  *
255  * serv may be -1 and qu may be 0.  vb must have been initialised,
256  * and will be left in an arbitrary consistent state.
257  *
258  * Returns either vb->buf, or a pointer to a string literal.  Do not modify
259  * vb before using the return value.
260  */
261   
262 /* From transmit.c: */
263
264 adns_status adns__mkquery(adns_state ads, vbuf *vb, int *id_r,
265                           const char *owner, int ol,
266                           const typeinfo *typei, adns_queryflags flags);
267 /* Assembles a query packet in vb, and returns id at *id_r. */
268
269 void adns__query_tcp(adns_query qu, struct timeval now);
270 /* Query must be in state tcpwait/timew; it will be moved to a new state
271  * if possible and no further processing can be done on it for now.
272  * (Resulting state is one of tcpwait/timew (if server not connected),
273  *  tcpsent/timew, child/childw or done/output.)
274  *
275  * adns__tcp_tryconnect should already have been called - _tcp
276  * will only use an existing connection (if there is one), which it
277  * may break.  If the conn list lost then the caller is responsible for any
278  * reestablishment and retry.
279  */
280
281 void adns__query_udp(adns_query qu, struct timeval now);
282 /* Query must be in state udp/NONE; it will be moved to a new state,
283  * and no further processing can be done on it for now.
284  * (Resulting state is one of udp/timew, tcpwait/timew (if server not connected),
285  *  tcpsent/timew, child/childw or done/output.)
286  */
287
288 /* From query.c: */
289
290 int adns__internal_submit(adns_state ads, adns_query *query_r,
291                           const typeinfo *typei, vbuf *qumsg_vb, int id,
292                           adns_queryflags flags, struct timeval now,
293                           adns_status failstat, const qcontext *ctx);
294 /* Submits a query (for internal use, called during external submits).
295  *
296  * The new query is returned in *query_r, or we return adns_s_nomemory.
297  *
298  * The query datagram should already have been assembled in qumsg_vb;
299  * the memory for it is _taken over_ by this routine whether it
300  * succeeds or fails (if it succeeds, the vbuf is reused for qu->vb).
301  *
302  * If failstat is nonzero then if we are successful in creating the query
303  * it is immediately failed with code failstat (but _submit still succeds).
304  *
305  * ctx is copied byte-for-byte into the query.
306  */
307
308 void *adns__alloc_interim(adns_query qu, size_t sz);
309 /* Allocates some memory, and records which query it came from
310  * and how much there was.
311  *
312  * If an error occurs in the query, all its memory is simply freed.
313  *
314  * If the query succeeds, one large buffer will be made which is
315  * big enough for all these allocations, and then adns__alloc_final
316  * will get memory from this buffer.
317  *
318  * _alloc_interim can fail, in which case it will fail the query too,
319  * so nothing more need be done with it.
320  *
321  * adns__alloc_interim(qu,0) will not return 0, but it will not
322  * necessarily return a distinct pointer each time.
323  */
324
325 void *adns__alloc_mine(adns_query qu, size_t sz);
326 /* Like _interim, but does not record the length for later
327  * copying into the answer.  This just ensures that the memory
328  * will be freed when we're done with the query.
329  */
330
331 void *adns__alloc_final(adns_query qu, size_t sz);
332 /* Cannot fail, and cannot return 0.
333  */
334
335 void adns__makefinal_block(adns_query qu, void **blpp, size_t sz);
336 void adns__makefinal_str(adns_query qu, char **strp);
337
338 void adns__reset_cnameonly(adns_query qu);
339 /* Resets all of the memory management stuff etc. to
340  * take account of only the CNAME.  Used when we find an error somewhere
341  * and want to just report the error (with perhaps CNAME info), and also
342  * when we're halfway through RRs in a datagram and discover that we
343  * need to retry the query.
344  */
345
346 void adns__query_done(adns_query qu);
347 void adns__query_fail(adns_query qu, adns_status stat);
348    
349 /* From reply.c: */
350
351 void adns__procdgram(adns_state ads, const byte *dgram, int len,
352                      int serv, struct timeval now);
353
354 /* From types.c: */
355
356 const typeinfo *adns__findtype(adns_rrtype type);
357
358 /* From parse.c: */
359
360 typedef struct {
361   adns_state ads;
362   adns_query qu;
363   int serv;
364   const byte *dgram;
365   int dglen, max, cbyte, namelen;
366   int *dmend_r;
367 } findlabel_state;
368
369 void adns__findlabel_start(findlabel_state *fls, adns_state ads,
370                            int serv, adns_query qu,
371                            const byte *dgram, int dglen, int max,
372                            int dmbegin, int *dmend_rlater);
373 /* Finds labels in a domain in a datagram.
374  *
375  * Call this routine first.
376  * dmend_rlater may be null.  ads (and of course fls) may not be.
377  * serv may be -1, qu may be null - they are for error reporting.
378  */
379
380 adns_status adns__findlabel_next(findlabel_state *fls, int *lablen_r, int *labstart_r);
381 /* Then, call this one repeatedly.
382  *
383  * It will return adns_s_ok if all is well, and tell you the length
384  * and start of successive labels.  labstart_r may be null, but
385  * lablen_r must not be.
386  *
387  * After the last label, it will return with *lablen_r zero.
388  * Do not then call it again; instead, just throw away the findlabel_state.
389  *
390  * *dmend_rlater will have been set to point to the next part of
391  * the datagram after the label (or after the uncompressed part,
392  * if compression was used).  *namelen_rlater will have been set
393  * to the length of the domain name (total length of labels plus
394  * 1 for each intervening dot).
395  *
396  * If the datagram appears to be truncated, *lablen_r will be -1.
397  * *dmend_rlater, *labstart_r and *namelen_r may contain garbage.
398  * Do not call _next again.
399  *
400  * There may also be errors, in which case *dmend_rlater,
401  * *namelen_rlater, *lablen_r and *labstart_r may contain garbage.
402  * Do not then call findlabel_next again.
403  */
404
405 adns_status adns__parse_domain(adns_state ads, int serv, adns_query qu,
406                                vbuf *vb, int flags,
407                                const byte *dgram, int dglen, int *cbyte_io, int max);
408 /* vb must already have been initialised; it will be reset if necessary.
409  * If there is truncation, vb->used will be set to 0; otherwise
410  * (if there is no error) vb will be null-terminated.
411  * If there is an error vb and *cbyte_io may be left indeterminate.
412  *
413  * serv may be -1 and qu may be 0 - they are used for error reporting only.
414  */
415
416 adns_status adns__findrr(adns_query qu, int serv,
417                          const byte *dgram, int dglen, int *cbyte_io,
418                          int *type_r, int *class_r, int *rdlen_r, int *rdstart_r,
419                          int *ownermatchedquery_r);
420   /* Finds the extent and some of the contents of an RR in a datagram
421    * and does some checks.  The datagram is *dgram, length dglen, and
422    * the RR starts at *cbyte_io (which is updated afterwards to point
423    * to the end of the RR).
424    *
425    * The type, class and RRdata length and start are returned iff
426    * the corresponding pointer variables are not null.  type_r and
427    * class_r may not be null.
428    *
429    * If ownermatchedquery_r != 0 then the owner domain of this
430    * RR will be compared with that in the query (or, if the query
431    * has gone to a CNAME lookup, with the canonical name).
432    * In this case, *ownermatchedquery_r will be set to 0 or 1.
433    * The query datagram (or CNAME datagram) MUST be valid and not truncated.
434    *
435    * If there is truncation then *type_r will be set to -1 and
436    * *cbyte_io, *class_r, *rdlen_r, *rdstart_r and *eo_matched_r will be
437    * undefined.
438    *
439    * qu must obviously be non-null.
440    *
441    * If an error is returned then *type_r will be undefined too.
442    */
443
444 int vbuf__append_quoted1035(vbuf *vb, const byte *buf, int len);
445
446 /* From event.c: */
447
448 void adns__tcp_broken(adns_state ads, const char *what, const char *why);
449 void adns__tcp_tryconnect(adns_state ads, struct timeval now);
450
451 void adns__autosys(adns_state ads, struct timeval now);
452 /* Make all the system calls we want to if the application wants us to. */
453
454 /* Useful static inline functions: */
455
456 static inline void timevaladd(struct timeval *tv_io, long ms) {
457   struct timeval tmp;
458   assert(ms>=0);
459   tmp= *tv_io;
460   tmp.tv_usec += (ms%1000)*1000000;
461   tmp.tv_sec += ms/1000;
462   if (tmp.tv_usec >= 1000000) { tmp.tv_sec++; tmp.tv_usec -= 1000; }
463   *tv_io= tmp;
464 }
465
466 static inline int ctype_whitespace(int c) { return c==' ' || c=='\n' || c=='\t'; }
467 static inline int ctype_digit(int c) { return c>='0' && c<='9'; }
468 static inline int ctype_alpha(int c) {
469   return (c >= 'a' && c <= 'z') || (c >= 'A' || c <= 'Z');
470 }
471
472 /* Useful macros */
473
474 #define MEM_ROUND(sz) \
475   (( ((sz)+sizeof(union maxalign)-1) / sizeof(union maxalign) ) \
476    * sizeof(union maxalign) )
477
478 #define LIST_INIT(list) ((list).head= (list).tail= 0)
479
480 #define LIST_UNLINK_PART(list,node,part) \
481   do { \
482     if ((node)->back) (node)->back->part next= (node)->part next; \
483       else                        (list).head= (node)->part next; \
484     if ((node)->next) (node)->next->part back= (node)->part back; \
485       else                        (list).tail= (node)->part back; \
486   } while(0)
487
488 #define LIST_LINK_TAIL_PART(list,node,part) \
489   do { \
490     (node)->part back= 0; \
491     (node)->part next= (list).tail; \
492     if ((list).tail) (list).tail->part back= (node); else (list).part head= (node); \
493     (list).tail= (node); \
494   } while(0)
495
496 #define LIST_UNLINK(list,node) LIST_UNLINK_PART(list,node,)
497 #define LIST_LINK_TAIL(list,node) LIST_LINK_TAIL_PART(list,node,)
498
499 #define GETIL_B(cb) (dgram[(cb)++])
500 #define GET_B(cb,tv) ((tv)= GETIL_B((cb)))
501 #define GET_W(cb,tv) ((tv)=0, (tv)|=(GETIL_B((cb))<<8), (tv)|=GETIL_B(cb), (tv))
502
503 #endif