12 #include <arpa/nameser.h>
13 #include <sys/socket.h>
14 #include <netinet/in.h>
15 #include <arpa/inet.h>
17 #include "adns-internal.h"
19 #define LIST_UNLINK_PART(list,node,part) \
21 if ((node)->back) (node)->back->part next= (node)->part next; \
22 else (list).head= (node)->part next; \
23 if ((node)->next) (node)->next->part back= (node)->part back; \
24 else (list).tail= (node)->part back; \
27 #define LIST_LINK_TAIL_PART(list,node,part) \
29 (node)->part back= 0; \
30 (node)->part next= (list).tail; \
31 if ((list).tail) (list).tail->part back= (node); else (list).part head= (node); \
32 (list).tail= (node); \
35 #define LIST_UNLINK(list,node) LIST_UNLINK_PART(list,node,)
36 #define LIST_LINK_TAIL_PART(list,node) LIST_LINK_TAIL(list,node,)
38 static void vdebug(adns_state ads, const char *fmt, va_list al) {
39 if (!(ads->iflags & adns_if_debug)) return;
40 fputs("adns debug: ",stderr);
41 vfprintf(stderr,fmt,al);
45 static void debug(adns_state ads, const char *fmt, ...) {
53 static void vdiag(adns_state ads, const char *fmt, va_list al) {
54 if (ads->iflags & adns_if_noerrprint) return;
55 fputs("adns: ",stderr);
56 vfprintf(stderr,fmt,al);
60 static void diag(adns_state ads, const char *fmt, ...) {
68 static void addserver(adns_state ads, struct in_addr addr) {
72 for (i=0; i<ads->nservers; i++) {
73 if (ads->servers[i].addr.s_addr == addr.s_addr) {
74 debug(ads,"duplicate nameserver %s ignored",inet_ntoa(addr));
79 if (ads->nservers>=MAXSERVERS) {
80 diag(ads,"too many nameservers, ignoring %s",inet_ntoa(addr));
84 ss= ads->servers+ads->nservers;
86 ss->state= server_disc;
87 ss->connw.head= ss->connw.tail= 0;
91 static void configparseerr(adns_state ads, const char *fn, int lno,
92 const char *fmt, ...) {
95 if (ads->iflags & adns_if_noerrprint) return;
96 if (lno==-1) fprintf(stderr,"adns: %s: ",fn);
97 else fprintf(stderr,"adns: %s:%d: ",fn,lno);
99 vfprintf(stderr,fmt,al);
104 static void ccf_nameserver(adns_state ads, const char *fn, int lno, const char *buf) {
107 if (!inet_aton(buf,&ia)) {
108 configparseerr(ads,fn,lno,"invalid nameserver address `%s'",buf);
111 debug(ads,"using nameserver %s",inet_ntoa(ia));
115 static void ccf_search(adns_state ads, const char *fn, int lno, const char *buf) {
117 diag(ads,"warning - `search' ignored FIXME");
120 static void ccf_sortlist(adns_state ads, const char *fn, int lno, const char *buf) {
121 diag(ads,"warning - `sortlist' ignored FIXME");
124 static void ccf_options(adns_state ads, const char *fn, int lno, const char *buf) {
126 diag(ads,"warning - `options' ignored FIXME");
129 static void ccf_clearnss(adns_state ads, const char *fn, int lno, const char *buf) {
133 static const struct configcommandinfo {
135 void (*fn)(adns_state ads, const char *fn, int lno, const char *buf);
136 } configcommandinfos[]= {
137 { "nameserver", ccf_nameserver },
138 { "domain", ccf_search },
139 { "search", ccf_search },
140 { "sortlist", ccf_sortlist },
141 { "options", ccf_options },
142 { "clearnameservers", ccf_clearnss },
146 static int ctype_whitespace(int c) { return c==' ' || c=='\n' || c=='\t'; }
147 static int ctype_digit(int c) { return c>='0' && c<='9'; }
149 static void readconfig(adns_state ads, const char *filename) {
150 char linebuf[2000], *p, *q;
153 const struct configcommandinfo *ccip;
155 file= fopen(filename,"r");
157 if (errno == ENOENT) {
158 debug(ads,"configuration file `%s' does not exist",filename);
161 diag(ads,"cannot open configuration file `%s': %s",filename,strerror(errno));
165 for (lno=1; fgets(linebuf,sizeof(linebuf),file); lno++) {
168 if (linebuf[l-1] != '\n' && !feof(file)) {
169 diag(ads,"%s:%d: line too long",filename,lno);
170 while ((c= getc(file)) != EOF && c != '\n') { }
174 while (l>0 && ctype_whitespace(linebuf[l-1])) l--;
177 while (ctype_whitespace(*p)) p++;
178 if (*p == '#' || *p == '\n') continue;
180 while (*q && !ctype_whitespace(*q)) q++;
181 for (ccip=configcommandinfos;
182 ccip->name && strncmp(ccip->name,p,q-p);
185 diag(ads,"%s:%d: unknown configuration directive `%.*s'",filename,lno,q-p,p);
188 while (ctype_whitespace(*q)) q++;
189 ccip->fn(ads,filename,lno,q);
192 diag(ads,"%s:%d: read error: %s",filename,lno,strerror(errno));
197 static const char *instrum_getenv(adns_state ads, const char *envvar) {
200 value= getenv(envvar);
201 if (!value) debug(ads,"environment variable %s not set",envvar);
202 else debug(ads,"environment variable %s set to `%s'",envvar,value);
206 static void readconfigenv(adns_state ads, const char *envvar) {
207 const char *filename;
209 if (ads->iflags & adns_if_noenv) {
210 debug(ads,"not checking environment variable `%s'",envvar);
213 filename= instrum_getenv(ads,envvar);
214 if (filename) readconfig(ads,filename);
217 int adns_init(adns_state *ads_r, adns_initflags flags) {
219 const char *res_options, *adns_res_options;
220 struct protoent *proto;
223 ads= malloc(sizeof(*ads)); if (!ads) return errno;
224 ads->tosend.head= ads->tosend.tail= 0;
225 ads->timew.head= ads->timew.tail= 0;
226 ads->childw.head= ads->childw.tail= 0;
227 ads->output.head= ads->output.tail= 0;
232 ads->tcpbufavail= ads->tcpbufused= ads->tcpbufdone= 0;
238 res_options= instrum_getenv(ads,"RES_OPTIONS");
239 adns_res_options= instrum_getenv(ads,"ADNS_RES_OPTIONS");
240 ccf_options(ads,"RES_OPTIONS",-1,res_options);
241 ccf_options(ads,"ADNS_RES_OPTIONS",-1,adns_res_options);
243 readconfig(ads,"/etc/resolv.conf");
244 readconfigenv(ads,"RES_CONF");
245 readconfigenv(ads,"ADNS_RES_CONF");
247 ccf_options(ads,"RES_OPTIONS",-1,res_options);
248 ccf_options(ads,"ADNS_RES_OPTIONS",-1,adns_res_options);
250 ccf_search(ads,"LOCALDOMAIN",-1,instrum_getenv(ads,"LOCALDOMAIN"));
251 ccf_search(ads,"ADNS_LOCALDOMAIN",-1,instrum_getenv(ads,"ADNS_LOCALDOMAIN"));
253 if (!ads->nservers) {
255 if (ads->iflags & adns_if_debug)
256 fprintf(stderr,"adns: no nameservers, using localhost\n");
257 ia.s_addr= INADDR_LOOPBACK;
261 proto= getprotobyname("udp"); if (!proto) { r= ENOPROTOOPT; goto x_free; }
262 ads->udpsocket= socket(AF_INET,SOCK_DGRAM,proto->p_proto);
263 if (!ads->udpsocket) { r= errno; goto x_closeudp; }
269 close(ads->udpsocket);
275 static void query_fail(adns_state ads, adns_query qu, adns_status stat) {
279 if (!ans) ans= malloc(sizeof(*qu->answer));
288 LIST_LINK_TAIL(ads->output,qu);
291 int adns_finish(adns_state ads) {
295 static void autosys(adns_state ads, struct timeval now) {
296 if (ads->iflags & adns_if_noautosys) return;
297 adns_callback(ads,-1,0,0,0);
300 void adns_cancel(adns_state ads, adns_query query) {
304 int adns_callback(adns_state ads, int maxfd,
305 const fd_set *readfds, const fd_set *writefds,
306 const fd_set *exceptfds) {
310 static void inter_maxto(struct timeval **tv_io, struct timeval *tvbuf,
311 struct timeval maxto) {
315 if (!rbuf) { *tvbuf= maxto; *tv_io= tvbuf; return; }
316 if (timercmp(rbuf,&maxto,>)) *rbuf= maxto;
319 static void inter_maxtoabs(struct timeval **tv_io, struct timeval *tvbuf,
320 struct timeval now, struct timeval maxtime) {
323 maxtime.tv_sec -= (now.tv_sec-1);
324 maxtime.tv_usec += (1000-now.tv_usec);
325 dr= ldiv(maxtime.tv_usec,1000);
326 maxtime.tv_sec += dr.quot;
327 maxtime.tv_usec -= dr.rem;
328 inter_maxto(tv_io,tvbuf,maxtime);
331 static void localresourcerr(struct timeval **tv_io, struct timeval *tvbuf,
332 const char *syscall) {
333 struct timeval tvto_lr;
335 diag(ads,"local system resources scarce (during %s): %s",syscall,strerror(errno));
336 timerclear(&tvto_lr); timevaladd(&tvto_lr,LOCALRESOURCEMS);
337 inter_maxto(tv_io, tvbuf, tvto_lr);
341 static inline void timevaladd(struct timeval *tv_io, long ms) {
345 tmp.tv_usec += (ms%1000)*1000;
346 tmp.tv_sec += ms/1000;
347 if (tmp.tv_usec >= 1000) { tmp.tv_sec++; tmp.tv_usec -= 1000; }
351 void adns_interest(adns_state ads, int *maxfd,
352 fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
353 struct timeval **tv_io, struct timeval *tvbuf) {
358 r= gettimeofday(&now,0);
359 if (r) { localresourcerr(tv_io,tvbuf,"gettimeofday"); return; }
361 for (qu= ads->timew; qu; qu= nqu) {
363 if (timercmp(&now,qu->timeout,>)) {
364 DLIST_UNLINK(ads->timew,qu);
365 if (qu->nextudpserver == -1) {
366 query_fail(ads,qu,adns_s_notresponding);
368 DLIST_LINKTAIL(ads->tosend,qu);
371 inter_maxtoabs(tv_io,tvbuf,now,qu->timeout);
375 for (qu= ads->tosend; qu; qu= nqu) {
377 quproc_tosend(ads,qu,now);
380 for (qu= ads->timew; qu; qu= qu->next) {
382 inter_addfd(maxfd,readfds,ads->udpsocket);
386 switch (ads->tcpstate) {
389 case server_connecting:
390 inter_addfd(maxfd,readfds,ads->tcpsocket);
391 inter_addfd(maxfd,writefds,ads->tcpsocket);
392 inter_addfd(maxfd,exceptfds,ads->tcpsocket);
394 case server_connected:
395 inter_addfd(maxfd,readfds,ads->tcpsocket);
396 inter_addfd(maxfd,exceptfds,ads->tcpsocket);
397 if (ads->opbufused) inter_addfd(maxfd,writefds,ads->tcpsocket);
404 static int internal_check(adns_state ads,
405 adns_query *query_io,
406 adns_answer **answer,
412 if (!ads->output.head) return EWOULDBLOCK;
413 qu= ads->output.head;
415 if (qu->id>=0) return EWOULDBLOCK;
417 LIST_UNLINK(ads->output,qu);
419 if (context_r) *context_r= qu->context;
424 int adns_wait(adns_state ads,
425 adns_query *query_io,
426 adns_answer **answer_r,
428 int r, maxfd, rsel, rcb;
429 fd_set readfds, writefds, exceptfds;
430 struct timeval tvbuf, *tvp;
433 r= internal_check(ads,query_io,answer_r,context_r);
434 if (r && r != EWOULDBLOCK) return r;
435 FD_ZERO(&readfds); FD_ZERO(&writefds); FD_ZERO(&exceptfds);
437 adns_interest(ads,&maxfd,&readfds,&writefds,&exceptfds,&tvp,&tvbuf);
438 rsel= select(maxfd,&readfds,&writefds,&exceptfds,tvp);
439 if (rsel==-1) return r;
440 rcb= adns_callback(ads,maxfd,&readfds,&writefds,&exceptfds);
445 int adns_check(adns_state ads,
446 adns_query *query_io,
447 adns_answer **answer_r,
450 return internal_check(ads,query_io,answer_r,context_r);
453 int adns_synchronous(adns_state ads,
456 adns_queryflags flags,
457 adns_answer **answer_r) {
461 r= adns_submit(ads,owner,type,flags,0,&qu);
465 r= adns_wait(ads,&qu,answer_r,0);
467 if (r) adns_cancel(ads,qu);
471 static adns_status mkquery(adns_state ads, const char *owner, int ol, int id,
472 adns_rrtype type, adns_queryflags flags, int *qml_r) {
473 int ll, c, nlabs, qbufreq;
474 unsigned char label[255], *nqbuf;
477 #define MKQUERY_ADDB(b) *nqbuf++= (b)
478 #define MKQUERY_ADDW(w) (MKQUERY_ADDB(((w)>>8)&0x0ff), MKQUERY_ADDB((w)&0x0ff))
480 qbufreq= 12+strlen(owner)+3;
481 if (ads->qbufavail < qbufreq) {
482 nqbuf= realloc(ads->qbuf,qbufreq);
483 if (!nqbuf) return adns_s_nolocalmem;
484 ads->qbuf= nqbuf; ads->qbufavail= qbufreq;
489 MKQUERY_ADDB(0x01); /* QR=Q(0), OPCODE=QUERY(0000), !AA, !TC, RD */
490 MKQUERY_ADDB(0x00); /* !RA, Z=000, RCODE=NOERROR(0000) */
491 MKQUERY_ADDW(1); /* QDCOUNT=1 */
492 MKQUERY_ADDW(0); /* ANCOUNT=0 */
493 MKQUERY_ADDW(0); /* NSCOUNT=0 */
494 MKQUERY_ADDW(0); /* ARCOUNT=0 */
495 p= owner; pe= owner+ol;
497 if (!*p) return adns_s_invaliddomain;
500 while (p!=pe && (c= *p++)!='.') {
502 if (!(flags & adns_f_anyquote)) return adns_s_invaliddomain;
503 if (ctype_digit(p[0])) {
504 if (ctype_digit(p[1]) && ctype_digit(p[2])) {
505 c= (*p++ - '0')*100 + (*p++ - '0')*10 + (*p++ - '0');
506 if (c >= 256) return adns_s_invaliddomain;
508 return adns_s_invaliddomain;
510 } else if (!(c= *p++)) {
511 return adns_s_invaliddomain;
514 if (!(flags & adns_f_anyquote)) {
515 if ((c >= '0' && c <= '9') || c == '-') {
516 if (!ll) return adns_s_invaliddomain;
517 } else if ((c < 'a' || c > 'z') && (c < 'A' && c > 'Z')) {
518 return adns_s_invaliddomain;
521 if (ll == sizeof(label)) return adns_s_invaliddomain;
524 if (!ll) return adns_s_invaliddomain;
525 if (nlabs++ > 63) return adns_s_invaliddomain;
527 memcpy(nqbuf,label,ll); nqbuf+= ll;
531 MKQUERY_ADDW(type & adns__rrt_typemask); /* QTYPE */
532 MKQUERY_ADDW(1); /* QCLASS=IN */
534 *qml_r= nqbuf - ads->qbuf;
539 static adns_query allocquery(adns_state ads, const char *owner, int ol,
540 int qml, int id, adns_rrtype type,
541 adns_queryflags flags, void *context) {
545 qu= malloc(sizeof(*qu)+ol+1+qml); if (!qu) return 0;
546 qu->next= qu->back= qu->parent= 0;
547 qu->children.head= qu->children.tail= 0;
548 qu->siblings.next= qu->siblings.back= 0;
553 qu->context= context;
555 qu->sentudp= qu->senttcp= 0;
557 memcpy(qu->owner,owner,ol); qu->owner[ol]= 0;
558 qu->querymsg= qm= qu->owner+ol+1;
559 memcpy(qm,ads->qbuf,qml);
564 static int failsubmit(adns_state ads, void *context, adns_query *query_r,
565 adns_rrtype type, adns_queryflags flags,
566 int id, adns_status stat) {
569 qu= allocquery(ads,0,0,0,id,type,flags,context); if (!qu) return errno;
570 query_fail(ads,qu,stat);
575 static void quproc_tosend(adns_state ads, adns_query qu, struct timeval now) {
576 /* Query must be on the `tosend' queue, and guarantees to remove it. */
577 struct sockaddr_in servaddr;
580 if (qu->nextudpserver != -1) {
581 if (qu->udpretries >= UDPMAXRETRIES) {
582 DLIST_UNLINK(ads->tosend,qu);
583 query_fail(ads,qu,adns_s_notresponding);
586 serv= qu->nextudpserver;
587 memset(&servaddr,0,sizeof(servaddr));
588 servaddr.sin_family= AF_INET;
589 servaddr.sin_addr= ads->servers[serv].addr;
590 servaddr.sin_port= htons(53);
591 r= sendto(ads->udpsocket,qu->querymsg,qu->querylen,0,&servaddr,sizeof(servaddr));
592 if (r<0 && errno == EMSGSIZE) {
593 qu->nextudpserver= -1;
596 diag("sendto %s failed: %s",inet_ntoa(servaddr.sin_addr),strerror(errno));
598 DLIST_UNLINK(ads->tosend,qu);
599 timevaladd(&now,UDPRETRYMS);
601 qu->sentudp |= (1<<serv);
602 qu->nextudpserver= (serv+1)%ads->nservers;
604 DLIST_LINKTAIL(ads->timew,qu);
610 serv= tcpserver_get(ads);
611 if (serv<0) { r=0; break; }
612 if (ads->opbufused) { r=0; break; }
613 r= write(ads->tcpsocket,qu->querymsg,qu->querylen);
615 if (errno == EAGAIN || errno == EINTR || errno == ENOSPC ||
616 errno == ENOBUFS || errno == ENOMEM) {
619 tcpserver_broken(serv);
621 if (r < qu->querylen) {
622 newopbufused= qu->opbufused + (qu->querylen-r);
623 if (newopbufused > ads->opbufavail) {
624 newopbufavail= ads->newopbufused<<1;
625 newopbuf= realloc(newopbufavail);
627 DLIST_UNLINK(ads->tosend,qu);
628 query_fail(ads,qu,adns_s_nolocalmem);
631 ads->opbuf= newopbuf;
632 ads->opbufavail= newopbufavail;
634 memcpy(ads->opbuf+ads->opbufused,qu->querymsg+r,qu->querylen-r);
635 ads->opbufused= newopbufused;
637 DLIST_UNLINK(ads->tosend,qu);
638 timevaladd(&now,TCPMS);
640 qu->senttcp |= (1<<qu->nextserver);
641 DLIST_LINKTAIL(ads->timew,qu);
644 int adns_submit(adns_state ads,
647 adns_queryflags flags,
649 adns_query *query_r) {
657 if (ol<=1 || ol>MAXDNAME+1)
658 return failsubmit(ads,context,query_r,type,flags,id,adns_s_invaliddomain);
659 if (owner[ol-1]=='.' && owner[ol-2]!='\\') { flags &= ~adns_f_search; ol--; }
661 stat= mkquery(ads,owner,ol,id,type,flags,&qml);
662 if (stat) return failsubmit(ads,context,query_r,type,flags,id,stat);
664 qu= allocquery(ads,owner,ol,qml,id,type,flags,context); if (!qu) return errno;
665 if (qu->flags & adns_f_usevc) qu->udpretries= -1;
666 LIST_LINK_TAIL(ads->tosend,qu);
668 r= gettimeofday(&now,0); if (r) return;
669 quproc_tosend(ads,qu,now);