chiark / gitweb /
src/query.c: New function `adns__free_interim' for releasing memory.
[adns.git] / src / query.c
1 /*
2  * query.c
3  * - overall query management (allocation, completion)
4  * - per-query memory management
5  * - query submission and cancellation (user-visible and internal)
6  */
7 /*
8  *  This file is part of adns, which is
9  *    Copyright (C) 1997-2000,2003,2006  Ian Jackson
10  *    Copyright (C) 1999-2000,2003,2006  Tony Finch
11  *    Copyright (C) 1991 Massachusetts Institute of Technology
12  *  (See the file INSTALL for full details.)
13  *  
14  *  This program is free software; you can redistribute it and/or modify
15  *  it under the terms of the GNU General Public License as published by
16  *  the Free Software Foundation; either version 2, or (at your option)
17  *  any later version.
18  *  
19  *  This program is distributed in the hope that it will be useful,
20  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
21  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  *  GNU General Public License for more details.
23  *  
24  *  You should have received a copy of the GNU General Public License
25  *  along with this program; if not, write to the Free Software Foundation,
26  *  Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 
27  */
28
29 #include "internal.h"
30
31 #include <stdlib.h>
32 #include <unistd.h>
33 #include <errno.h>
34
35 #include <sys/time.h>
36
37 #include "internal.h"
38
39 static adns_query query_alloc(adns_state ads,
40                               const typeinfo *typei, adns_rrtype type,
41                               adns_queryflags flags, struct timeval now) {
42   /* Allocate a virgin query and return it. */
43   adns_query qu;
44   
45   qu= malloc(sizeof(*qu));  if (!qu) return 0;
46   qu->answer= malloc(sizeof(*qu->answer));
47   if (!qu->answer) { free(qu); return 0; }
48   
49   qu->ads= ads;
50   qu->state= query_tosend;
51   qu->back= qu->next= qu->parent= 0;
52   LIST_INIT(qu->children);
53   LINK_INIT(qu->siblings);
54   LIST_INIT(qu->allocations);
55   qu->interim_allocd= 0;
56   qu->preserved_allocd= 0;
57   qu->final_allocspace= 0;
58
59   qu->typei= typei;
60   qu->query_dgram= 0;
61   qu->query_dglen= 0;
62   adns__vbuf_init(&qu->vb);
63
64   qu->cname_dgram= 0;
65   qu->cname_dglen= qu->cname_begin= 0;
66
67   adns__vbuf_init(&qu->search_vb);
68   qu->search_origlen= qu->search_pos= qu->search_doneabs= 0;
69
70   qu->id= -2; /* will be overwritten with real id before we leave adns */
71   qu->flags= flags;
72   qu->retries= 0;
73   qu->udpnextserver= 0;
74   qu->udpsent= 0;
75   timerclear(&qu->timeout);
76   qu->expires= now.tv_sec + MAXTTLBELIEVE;
77
78   memset(&qu->ctx,0,sizeof(qu->ctx));
79
80   qu->answer->status= adns_s_ok;
81   qu->answer->cname= qu->answer->owner= 0;
82   qu->answer->type= type;
83   qu->answer->expires= -1;
84   qu->answer->nrrs= 0;
85   qu->answer->rrs.untyped= 0;
86   qu->answer->rrsz= typei->getrrsz(typei,type);
87
88   return qu;
89 }
90
91 static void query_submit(adns_state ads, adns_query qu,
92                          const typeinfo *typei, vbuf *qumsg_vb, int id,
93                          adns_queryflags flags, struct timeval now) {
94   /* Fills in the query message in for a previously-allocated query,
95    * and submits it.  Cannot fail.  Takes over the memory for qumsg_vb.
96    */
97
98   qu->vb= *qumsg_vb;
99   adns__vbuf_init(qumsg_vb);
100
101   qu->query_dgram= malloc(qu->vb.used);
102   if (!qu->query_dgram) { adns__query_fail(qu,adns_s_nomemory); return; }
103   
104   qu->id= id;
105   qu->query_dglen= qu->vb.used;
106   memcpy(qu->query_dgram,qu->vb.buf,qu->vb.used);
107   
108   adns__query_send(qu,now);
109 }
110
111 adns_status adns__ckl_hostname(adns_state ads, adns_queryflags flags,
112                                union checklabel_state *cls,
113                                qcontext *ctx, int labnum,
114                                const char *label, int lablen)
115 {
116   int i, c;
117
118   if (flags & adns_qf_quoteok_query) return adns_s_ok;
119   for (i=0; i<lablen; i++) {
120     c= label[i];
121     if (c == '-') {
122       if (!i) return adns_s_querydomaininvalid;
123     } else if (!ctype_alpha(c) && !ctype_digit(c)) {
124       return adns_s_querydomaininvalid;
125     }
126   }
127   return adns_s_ok;
128 }
129
130 static adns_status check_domain_name(adns_state ads, adns_queryflags flags,
131                                      qcontext *ctx, const typeinfo *typei,
132                                      const byte *dgram, int dglen)
133 {
134   findlabel_state fls;
135   adns_status err;
136   int labnum= 0, labstart, lablen;
137   union checklabel_state cls;
138
139   adns__findlabel_start(&fls,ads, -1,0, dgram,dglen,dglen, DNS_HDRSIZE,0);
140   do {
141     err= adns__findlabel_next(&fls, &lablen,&labstart);
142     assert(!err); assert(lablen >= 0);
143     err= typei->checklabel(ads,flags, &cls,ctx,
144                            labnum++, dgram+labstart,lablen);
145     if (err) return err;
146   } while (lablen);
147   return adns_s_ok;
148 }
149
150 adns_status adns__internal_submit(adns_state ads, adns_query *query_r,
151                                   const typeinfo *typei, adns_rrtype type,
152                                   vbuf *qumsg_vb, int id,
153                                   adns_queryflags flags, struct timeval now,
154                                   qcontext *ctx) {
155   adns_query qu;
156   adns_status err;
157
158   err= check_domain_name(ads, flags,ctx,typei, qumsg_vb->buf,qumsg_vb->used);
159   if (err) goto x_err;
160   qu= query_alloc(ads,typei,type,flags,now);
161   if (!qu) { err = adns_s_nomemory; goto x_err; }
162   *query_r= qu;
163
164   memcpy(&qu->ctx,ctx,sizeof(qu->ctx));
165   query_submit(ads,qu, typei,qumsg_vb,id,flags,now);
166   
167   return adns_s_ok;
168
169 x_err:
170   adns__vbuf_free(qumsg_vb);
171   return err;
172 }
173
174 static void query_simple(adns_state ads, adns_query qu,
175                          const char *owner, int ol,
176                          const typeinfo *typei, adns_queryflags flags,
177                          struct timeval now) {
178   vbuf vb_new;
179   int id;
180   adns_status stat;
181
182   stat= adns__mkquery(ads,&qu->vb,&id, owner,ol,
183                       typei,qu->answer->type, flags);
184   if (stat) {
185     if (stat == adns_s_querydomaintoolong && (flags & adns_qf_search)) {
186       adns__search_next(ads,qu,now);
187       return;
188     } else {
189       adns__query_fail(qu,stat);
190       return;
191     }
192   }
193
194   stat= check_domain_name(ads, flags,&qu->ctx,typei, qu->vb.buf,qu->vb.used);
195   if (stat) { adns__query_fail(qu,stat); return; }
196
197   vb_new= qu->vb;
198   adns__vbuf_init(&qu->vb);
199   query_submit(ads,qu, typei,&vb_new,id, flags,now);
200 }
201
202 void adns__search_next(adns_state ads, adns_query qu, struct timeval now) {
203   const char *nextentry;
204   adns_status stat;
205   
206   if (qu->search_doneabs<0) {
207     nextentry= 0;
208     qu->search_doneabs= 1;
209   } else {
210     if (qu->search_pos >= ads->nsearchlist) {
211       if (qu->search_doneabs) {
212         qu->search_vb.used= qu->search_origlen;
213         stat= adns_s_nxdomain; goto x_fail;
214       } else {
215         nextentry= 0;
216         qu->search_doneabs= 1;
217       }
218     } else {
219       nextentry= ads->searchlist[qu->search_pos++];
220     }
221   }
222
223   qu->search_vb.used= qu->search_origlen;
224   if (nextentry) {
225     if (!adns__vbuf_append(&qu->search_vb,".",1) ||
226         !adns__vbuf_appendstr(&qu->search_vb,nextentry))
227       goto x_nomemory;
228   }
229
230   free(qu->query_dgram);
231   qu->query_dgram= 0; qu->query_dglen= 0;
232
233   query_simple(ads,qu, qu->search_vb.buf, qu->search_vb.used,
234                qu->typei, qu->flags, now);
235   return;
236
237 x_nomemory:
238   stat= adns_s_nomemory;
239 x_fail:
240   adns__query_fail(qu,stat);
241 }
242
243 static int save_owner(adns_query qu, const char *owner, int ol) {
244   /* Returns 1 if OK, otherwise there was no memory. */
245   adns_answer *ans;
246
247   if (!(qu->flags & adns_qf_owner)) return 1;
248
249   ans= qu->answer;
250   assert(!ans->owner);
251
252   ans->owner= adns__alloc_preserved(qu,ol+1);  if (!ans->owner) return 0;
253
254   memcpy(ans->owner,owner,ol);
255   ans->owner[ol]= 0;
256   return 1;
257 }
258
259 int adns_submit(adns_state ads,
260                 const char *owner,
261                 adns_rrtype type,
262                 adns_queryflags flags,
263                 void *context,
264                 adns_query *query_r) {
265   int r, ol, ndots;
266   adns_status stat;
267   const typeinfo *typei;
268   struct timeval now;
269   adns_query qu;
270   const char *p;
271
272   adns__consistency(ads,0,cc_entex);
273
274   typei= adns__findtype(type);
275   if (!typei) return ENOSYS;
276
277   r= gettimeofday(&now,0); if (r) goto x_errno;
278   qu= query_alloc(ads,typei,type,flags,now); if (!qu) goto x_errno;
279   
280   qu->ctx.ext= context;
281   qu->ctx.callback= 0;
282   memset(&qu->ctx.pinfo,0,sizeof(qu->ctx.pinfo));
283   memset(&qu->ctx.tinfo,0,sizeof(qu->ctx.tinfo));
284
285   *query_r= qu;
286
287   ol= strlen(owner);
288   if (!ol) { stat= adns_s_querydomaininvalid; goto x_adnsfail; }
289   if (ol>DNS_MAXDOMAIN+1) { stat= adns_s_querydomaintoolong; goto x_adnsfail; }
290                                  
291   if (ol>=1 && owner[ol-1]=='.' && (ol<2 || owner[ol-2]!='\\')) {
292     flags &= ~adns_qf_search;
293     qu->flags= flags;
294     ol--;
295   }
296
297   if (flags & adns_qf_search) {
298     r= adns__vbuf_append(&qu->search_vb,owner,ol);
299     if (!r) { stat= adns_s_nomemory; goto x_adnsfail; }
300
301     for (ndots=0, p=owner; (p= strchr(p,'.')); p++, ndots++);
302     qu->search_doneabs= (ndots >= ads->searchndots) ? -1 : 0;
303     qu->search_origlen= ol;
304     adns__search_next(ads,qu,now);
305   } else {
306     if (flags & adns_qf_owner) {
307       if (!save_owner(qu,owner,ol)) { stat= adns_s_nomemory; goto x_adnsfail; }
308     }
309     query_simple(ads,qu, owner,ol, typei,flags, now);
310   }
311   adns__autosys(ads,now);
312   adns__consistency(ads,qu,cc_entex);
313   return 0;
314
315  x_adnsfail:
316   adns__query_fail(qu,stat);
317   adns__consistency(ads,qu,cc_entex);
318   return 0;
319
320  x_errno:
321   r= errno;
322   assert(r);
323   adns__consistency(ads,0,cc_entex);
324   return r;
325 }
326
327 int adns_submit_reverse_any(adns_state ads,
328                             const struct sockaddr *addr,
329                             const char *zone,
330                             adns_rrtype type,
331                             adns_queryflags flags,
332                             void *context,
333                             adns_query *query_r) {
334   char *buf, *buf_free = 0;
335   char shortbuf[100];
336   int r;
337
338   flags &= ~adns_qf_search;
339
340   buf = shortbuf;
341   r= adns__make_reverse_domain(addr,zone, &buf,sizeof(shortbuf),&buf_free);
342   if (r) return r;
343   r= adns_submit(ads,buf,type,flags,context,query_r);
344   free(buf_free);
345   return r;
346 }
347
348 int adns_submit_reverse(adns_state ads,
349                         const struct sockaddr *addr,
350                         adns_rrtype type,
351                         adns_queryflags flags,
352                         void *context,
353                         adns_query *query_r) {
354   if (((type^adns_r_ptr) & adns_rrt_reprmask) &&
355       ((type^adns_r_ptr_raw) & adns_rrt_reprmask))
356     return EINVAL;
357   return adns_submit_reverse_any(ads,addr,0,type,flags,context,query_r);
358 }
359
360 int adns_synchronous(adns_state ads,
361                      const char *owner,
362                      adns_rrtype type,
363                      adns_queryflags flags,
364                      adns_answer **answer_r) {
365   adns_query qu;
366   int r;
367   
368   r= adns_submit(ads,owner,type,flags,0,&qu);
369   if (r) return r;
370
371   r= adns_wait(ads,&qu,answer_r,0);
372   if (r) adns_cancel(qu);
373
374   return r;
375 }
376
377 static void *alloc_common(adns_query qu, size_t sz) {
378   allocnode *an;
379
380   if (!sz) return qu; /* Any old pointer will do */
381   assert(!qu->final_allocspace);
382   an= malloc(MEM_ROUND(MEM_ROUND(sizeof(*an)) + sz));
383   if (!an) return 0;
384   LIST_LINK_TAIL(qu->allocations,an);
385   an->sz= sz;
386   return (byte*)an + MEM_ROUND(sizeof(*an));
387 }
388
389 void *adns__alloc_interim(adns_query qu, size_t sz) {
390   void *rv;
391   
392   sz= MEM_ROUND(sz);
393   rv= alloc_common(qu,sz);
394   if (!rv) return 0;
395   qu->interim_allocd += sz;
396   return rv;
397 }
398
399 void *adns__alloc_preserved(adns_query qu, size_t sz) {
400   void *rv;
401   
402   sz= MEM_ROUND(sz);
403   rv= adns__alloc_interim(qu,sz);
404   if (!rv) return 0;
405   qu->preserved_allocd += sz;
406   return rv;
407 }
408
409 static allocnode *alloc_info(adns_query qu, void *p, size_t *sz_r) {
410   allocnode *an;
411
412   if (!p || p == qu) { *sz_r= 0; return 0; }
413   an= (allocnode *)((byte *)p - MEM_ROUND(sizeof(allocnode)));
414   *sz_r= MEM_ROUND(an->sz);
415   return an;
416 }
417
418 void adns__free_interim(adns_query qu, void *p) {
419   size_t sz;
420   allocnode *an= alloc_info(qu, p, &sz);
421
422   if (!an) return;
423   assert(!qu->final_allocspace);
424   LIST_UNLINK(qu->allocations, an);
425   free(an);
426   qu->interim_allocd -= sz;
427 }
428
429 void *adns__alloc_mine(adns_query qu, size_t sz) {
430   return alloc_common(qu,MEM_ROUND(sz));
431 }
432
433 void adns__transfer_interim(adns_query from, adns_query to, void *block) {
434   size_t sz;
435   allocnode *an= alloc_info(from, block, &sz);
436
437   if (!an) return;
438
439   assert(!to->final_allocspace);
440   assert(!from->final_allocspace);
441   
442   LIST_UNLINK(from->allocations,an);
443   LIST_LINK_TAIL(to->allocations,an);
444
445   from->interim_allocd -= sz;
446   to->interim_allocd += sz;
447
448   if (to->expires > from->expires) to->expires= from->expires;
449 }
450
451 void *adns__alloc_final(adns_query qu, size_t sz) {
452   /* When we're in the _final stage, we _subtract_ from interim_alloc'd
453    * each allocation, and use final_allocspace to point to the next free
454    * bit.
455    */
456   void *rp;
457
458   sz= MEM_ROUND(sz);
459   rp= qu->final_allocspace;
460   assert(rp);
461   qu->interim_allocd -= sz;
462   assert(qu->interim_allocd>=0);
463   qu->final_allocspace= (byte*)rp + sz;
464   return rp;
465 }
466
467 static void cancel_children(adns_query qu) {
468   adns_query cqu, ncqu;
469
470   for (cqu= qu->children.head; cqu; cqu= ncqu) {
471     ncqu= cqu->siblings.next;
472     adns_cancel(cqu);
473   }
474 }
475
476 void adns__reset_preserved(adns_query qu) {
477   assert(!qu->final_allocspace);
478   cancel_children(qu);
479   qu->answer->nrrs= 0;
480   qu->answer->rrs.untyped= 0;
481   qu->interim_allocd= qu->preserved_allocd;
482 }
483
484 static void free_query_allocs(adns_query qu) {
485   allocnode *an, *ann;
486
487   cancel_children(qu);
488   for (an= qu->allocations.head; an; an= ann) { ann= an->next; free(an); }
489   LIST_INIT(qu->allocations);
490   adns__vbuf_free(&qu->vb);
491   adns__vbuf_free(&qu->search_vb);
492   free(qu->query_dgram);
493   qu->query_dgram= 0;
494 }
495
496 void adns_cancel(adns_query qu) {
497   adns_state ads;
498
499   ads= qu->ads;
500   adns__consistency(ads,qu,cc_entex);
501   if (qu->parent) LIST_UNLINK_PART(qu->parent->children,qu,siblings.);
502   switch (qu->state) {
503   case query_tosend:
504     LIST_UNLINK(ads->udpw,qu);
505     break;
506   case query_tcpw:
507     LIST_UNLINK(ads->tcpw,qu);
508     break;
509   case query_childw:
510     LIST_UNLINK(ads->childw,qu);
511     break;
512   case query_done:
513     LIST_UNLINK(ads->output,qu);
514     break;
515   default:
516     abort();
517   }
518   free_query_allocs(qu);
519   free(qu->answer);
520   free(qu);
521   adns__consistency(ads,0,cc_entex);
522 }
523
524 void adns__update_expires(adns_query qu, unsigned long ttl,
525                           struct timeval now) {
526   time_t max;
527
528   assert(ttl <= MAXTTLBELIEVE);
529   max= now.tv_sec + ttl;
530   if (qu->expires < max) return;
531   qu->expires= max;
532 }
533
534 static void makefinal_query(adns_query qu) {
535   adns_answer *ans;
536   int rrn;
537
538   ans= qu->answer;
539
540   if (qu->interim_allocd) {
541     ans= realloc(qu->answer,
542                  MEM_ROUND(MEM_ROUND(sizeof(*ans)) + qu->interim_allocd));
543     if (!ans) goto x_nomem;
544     qu->answer= ans;
545   }
546
547   qu->final_allocspace= (byte*)ans + MEM_ROUND(sizeof(*ans));
548   adns__makefinal_str(qu,&ans->cname);
549   adns__makefinal_str(qu,&ans->owner);
550   
551   if (ans->nrrs) {
552     adns__makefinal_block(qu, &ans->rrs.untyped, ans->nrrs*ans->rrsz);
553
554     for (rrn=0; rrn<ans->nrrs; rrn++)
555       qu->typei->makefinal(qu, ans->rrs.bytes + rrn*ans->rrsz);
556   }
557   
558   free_query_allocs(qu);
559   return;
560   
561  x_nomem:
562   qu->preserved_allocd= 0;
563   qu->answer->cname= 0;
564   qu->answer->owner= 0;
565   adns__reset_preserved(qu); /* (but we just threw away the preserved stuff) */
566
567   qu->answer->status= adns_s_nomemory;
568   free_query_allocs(qu);
569 }
570
571 void adns__query_done(adns_query qu) {
572   adns_answer *ans;
573   adns_query parent;
574
575   cancel_children(qu);
576
577   qu->id= -1;
578   ans= qu->answer;
579
580   if (qu->flags & adns_qf_search && ans->status != adns_s_nomemory) {
581     if (!save_owner(qu, qu->search_vb.buf, qu->search_vb.used)) {
582       adns__query_fail(qu,adns_s_nomemory);
583       return;
584     }
585   }
586
587   if (ans->nrrs && qu->typei->diff_needswap) {
588     if (!adns__vbuf_ensure(&qu->vb,qu->answer->rrsz)) {
589       adns__query_fail(qu,adns_s_nomemory);
590       return;
591     }
592     adns__isort(ans->rrs.bytes, ans->nrrs, ans->rrsz,
593                 qu->vb.buf,
594                 (int(*)(void*, const void*, const void*))
595                   qu->typei->diff_needswap,
596                 qu->ads);
597   }
598   if (ans->nrrs && qu->typei->postsort) {
599     qu->typei->postsort(qu->ads, ans->rrs.bytes,
600                         ans->nrrs,ans->rrsz, qu->typei);
601   }
602
603   ans->expires= qu->expires;
604   parent= qu->parent;
605   if (parent) {
606     LIST_UNLINK_PART(parent->children,qu,siblings.);
607     LIST_UNLINK(qu->ads->childw,parent);
608     qu->ctx.callback(parent,qu);
609     free_query_allocs(qu);
610     free(qu->answer);
611     free(qu);
612   } else {
613     makefinal_query(qu);
614     LIST_LINK_TAIL(qu->ads->output,qu);
615     qu->state= query_done;
616   }
617 }
618
619 void adns__query_fail(adns_query qu, adns_status stat) {
620   adns__reset_preserved(qu);
621   qu->answer->status= stat;
622   adns__query_done(qu);
623 }
624
625 void adns__makefinal_str(adns_query qu, char **strp) {
626   int l;
627   char *before, *after;
628
629   before= *strp;
630   if (!before) return;
631   l= strlen(before)+1;
632   after= adns__alloc_final(qu,l);
633   memcpy(after,before,l);
634   *strp= after;  
635 }
636
637 void adns__makefinal_block(adns_query qu, void **blpp, size_t sz) {
638   void *before, *after;
639
640   before= *blpp;
641   if (!before) return;
642   after= adns__alloc_final(qu,sz);
643   memcpy(after,before,sz);
644   *blpp= after;
645 }