OSSP CVS Repository

ossp - Check-in [131]
Not logged in
[Honeypot]  [Browse]  [Home]  [Login]  [Reports
[Search]  [Ticket]  [Timeline
  [Patchset]  [Tagging/Branching

Check-in Number: 131
Date: 2000-Aug-11 13:35:09 (local)
2000-Aug-11 11:35:09 (UTC)
User:rse
Branch:
Comment: Import of ADNS 0.9
Tickets:
Inspections:
Files:
ossp-pkg/adns/adns_event.c      added-> 1.1.1.3
ossp-pkg/adns/adns_query.c      added-> 1.1.1.4
ossp-pkg/adns/adns_reply.c      added-> 1.1.1.4
ossp-pkg/adns/adns_test.c      added-> 1.1.1.3
ossp-pkg/adns/adns_transmit.c      added-> 1.1.1.4
ossp-pkg/adns/configure.in      added-> 1.1.1.3

ossp-pkg/adns/adns_event.c -> 1.1.1.3

*** /dev/null    Fri May  3 13:52:11 2024
--- -    Fri May  3 13:52:34 2024
***************
*** 0 ****
--- 1,723 ----
+ /*
+  * event.c
+  * - event loop core
+  * - TCP connection management
+  * - user-visible check/wait and event-loop-related functions
+  */
+ /*
+  *  This file is
+  *    Copyright (C) 1997-2000 Ian Jackson <ian@davenant.greenend.org.uk>
+  *
+  *  It is part of adns, which is
+  *    Copyright (C) 1997-2000 Ian Jackson <ian@davenant.greenend.org.uk>
+  *    Copyright (C) 1999 Tony Finch <dot@dotat.at>
+  *  
+  *  This program is free software; you can redistribute it and/or modify
+  *  it under the terms of the GNU General Public License as published by
+  *  the Free Software Foundation; either version 2, or (at your option)
+  *  any later version.
+  *  
+  *  This program is distributed in the hope that it will be useful,
+  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  *  GNU General Public License for more details.
+  *  
+  *  You should have received a copy of the GNU General Public License
+  *  along with this program; if not, write to the Free Software Foundation,
+  *  Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 
+  */
+ 
+ #include <errno.h>
+ #include <stdlib.h>
+ #include <unistd.h>
+ 
+ #include <sys/types.h>
+ #include <sys/time.h>
+ #include <netdb.h>
+ #include <sys/socket.h>
+ #include <netinet/in.h>
+ #include <arpa/inet.h>
+ 
+ #include "internal.h"
+ #include "tvarith.h"
+ 
+ /* TCP connection management. */
+ 
+ static void tcp_close(adns_state ads) {
+   int serv;
+   
+   serv= ads->tcpserver;
+   close(ads->tcpsocket);
+   ads->tcpsocket= -1;
+   ads->tcprecv.used= ads->tcprecv_skip= ads->tcpsend.used= 0;
+ }
+ 
+ void adns__tcp_broken(adns_state ads, const char *what, const char *why) {
+   int serv;
+   adns_query qu;
+   
+   assert(ads->tcpstate == server_connecting || ads->tcpstate == server_ok);
+   serv= ads->tcpserver;
+   if (what) adns__warn(ads,serv,0,"TCP connection failed: %s: %s",what,why);
+ 
+   if (ads->tcpstate == server_connecting) {
+     /* Counts as a retry for all the queries waiting for TCP. */
+     for (qu= ads->tcpw.head; qu; qu= qu->next)
+       qu->retries++;
+   }
+ 
+   tcp_close(ads);
+   ads->tcpstate= server_broken;
+   ads->tcpserver= (serv+1)%ads->nservers;
+ }
+ 
+ static void tcp_connected(adns_state ads, struct timeval now) {
+   adns_query qu, nqu;
+   
+   adns__debug(ads,ads->tcpserver,0,"TCP connected");
+   ads->tcpstate= server_ok;
+   for (qu= ads->tcpw.head; qu && ads->tcpstate == server_ok; qu= nqu) {
+     nqu= qu->next;
+     assert(qu->state == query_tcpw);
+     adns__querysend_tcp(qu,now);
+   }
+ }
+ 
+ void adns__tcp_tryconnect(adns_state ads, struct timeval now) {
+   int r, fd, tries;
+   struct sockaddr_in addr;
+   struct protoent *proto;
+ 
+   for (tries=0; tries<ads->nservers; tries++) {
+     switch (ads->tcpstate) {
+     case server_connecting:
+     case server_ok:
+     case server_broken:
+       return;
+     case server_disconnected:
+       break;
+     default:
+       abort();
+     }
+     
+     assert(!ads->tcpsend.used);
+     assert(!ads->tcprecv.used);
+     assert(!ads->tcprecv_skip);
+ 
+     proto= getprotobyname("tcp");
+     if (!proto) { adns__diag(ads,-1,0,"unable to find protocol no. for TCP !"); return; }
+     fd= socket(AF_INET,SOCK_STREAM,proto->p_proto);
+     if (fd<0) {
+       adns__diag(ads,-1,0,"cannot create TCP socket: %s",strerror(errno));
+       return;
+     }
+     r= adns__setnonblock(ads,fd);
+     if (r) {
+       adns__diag(ads,-1,0,"cannot make TCP socket nonblocking: %s",strerror(r));
+       close(fd);
+       return;
+     }
+     memset(&addr,0,sizeof(addr));
+     addr.sin_family= AF_INET;
+     addr.sin_port= htons(DNS_PORT);
+     addr.sin_addr= ads->servers[ads->tcpserver].addr;
+     r= connect(fd,(const struct sockaddr*)&addr,sizeof(addr));
+     ads->tcpsocket= fd;
+     ads->tcpstate= server_connecting;
+     if (r==0) { tcp_connected(ads,now); return; }
+     if (errno == EWOULDBLOCK || errno == EINPROGRESS) {
+       ads->tcptimeout= now;
+       timevaladd(&ads->tcptimeout,TCPCONNMS);
+       return;
+     }
+     adns__tcp_broken(ads,"connect",strerror(errno));
+     ads->tcpstate= server_disconnected;
+   }
+ }
+ 
+ /* Timeout handling functions. */
+ 
+ void adns__must_gettimeofday(adns_state ads, const struct timeval **now_io,
+                             struct timeval *tv_buf) {
+   const struct timeval *now;
+   int r;
+ 
+   now= *now_io;
+   if (now) return;
+   r= gettimeofday(tv_buf,0); if (!r) { *now_io= tv_buf; return; }
+   adns__diag(ads,-1,0,"gettimeofday failed: %s",strerror(errno));
+   adns_globalsystemfailure(ads);
+   return;
+ }
+ 
+ static void inter_immed(struct timeval **tv_io, struct timeval *tvbuf) {
+   struct timeval *rbuf;
+ 
+   if (!tv_io) return;
+ 
+   rbuf= *tv_io;
+   if (!rbuf) { *tv_io= rbuf= tvbuf; }
+ 
+   timerclear(rbuf);
+ }
+     
+ static void inter_maxto(struct timeval **tv_io, struct timeval *tvbuf,
+                        struct timeval maxto) {
+   struct timeval *rbuf;
+ 
+   if (!tv_io) return;
+   rbuf= *tv_io;
+   if (!rbuf) {
+     *tvbuf= maxto; *tv_io= tvbuf;
+   } else {
+     if (timercmp(rbuf,&maxto,>)) *rbuf= maxto;
+   }
+ /*fprintf(stderr,"inter_maxto maxto=%ld.%06ld result=%ld.%06ld\n",
+        maxto.tv_sec,maxto.tv_usec,(**tv_io).tv_sec,(**tv_io).tv_usec);*/
+ }
+ 
+ static void inter_maxtoabs(struct timeval **tv_io, struct timeval *tvbuf,
+                           struct timeval now, struct timeval maxtime) {
+   /* tv_io may be 0 */
+   ldiv_t dr;
+ 
+ /*fprintf(stderr,"inter_maxtoabs now=%ld.%06ld maxtime=%ld.%06ld\n",
+        now.tv_sec,now.tv_usec,maxtime.tv_sec,maxtime.tv_usec);*/
+   if (!tv_io) return;
+   maxtime.tv_sec -= (now.tv_sec+2);
+   maxtime.tv_usec -= (now.tv_usec-2000000);
+   dr= ldiv(maxtime.tv_usec,1000000);
+   maxtime.tv_sec += dr.quot;
+   maxtime.tv_usec -= dr.quot*1000000;
+   if (maxtime.tv_sec<0) timerclear(&maxtime);
+   inter_maxto(tv_io,tvbuf,maxtime);
+ }
+ 
+ static void timeouts_queue(adns_state ads, int act,
+                           struct timeval **tv_io, struct timeval *tvbuf,
+                           struct timeval now, struct query_queue *queue) {
+   adns_query qu, nqu;
+   
+   for (qu= queue->head; qu; qu= nqu) {
+     nqu= qu->next;
+     if (!timercmp(&now,&qu->timeout,>)) {
+       inter_maxtoabs(tv_io,tvbuf,now,qu->timeout);
+     } else {
+       if (!act) { inter_immed(tv_io,tvbuf); return; }
+       LIST_UNLINK(*queue,qu);
+       if (qu->state != query_tosend) {
+        adns__query_fail(qu,adns_s_timeout);
+       } else {
+        adns__query_send(qu,now);
+       }
+       nqu= queue->head;
+     }
+   }
+ }
+ 
+ static void tcp_events(adns_state ads, int act,
+                       struct timeval **tv_io, struct timeval *tvbuf,
+                       struct timeval now) {
+   adns_query qu, nqu;
+   
+   for (;;) {
+     switch (ads->tcpstate) {
+     case server_broken:
+       if (!act) { inter_immed(tv_io,tvbuf); return; }
+       for (qu= ads->tcpw.head; qu; qu= nqu) {
+        nqu= qu->next;
+        assert(qu->state == query_tcpw);
+        if (qu->retries > ads->nservers) {
+          LIST_UNLINK(ads->tcpw,qu);
+          adns__query_fail(qu,adns_s_allservfail);
+        }
+       }
+       ads->tcpstate= server_disconnected;
+     case server_disconnected: /* fall through */
+       if (!ads->tcpw.head) return;
+       if (!act) { inter_immed(tv_io,tvbuf); return; }
+       adns__tcp_tryconnect(ads,now);
+       break;
+     case server_ok:
+       if (ads->tcpw.head) return;
+       if (!ads->tcptimeout.tv_sec) {
+        assert(!ads->tcptimeout.tv_usec);
+        ads->tcptimeout= now;
+        timevaladd(&ads->tcptimeout,TCPIDLEMS);
+       }
+     case server_connecting: /* fall through */
+       if (!act || !timercmp(&now,&ads->tcptimeout,>)) {
+        inter_maxtoabs(tv_io,tvbuf,now,ads->tcptimeout);
+        return;
+       } {
+        /* TCP timeout has happened */
+        switch (ads->tcpstate) {
+        case server_connecting: /* failed to connect */
+          adns__tcp_broken(ads,"unable to make connection","timed out");
+          break;
+        case server_ok: /* idle timeout */
+          tcp_close(ads);
+          ads->tcpstate= server_disconnected;
+          return;
+        default:
+          abort();
+        }
+       }
+       break;
+     default:
+       abort();
+     }
+   }
+   return;
+ }
+ 
+ void adns__timeouts(adns_state ads, int act,
+                    struct timeval **tv_io, struct timeval *tvbuf,
+                    struct timeval now) {
+   timeouts_queue(ads,act,tv_io,tvbuf,now, &ads->udpw);
+   timeouts_queue(ads,act,tv_io,tvbuf,now, &ads->tcpw);
+   tcp_events(ads,act,tv_io,tvbuf,now);
+ }
+ 
+ void adns_firsttimeout(adns_state ads,
+                       struct timeval **tv_io, struct timeval *tvbuf,
+                       struct timeval now) {
+   adns__consistency(ads,0,cc_entex);
+   adns__timeouts(ads, 0, tv_io,tvbuf, now);
+   adns__consistency(ads,0,cc_entex);
+ }
+ 
+ void adns_processtimeouts(adns_state ads, const struct timeval *now) {
+   struct timeval tv_buf;
+ 
+   adns__consistency(ads,0,cc_entex);
+   adns__must_gettimeofday(ads,&now,&tv_buf);
+   if (now) adns__timeouts(ads, 1, 0,0, *now);
+   adns__consistency(ads,0,cc_entex);
+ }
+ 
+ /* fd handling functions.  These are the top-level of the real work of
+  * reception and often transmission.
+  */
+ 
+ int adns__pollfds(adns_state ads, struct pollfd pollfds_buf[MAX_POLLFDS]) {
+   /* Returns the number of entries filled in.  Always zeroes revents. */
+ 
+   assert(MAX_POLLFDS==2);
+ 
+   pollfds_buf[0].fd= ads->udpsocket;
+   pollfds_buf[0].events= POLLIN;
+   pollfds_buf[0].revents= 0;
+ 
+   switch (ads->tcpstate) {
+   case server_disconnected:
+   case server_broken:
+     return 1;
+   case server_connecting:
+     pollfds_buf[1].events= POLLOUT;
+     break;
+   case server_ok:
+     pollfds_buf[1].events= ads->tcpsend.used ? POLLIN|POLLOUT|POLLPRI : POLLIN|POLLPRI;
+     break;
+   default:
+     abort();
+   }
+   pollfds_buf[1].fd= ads->tcpsocket;
+   return 2;
+ }
+ 
+ int adns_processreadable(adns_state ads, int fd, const struct timeval *now) {
+   int want, dgramlen, r, udpaddrlen, serv, old_skip;
+   byte udpbuf[DNS_MAXUDP];
+   struct sockaddr_in udpaddr;
+   
+   adns__consistency(ads,0,cc_entex);
+ 
+   switch (ads->tcpstate) {
+   case server_disconnected:
+   case server_broken:
+   case server_connecting:
+     break;
+   case server_ok:
+     if (fd != ads->tcpsocket) break;
+     assert(!ads->tcprecv_skip);
+     do {
+       if (ads->tcprecv.used >= ads->tcprecv_skip+2) {
+        dgramlen= ((ads->tcprecv.buf[ads->tcprecv_skip]<<8) |
+                   ads->tcprecv.buf[ads->tcprecv_skip+1]);
+        if (ads->tcprecv.used >= ads->tcprecv_skip+2+dgramlen) {
+          old_skip= ads->tcprecv_skip;
+          ads->tcprecv_skip += 2+dgramlen;
+          adns__procdgram(ads, ads->tcprecv.buf+old_skip+2,
+                          dgramlen, ads->tcpserver, 1,*now);
+          continue;
+        } else {
+          want= 2+dgramlen;
+        }
+       } else {
+        want= 2;
+       }
+       ads->tcprecv.used -= ads->tcprecv_skip;
+       memmove(ads->tcprecv.buf,ads->tcprecv.buf+ads->tcprecv_skip,ads->tcprecv.used);
+       ads->tcprecv_skip= 0;
+       if (!adns__vbuf_ensure(&ads->tcprecv,want)) { r= ENOMEM; goto xit; }
+       assert(ads->tcprecv.used <= ads->tcprecv.avail);
+       if (ads->tcprecv.used == ads->tcprecv.avail) continue;
+       r= read(ads->tcpsocket,
+              ads->tcprecv.buf+ads->tcprecv.used,
+              ads->tcprecv.avail-ads->tcprecv.used);
+       if (r>0) {
+        ads->tcprecv.used+= r;
+       } else {
+        if (r) {
+          if (errno==EAGAIN || errno==EWOULDBLOCK) { r= 0; goto xit; }
+          if (errno==EINTR) continue;
+          if (errno_resources(errno)) { r= errno; goto xit; }
+        }
+        adns__tcp_broken(ads,"read",r?strerror(errno):"closed");
+       }
+     } while (ads->tcpstate == server_ok);
+     r= 0; goto xit;
+   default:
+     abort();
+   }
+   if (fd == ads->udpsocket) {
+     for (;;) {
+       udpaddrlen= sizeof(udpaddr);
+       r= recvfrom(ads->udpsocket,udpbuf,sizeof(udpbuf),0,
+                  (struct sockaddr*)&udpaddr,&udpaddrlen);
+       if (r<0) {
+        if (errno == EAGAIN || errno == EWOULDBLOCK) { r= 0; goto xit; }
+        if (errno == EINTR) continue;
+        if (errno_resources(errno)) { r= errno; goto xit; }
+        adns__warn(ads,-1,0,"datagram receive error: %s",strerror(errno));
+        r= 0; goto xit;
+       }
+       if (udpaddrlen != sizeof(udpaddr)) {
+        adns__diag(ads,-1,0,"datagram received with wrong address length %d"
+                   " (expected %d)", udpaddrlen,sizeof(udpaddr));
+        continue;
+       }
+       if (udpaddr.sin_family != AF_INET) {
+        adns__diag(ads,-1,0,"datagram received with wrong protocol family"
+                   " %u (expected %u)",udpaddr.sin_family,AF_INET);
+        continue;
+       }
+       if (ntohs(udpaddr.sin_port) != DNS_PORT) {
+        adns__diag(ads,-1,0,"datagram received from wrong port %u (expected %u)",
+                   ntohs(udpaddr.sin_port),DNS_PORT);
+        continue;
+       }
+       for (serv= 0;
+           serv < ads->nservers &&
+             ads->servers[serv].addr.s_addr != udpaddr.sin_addr.s_addr;
+           serv++);
+       if (serv >= ads->nservers) {
+        adns__warn(ads,-1,0,"datagram received from unknown nameserver %s",
+                   inet_ntoa(udpaddr.sin_addr));
+        continue;
+       }
+       adns__procdgram(ads,udpbuf,r,serv,0,*now);
+     }
+   }
+   r= 0;
+ xit:
+   adns__consistency(ads,0,cc_entex);
+   return r;
+ }
+ 
+ int adns_processwriteable(adns_state ads, int fd, const struct timeval *now) {
+   int r;
+   
+   adns__consistency(ads,0,cc_entex);
+ 
+   switch (ads->tcpstate) {
+   case server_disconnected:
+   case server_broken:
+     break;
+   case server_connecting:
+     if (fd != ads->tcpsocket) break;
+     assert(ads->tcprecv.used==0);
+     assert(ads->tcprecv_skip==0);
+     for (;;) {
+       if (!adns__vbuf_ensure(&ads->tcprecv,1)) { r= ENOMEM; goto xit; }
+       r= read(ads->tcpsocket,&ads->tcprecv.buf,1);
+       if (r==0 || (r<0 && (errno==EAGAIN || errno==EWOULDBLOCK))) {
+        tcp_connected(ads,*now);
+        r= 0; goto xit;
+       }
+       if (r>0) {
+        adns__tcp_broken(ads,"connect/read","sent data before first request");
+        r= 0; goto xit;
+       }
+       if (errno==EINTR) continue;
+       if (errno_resources(errno)) { r= errno; goto xit; }
+       adns__tcp_broken(ads,"connect/read",strerror(errno));
+       r= 0; goto xit;
+     } /* not reached */
+   case server_ok:
+     if (fd != ads->tcpsocket) break;
+     while (ads->tcpsend.used) {
+       adns__sigpipe_protect(ads);
+       r= write(ads->tcpsocket,ads->tcpsend.buf,ads->tcpsend.used);
+       adns__sigpipe_unprotect(ads);
+       if (r<0) {
+        if (errno==EINTR) continue;
+        if (errno==EAGAIN || errno==EWOULDBLOCK) { r= 0; goto xit; }
+        if (errno_resources(errno)) { r= errno; goto xit; }
+        adns__tcp_broken(ads,"write",strerror(errno));
+        r= 0; goto xit;
+       } else if (r>0) {
+        ads->tcpsend.used -= r;
+        memmove(ads->tcpsend.buf,ads->tcpsend.buf+r,ads->tcpsend.used);
+       }
+     }
+     r= 0;
+     goto xit;
+   default:
+     abort();
+   }
+   r= 0;
+ xit:
+   adns__consistency(ads,0,cc_entex);
+   return r;
+ }
+   
+ int adns_processexceptional(adns_state ads, int fd, const struct timeval *now) {
+   adns__consistency(ads,0,cc_entex);
+   switch (ads->tcpstate) {
+   case server_disconnected:
+   case server_broken:
+     break;
+   case server_connecting:
+   case server_ok:
+     if (fd != ads->tcpsocket) break;
+     adns__tcp_broken(ads,"poll/select","exceptional condition detected");
+     break;
+   default:
+     abort();
+   }
+   adns__consistency(ads,0,cc_entex);
+   return 0;
+ }
+ 
+ static void fd_event(adns_state ads, int fd,
+                     int revent, int pollflag,
+                     int maxfd, const fd_set *fds,
+                     int (*func)(adns_state, int fd, const struct timeval *now),
+                     struct timeval now, int *r_r) {
+   int r;
+   
+   if (!(revent & pollflag)) return;
+   if (fds && !(fd<maxfd && FD_ISSET(fd,fds))) return;
+   r= func(ads,fd,&now);
+   if (r) {
+     if (r_r) {
+       *r_r= r;
+     } else {
+       adns__diag(ads,-1,0,"process fd failed after select: %s",strerror(errno));
+       adns_globalsystemfailure(ads);
+     }
+   }
+ }
+ 
+ void adns__fdevents(adns_state ads,
+                    const struct pollfd *pollfds, int npollfds,
+                    int maxfd, const fd_set *readfds,
+                    const fd_set *writefds, const fd_set *exceptfds,
+                    struct timeval now, int *r_r) {
+   int i, fd, revents;
+ 
+   for (i=0; i<npollfds; i++) {
+     fd= pollfds[i].fd;
+     if (fd >= maxfd) maxfd= fd+1;
+     revents= pollfds[i].revents;
+     fd_event(ads,fd, revents,POLLIN, maxfd,readfds, adns_processreadable,now,r_r);
+     fd_event(ads,fd, revents,POLLOUT, maxfd,writefds, adns_processwriteable,now,r_r);
+     fd_event(ads,fd, revents,POLLPRI, maxfd,exceptfds, adns_processexceptional,now,r_r);
+   }
+ }
+ 
+ /* Wrappers for select(2). */
+ 
+ void adns_beforeselect(adns_state ads, int *maxfd_io, fd_set *readfds_io,
+                       fd_set *writefds_io, fd_set *exceptfds_io,
+                       struct timeval **tv_mod, struct timeval *tv_tobuf,
+                       const struct timeval *now) {
+   struct timeval tv_nowbuf;
+   struct pollfd pollfds[MAX_POLLFDS];
+   int i, fd, maxfd, npollfds;
+   
+   adns__consistency(ads,0,cc_entex);
+ 
+   if (tv_mod && (!*tv_mod || (*tv_mod)->tv_sec || (*tv_mod)->tv_usec)) {
+     /* The caller is planning to sleep. */
+     adns__must_gettimeofday(ads,&now,&tv_nowbuf);
+     if (!now) { inter_immed(tv_mod,tv_tobuf); goto xit; }
+     adns__timeouts(ads, 0, tv_mod,tv_tobuf, *now);
+   }
+ 
+   npollfds= adns__pollfds(ads,pollfds);
+   maxfd= *maxfd_io;
+   for (i=0; i<npollfds; i++) {
+     fd= pollfds[i].fd;
+     if (fd >= maxfd) maxfd= fd+1;
+     if (pollfds[i].events & POLLIN) FD_SET(fd,readfds_io);
+     if (pollfds[i].events & POLLOUT) FD_SET(fd,writefds_io);
+     if (pollfds[i].events & POLLPRI) FD_SET(fd,exceptfds_io);
+   }
+   *maxfd_io= maxfd;
+ 
+ xit:
+   adns__consistency(ads,0,cc_entex);
+ }
+ 
+ void adns_afterselect(adns_state ads, int maxfd, const fd_set *readfds,
+                      const fd_set *writefds, const fd_set *exceptfds,
+                      const struct timeval *now) {
+   struct timeval tv_buf;
+   struct pollfd pollfds[MAX_POLLFDS];
+   int npollfds, i;
+ 
+   adns__consistency(ads,0,cc_entex);
+   adns__must_gettimeofday(ads,&now,&tv_buf);
+   if (!now) goto xit;
+   adns_processtimeouts(ads,now);
+ 
+   npollfds= adns__pollfds(ads,pollfds);
+   for (i=0; i<npollfds; i++) pollfds[i].revents= POLLIN|POLLOUT|POLLPRI;
+   adns__fdevents(ads,
+                 pollfds,npollfds,
+                 maxfd,readfds,writefds,exceptfds,
+                 *now, 0);
+ xit:
+   adns__consistency(ads,0,cc_entex);
+ }
+ 
+ /* General helpful functions. */
+ 
+ void adns_globalsystemfailure(adns_state ads) {
+   adns__consistency(ads,0,cc_entex);
+ 
+   while (ads->udpw.head) adns__query_fail(ads->udpw.head, adns_s_systemfail);
+   while (ads->tcpw.head) adns__query_fail(ads->tcpw.head, adns_s_systemfail);
+   
+   switch (ads->tcpstate) {
+   case server_connecting:
+   case server_ok:
+     adns__tcp_broken(ads,0,0);
+     break;
+   case server_disconnected:
+   case server_broken:
+     break;
+   default:
+     abort();
+   }
+   adns__consistency(ads,0,cc_entex);
+ }
+ 
+ int adns_processany(adns_state ads) {
+   int r, i;
+   struct timeval now;
+   struct pollfd pollfds[MAX_POLLFDS];
+   int npollfds;
+ 
+   adns__consistency(ads,0,cc_entex);
+ 
+   r= gettimeofday(&now,0);
+   if (!r) adns_processtimeouts(ads,&now);
+ 
+   /* We just use adns__fdevents to loop over the fd's trying them.
+    * This seems more sensible than calling select, since we're most
+    * likely just to want to do a read on one or two fds anyway.
+    */
+   npollfds= adns__pollfds(ads,pollfds);
+   for (i=0; i<npollfds; i++) pollfds[i].revents= pollfds[i].events & ~POLLPRI;
+   adns__fdevents(ads,
+                 pollfds,npollfds,
+                 0,0,0,0,
+                 now,&r);
+ 
+   adns__consistency(ads,0,cc_entex);
+   return 0;
+ }
+ 
+ void adns__autosys(adns_state ads, struct timeval now) {
+   if (ads->iflags & adns_if_noautosys) return;
+   adns_processany(ads);
+ }
+ 
+ int adns__internal_check(adns_state ads,
+                         adns_query *query_io,
+                         adns_answer **answer,
+                         void **context_r) {
+   adns_query qu;
+ 
+   qu= *query_io;
+   if (!qu) {
+     if (ads->output.head) {
+       qu= ads->output.head;
+     } else if (ads->udpw.head || ads->tcpw.head) {
+       return EAGAIN;
+     } else {
+       return ESRCH;
+     }
+   } else {
+     if (qu->id>=0) return EAGAIN;
+   }
+   LIST_UNLINK(ads->output,qu);
+   *answer= qu->answer;
+   if (context_r) *context_r= qu->ctx.ext;
+   *query_io= qu;
+   free(qu);
+   return 0;
+ }
+ 
+ int adns_wait(adns_state ads,
+              adns_query *query_io,
+              adns_answer **answer_r,
+              void **context_r) {
+   int r, maxfd, rsel;
+   fd_set readfds, writefds, exceptfds;
+   struct timeval tvbuf, *tvp;
+   
+   adns__consistency(ads,*query_io,cc_entex);
+   for (;;) {
+     r= adns__internal_check(ads,query_io,answer_r,context_r);
+     if (r != EAGAIN) break;
+     maxfd= 0; tvp= 0;
+     FD_ZERO(&readfds); FD_ZERO(&writefds); FD_ZERO(&exceptfds);
+     adns_beforeselect(ads,&maxfd,&readfds,&writefds,&exceptfds,&tvp,&tvbuf,0);
+     assert(tvp);
+     rsel= select(maxfd,&readfds,&writefds,&exceptfds,tvp);
+     if (rsel==-1) {
+       if (errno == EINTR) {
+        if (ads->iflags & adns_if_eintr) { r= EINTR; break; }
+       } else {
+        adns__diag(ads,-1,0,"select failed in wait: %s",strerror(errno));
+        adns_globalsystemfailure(ads);
+       }
+     } else {
+       assert(rsel >= 0);
+       adns_afterselect(ads,maxfd,&readfds,&writefds,&exceptfds,0);
+     }
+   }
+   adns__consistency(ads,0,cc_entex);
+   return r;
+ }
+ 
+ int adns_check(adns_state ads,
+               adns_query *query_io,
+               adns_answer **answer_r,
+               void **context_r) {
+   struct timeval now;
+   int r;
+   
+   adns__consistency(ads,*query_io,cc_entex);
+   r= gettimeofday(&now,0);
+   if (!r) adns__autosys(ads,now);
+ 
+   r= adns__internal_check(ads,query_io,answer_r,context_r);
+   adns__consistency(ads,0,cc_entex);
+   return r;
+ }


ossp-pkg/adns/adns_query.c -> 1.1.1.4

*** /dev/null    Fri May  3 13:52:11 2024
--- -    Fri May  3 13:52:34 2024
***************
*** 0 ****
--- 1,572 ----
+ /*
+  * query.c
+  * - overall query management (allocation, completion)
+  * - per-query memory management
+  * - query submission and cancellation (user-visible and internal)
+  */
+ /*
+  *  This file is
+  *    Copyright (C) 1997-2000 Ian Jackson <ian@davenant.greenend.org.uk>
+  *
+  *  It is part of adns, which is
+  *    Copyright (C) 1997-2000 Ian Jackson <ian@davenant.greenend.org.uk>
+  *    Copyright (C) 1999 Tony Finch <dot@dotat.at>
+  *  
+  *  This program is free software; you can redistribute it and/or modify
+  *  it under the terms of the GNU General Public License as published by
+  *  the Free Software Foundation; either version 2, or (at your option)
+  *  any later version.
+  *  
+  *  This program is distributed in the hope that it will be useful,
+  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  *  GNU General Public License for more details.
+  *  
+  *  You should have received a copy of the GNU General Public License
+  *  along with this program; if not, write to the Free Software Foundation,
+  *  Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 
+  */
+ 
+ #include "internal.h"
+ 
+ #include <stdlib.h>
+ #include <unistd.h>
+ #include <errno.h>
+ 
+ #include <sys/time.h>
+ 
+ #include "internal.h"
+ 
+ static adns_query query_alloc(adns_state ads, const typeinfo *typei,
+                              adns_queryflags flags, struct timeval now) {
+   /* Allocate a virgin query and return it. */
+   adns_query qu;
+   
+   qu= malloc(sizeof(*qu));  if (!qu) return 0;
+   qu->answer= malloc(sizeof(*qu->answer));  if (!qu->answer) { free(qu); return 0; }
+   
+   qu->ads= ads;
+   qu->state= query_tosend;
+   qu->back= qu->next= qu->parent= 0;
+   LIST_INIT(qu->children);
+   LINK_INIT(qu->siblings);
+   LIST_INIT(qu->allocations);
+   qu->interim_allocd= 0;
+   qu->preserved_allocd= 0;
+   qu->final_allocspace= 0;
+ 
+   qu->typei= typei;
+   qu->query_dgram= 0;
+   qu->query_dglen= 0;
+   adns__vbuf_init(&qu->vb);
+ 
+   qu->cname_dgram= 0;
+   qu->cname_dglen= qu->cname_begin= 0;
+ 
+   adns__vbuf_init(&qu->search_vb);
+   qu->search_origlen= qu->search_pos= qu->search_doneabs= 0;
+ 
+   qu->id= -2; /* will be overwritten with real id before we leave adns */
+   qu->flags= flags;
+   qu->retries= 0;
+   qu->udpnextserver= 0;
+   qu->udpsent= 0;
+   timerclear(&qu->timeout);
+   qu->expires= now.tv_sec + MAXTTLBELIEVE;
+ 
+   memset(&qu->ctx,0,sizeof(qu->ctx));
+ 
+   qu->answer->status= adns_s_ok;
+   qu->answer->cname= qu->answer->owner= 0;
+   qu->answer->type= typei->type;
+   qu->answer->expires= -1;
+   qu->answer->nrrs= 0;
+   qu->answer->rrs.untyped= 0;
+   qu->answer->rrsz= typei->rrsz;
+ 
+   return qu;
+ }
+ 
+ static void query_submit(adns_state ads, adns_query qu,
+                         const typeinfo *typei, vbuf *qumsg_vb, int id,
+                         adns_queryflags flags, struct timeval now) {
+   /* Fills in the query message in for a previously-allocated query,
+    * and submits it.  Cannot fail.  Takes over the memory for qumsg_vb.
+    */
+ 
+   qu->vb= *qumsg_vb;
+   adns__vbuf_init(qumsg_vb);
+ 
+   qu->query_dgram= malloc(qu->vb.used);
+   if (!qu->query_dgram) { adns__query_fail(qu,adns_s_nomemory); return; }
+   
+   qu->id= id;
+   qu->query_dglen= qu->vb.used;
+   memcpy(qu->query_dgram,qu->vb.buf,qu->vb.used);
+   
+   adns__query_send(qu,now);
+ }
+ 
+ adns_status adns__internal_submit(adns_state ads, adns_query *query_r,
+                                  const typeinfo *typei, vbuf *qumsg_vb, int id,
+                                  adns_queryflags flags, struct timeval now,
+                                  const qcontext *ctx) {
+   adns_query qu;
+ 
+   qu= query_alloc(ads,typei,flags,now);
+   if (!qu) { adns__vbuf_free(qumsg_vb); return adns_s_nomemory; }
+   *query_r= qu;
+ 
+   memcpy(&qu->ctx,ctx,sizeof(qu->ctx));
+   query_submit(ads,qu, typei,qumsg_vb,id,flags,now);
+   
+   return adns_s_ok;
+ }
+ 
+ static void query_simple(adns_state ads, adns_query qu,
+                         const char *owner, int ol,
+                         const typeinfo *typei, adns_queryflags flags,
+                         struct timeval now) {
+   vbuf vb_new;
+   int id;
+   adns_status stat;
+ 
+   stat= adns__mkquery(ads,&qu->vb,&id, owner,ol, typei,flags);
+   if (stat) {
+     if (stat == adns_s_querydomaintoolong && (flags & adns_qf_search)) {
+       adns__search_next(ads,qu,now);
+       return;
+     } else {
+       adns__query_fail(qu,stat);
+       return;
+     }
+   }
+ 
+   vb_new= qu->vb;
+   adns__vbuf_init(&qu->vb);
+   query_submit(ads,qu, typei,&vb_new,id, flags,now);
+ }
+ 
+ void adns__search_next(adns_state ads, adns_query qu, struct timeval now) {
+   const char *nextentry;
+   adns_status stat;
+   
+   if (qu->search_doneabs<0) {
+     nextentry= 0;
+     qu->search_doneabs= 1;
+   } else {
+     if (qu->search_pos >= ads->nsearchlist) {
+       if (qu->search_doneabs) {
+        stat= adns_s_nxdomain; goto x_fail;
+        return;
+       } else {
+        nextentry= 0;
+        qu->search_doneabs= 1;
+       }
+     } else {
+       nextentry= ads->searchlist[qu->search_pos++];
+     }
+   }
+ 
+   qu->search_vb.used= qu->search_origlen;
+   if (nextentry) {
+     if (!adns__vbuf_append(&qu->search_vb,".",1) ||
+        !adns__vbuf_appendstr(&qu->search_vb,nextentry)) {
+       stat= adns_s_nomemory; goto x_fail;
+     }
+   }
+ 
+   free(qu->query_dgram);
+   qu->query_dgram= 0; qu->query_dglen= 0;
+ 
+   query_simple(ads,qu, qu->search_vb.buf, qu->search_vb.used, qu->typei, qu->flags, now);
+   return;
+   
+ x_fail:
+   adns__query_fail(qu,stat);
+ }
+ 
+ static int save_owner(adns_query qu, const char *owner, int ol) {
+   /* Returns 1 if OK, otherwise there was no memory. */
+   adns_answer *ans;
+ 
+   ans= qu->answer;
+   assert(!ans->owner);
+ 
+   ans->owner= adns__alloc_preserved(qu,ol+1);  if (!ans->owner) return 0;
+ 
+   memcpy(ans->owner,owner,ol);
+   ans->owner[ol]= 0;
+   return 1;
+ }
+ 
+ int adns_submit(adns_state ads,
+                const char *owner,
+                adns_rrtype type,
+                adns_queryflags flags,
+                void *context,
+                adns_query *query_r) {
+   int r, ol, ndots;
+   adns_status stat;
+   const typeinfo *typei;
+   struct timeval now;
+   adns_query qu;
+   const char *p;
+ 
+   adns__consistency(ads,0,cc_entex);
+ 
+   typei= adns__findtype(type);
+   if (!typei) return ENOSYS;
+ 
+   r= gettimeofday(&now,0); if (r) goto x_errno;
+   qu= query_alloc(ads,typei,flags,now); if (!qu) goto x_errno;
+   
+   qu->ctx.ext= context;
+   qu->ctx.callback= 0;
+   memset(&qu->ctx.info,0,sizeof(qu->ctx.info));
+ 
+   *query_r= qu;
+ 
+   ol= strlen(owner);
+   if (!ol) { stat= adns_s_querydomaininvalid; goto x_adnsfail; }
+   if (ol>DNS_MAXDOMAIN+1) { stat= adns_s_querydomaintoolong; goto x_adnsfail; }
+                                 
+   if (ol>=1 && owner[ol-1]=='.' && (ol<2 || owner[ol-2]!='\\')) {
+     flags &= ~adns_qf_search;
+     qu->flags= flags;
+     ol--;
+   }
+ 
+   if (flags & adns_qf_search) {
+     r= adns__vbuf_append(&qu->search_vb,owner,ol);
+     if (!r) { stat= adns_s_nomemory; goto x_adnsfail; }
+ 
+     for (ndots=0, p=owner; (p= strchr(p,'.')); p++, ndots++);
+     qu->search_doneabs= (ndots >= ads->searchndots) ? -1 : 0;
+     qu->search_origlen= ol;
+     adns__search_next(ads,qu,now);
+   } else {
+     if (flags & adns_qf_owner) {
+       if (!save_owner(qu,owner,ol)) { stat= adns_s_nomemory; goto x_adnsfail; }
+     }
+     query_simple(ads,qu, owner,ol, typei,flags, now);
+   }
+   adns__autosys(ads,now);
+   adns__consistency(ads,qu,cc_entex);
+   return 0;
+ 
+  x_adnsfail:
+   adns__query_fail(qu,stat);
+   adns__consistency(ads,qu,cc_entex);
+   return 0;
+ 
+  x_errno:
+   r= errno;
+   assert(r);
+   adns__consistency(ads,0,cc_entex);
+   return r;
+ }
+ 
+ int adns_submit_reverse_any(adns_state ads,
+                            const struct sockaddr *addr,
+                            const char *zone,
+                            adns_rrtype type,
+                            adns_queryflags flags,
+                            void *context,
+                            adns_query *query_r) {
+   const unsigned char *iaddr;
+   char *buf, *buf_free;
+   char shortbuf[100];
+   int r, lreq;
+ 
+   flags &= ~adns_qf_search;
+ 
+   if (addr->sa_family != AF_INET) return ENOSYS;
+   iaddr= (const unsigned char*) &(((const struct sockaddr_in*)addr) -> sin_addr);
+ 
+   lreq= strlen(zone) + 4*4 + 1;
+   if (lreq > sizeof(shortbuf)) {
+     buf= malloc(strlen(zone) + 4*4 + 1);
+     if (!buf) return errno;
+     buf_free= buf;
+   } else {
+     buf= shortbuf;
+     buf_free= 0;
+   }
+   sprintf(buf, "%d.%d.%d.%d.%s", iaddr[3], iaddr[2], iaddr[1], iaddr[0], zone);
+ 
+   r= adns_submit(ads,buf,type,flags,context,query_r);
+   free(buf_free);
+   return r;
+ }
+ 
+ int adns_submit_reverse(adns_state ads,
+                        const struct sockaddr *addr,
+                        adns_rrtype type,
+                        adns_queryflags flags,
+                        void *context,
+                        adns_query *query_r) {
+   if (type != adns_r_ptr && type != adns_r_ptr_raw) return EINVAL;
+   return adns_submit_reverse_any(ads,addr,"in-addr.arpa",type,flags,context,query_r);
+ }
+ 
+ int adns_synchronous(adns_state ads,
+                     const char *owner,
+                     adns_rrtype type,
+                     adns_queryflags flags,
+                     adns_answer **answer_r) {
+   adns_query qu;
+   int r;
+   
+   r= adns_submit(ads,owner,type,flags,0,&qu);
+   if (r) return r;
+ 
+   r= adns_wait(ads,&qu,answer_r,0);
+   if (r) adns_cancel(qu);
+ 
+   return r;
+ }
+ 
+ static void *alloc_common(adns_query qu, size_t sz) {
+   allocnode *an;
+ 
+   if (!sz) return qu; /* Any old pointer will do */
+   assert(!qu->final_allocspace);
+   an= malloc(MEM_ROUND(MEM_ROUND(sizeof(*an)) + sz));
+   if (!an) return 0;
+   LIST_LINK_TAIL(qu->allocations,an);
+   return (byte*)an + MEM_ROUND(sizeof(*an));
+ }
+ 
+ void *adns__alloc_interim(adns_query qu, size_t sz) {
+   void *rv;
+   
+   sz= MEM_ROUND(sz);
+   rv= alloc_common(qu,sz);
+   if (!rv) return 0;
+   qu->interim_allocd += sz;
+   return rv;
+ }
+ 
+ void *adns__alloc_preserved(adns_query qu, size_t sz) {
+   void *rv;
+   
+   sz= MEM_ROUND(sz);
+   rv= adns__alloc_interim(qu,sz);
+   if (!rv) return 0;
+   qu->preserved_allocd += sz;
+   return rv;
+ }
+ 
+ void *adns__alloc_mine(adns_query qu, size_t sz) {
+   return alloc_common(qu,MEM_ROUND(sz));
+ }
+ 
+ void adns__transfer_interim(adns_query from, adns_query to, void *block, size_t sz) {
+   allocnode *an;
+ 
+   if (!block) return;
+   an= (void*)((byte*)block - MEM_ROUND(sizeof(*an)));
+ 
+   assert(!to->final_allocspace);
+   assert(!from->final_allocspace);
+   
+   LIST_UNLINK(from->allocations,an);
+   LIST_LINK_TAIL(to->allocations,an);
+ 
+   sz= MEM_ROUND(sz);
+   from->interim_allocd -= sz;
+   to->interim_allocd += sz;
+ 
+   if (to->expires > from->expires) to->expires= from->expires;
+ }
+ 
+ void *adns__alloc_final(adns_query qu, size_t sz) {
+   /* When we're in the _final stage, we _subtract_ from interim_alloc'd
+    * each allocation, and use final_allocspace to point to the next free
+    * bit.
+    */
+   void *rp;
+ 
+   sz= MEM_ROUND(sz);
+   rp= qu->final_allocspace;
+   assert(rp);
+   qu->interim_allocd -= sz;
+   assert(qu->interim_allocd>=0);
+   qu->final_allocspace= (byte*)rp + sz;
+   return rp;
+ }
+ 
+ static void cancel_children(adns_query qu) {
+   adns_query cqu, ncqu;
+ 
+   for (cqu= qu->children.head; cqu; cqu= ncqu) {
+     ncqu= cqu->siblings.next;
+     adns_cancel(cqu);
+   }
+ }
+ 
+ void adns__reset_preserved(adns_query qu) {
+   assert(!qu->final_allocspace);
+   cancel_children(qu);
+   qu->answer->nrrs= 0;
+   qu->answer->rrs.untyped= 0;
+   qu->interim_allocd= qu->preserved_allocd;
+ }
+ 
+ static void free_query_allocs(adns_query qu) {
+   allocnode *an, *ann;
+ 
+   cancel_children(qu);
+   for (an= qu->allocations.head; an; an= ann) { ann= an->next; free(an); }
+   LIST_INIT(qu->allocations);
+   adns__vbuf_free(&qu->vb);
+   adns__vbuf_free(&qu->search_vb);
+   free(qu->query_dgram);
+   qu->query_dgram= 0;
+ }
+ 
+ void adns_cancel(adns_query qu) {
+   adns_state ads;
+ 
+   ads= qu->ads;
+   adns__consistency(ads,qu,cc_entex);
+   if (qu->parent) LIST_UNLINK_PART(qu->parent->children,qu,siblings.);
+   switch (qu->state) {
+   case query_tosend:
+     LIST_UNLINK(ads->udpw,qu);
+     break;
+   case query_tcpw:
+     LIST_UNLINK(ads->tcpw,qu);
+     break;
+   case query_childw:
+     LIST_UNLINK(ads->childw,qu);
+     break;
+   case query_done:
+     LIST_UNLINK(ads->output,qu);
+     break;
+   default:
+     abort();
+   }
+   free_query_allocs(qu);
+   free(qu->answer);
+   free(qu);
+   adns__consistency(ads,0,cc_entex);
+ }
+ 
+ void adns__update_expires(adns_query qu, unsigned long ttl, struct timeval now) {
+   time_t max;
+ 
+   assert(ttl <= MAXTTLBELIEVE);
+   max= now.tv_sec + ttl;
+   if (qu->expires < max) return;
+   qu->expires= max;
+ }
+ 
+ static void makefinal_query(adns_query qu) {
+   adns_answer *ans;
+   int rrn;
+ 
+   ans= qu->answer;
+ 
+   if (qu->interim_allocd) {
+     ans= realloc(qu->answer, MEM_ROUND(MEM_ROUND(sizeof(*ans)) + qu->interim_allocd));
+     if (!ans) goto x_nomem;
+     qu->answer= ans;
+   }
+ 
+   qu->final_allocspace= (byte*)ans + MEM_ROUND(sizeof(*ans));
+   adns__makefinal_str(qu,&ans->cname);
+   adns__makefinal_str(qu,&ans->owner);
+   
+   if (ans->nrrs) {
+     adns__makefinal_block(qu, &ans->rrs.untyped, ans->nrrs*ans->rrsz);
+ 
+     for (rrn=0; rrn<ans->nrrs; rrn++)
+       qu->typei->makefinal(qu, ans->rrs.bytes + rrn*ans->rrsz);
+   }
+   
+   free_query_allocs(qu);
+   return;
+   
+  x_nomem:
+   qu->preserved_allocd= 0;
+   qu->answer->cname= 0;
+   qu->answer->owner= 0;
+   adns__reset_preserved(qu); /* (but we just threw away the preserved stuff) */
+ 
+   qu->answer->status= adns_s_nomemory;
+   free_query_allocs(qu);
+ }
+ 
+ void adns__query_done(adns_query qu) {
+   adns_answer *ans;
+   adns_query parent;
+ 
+   cancel_children(qu);
+ 
+   qu->id= -1;
+   ans= qu->answer;
+ 
+   if (qu->flags & adns_qf_owner && qu->flags & adns_qf_search &&
+       ans->status != adns_s_nomemory) {
+     if (!save_owner(qu, qu->search_vb.buf, qu->search_vb.used)) {
+       adns__query_fail(qu,adns_s_nomemory);
+       return;
+     }
+   }
+ 
+   if (ans->nrrs && qu->typei->diff_needswap) {
+     if (!adns__vbuf_ensure(&qu->vb,qu->typei->rrsz)) {
+       adns__query_fail(qu,adns_s_nomemory);
+       return;
+     }
+     adns__isort(ans->rrs.bytes, ans->nrrs, ans->rrsz,
+                qu->vb.buf,
+                (int(*)(void*, const void*, const void*))qu->typei->diff_needswap,
+                qu->ads);
+   }
+ 
+   ans->expires= qu->expires;
+   parent= qu->parent;
+   if (parent) {
+     LIST_UNLINK_PART(parent->children,qu,siblings.);
+     LIST_UNLINK(qu->ads->childw,parent);
+     qu->ctx.callback(parent,qu);
+     free_query_allocs(qu);
+     free(qu->answer);
+     free(qu);
+   } else {
+     makefinal_query(qu);
+     LIST_LINK_TAIL(qu->ads->output,qu);
+     qu->state= query_done;
+   }
+ }
+ 
+ void adns__query_fail(adns_query qu, adns_status stat) {
+   adns__reset_preserved(qu);
+   qu->answer->status= stat;
+   adns__query_done(qu);
+ }
+ 
+ void adns__makefinal_str(adns_query qu, char **strp) {
+   int l;
+   char *before, *after;
+ 
+   before= *strp;
+   if (!before) return;
+   l= strlen(before)+1;
+   after= adns__alloc_final(qu,l);
+   memcpy(after,before,l);
+   *strp= after;  
+ }
+ 
+ void adns__makefinal_block(adns_query qu, void **blpp, size_t sz) {
+   void *before, *after;
+ 
+   before= *blpp;
+   if (!before) return;
+   after= adns__alloc_final(qu,sz);
+   memcpy(after,before,sz);
+   *blpp= after;
+ }


ossp-pkg/adns/adns_reply.c -> 1.1.1.4

*** /dev/null    Fri May  3 13:52:11 2024
--- -    Fri May  3 13:52:34 2024
***************
*** 0 ****
--- 1,370 ----
+ /*
+  * reply.c
+  * - main handling and parsing routine for received datagrams
+  */
+ /*
+  *  This file is
+  *    Copyright (C) 1997-2000 Ian Jackson <ian@davenant.greenend.org.uk>
+  *
+  *  It is part of adns, which is
+  *    Copyright (C) 1997-2000 Ian Jackson <ian@davenant.greenend.org.uk>
+  *    Copyright (C) 1999 Tony Finch <dot@dotat.at>
+  *  
+  *  This program is free software; you can redistribute it and/or modify
+  *  it under the terms of the GNU General Public License as published by
+  *  the Free Software Foundation; either version 2, or (at your option)
+  *  any later version.
+  *  
+  *  This program is distributed in the hope that it will be useful,
+  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  *  GNU General Public License for more details.
+  *  
+  *  You should have received a copy of the GNU General Public License
+  *  along with this program; if not, write to the Free Software Foundation,
+  *  Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 
+  */
+ 
+ #include <stdlib.h>
+ 
+ #include "internal.h"
+     
+ void adns__procdgram(adns_state ads, const byte *dgram, int dglen,
+                     int serv, int viatcp, struct timeval now) {
+   int cbyte, rrstart, wantedrrs, rri, foundsoa, foundns, cname_here;
+   int id, f1, f2, qdcount, ancount, nscount, arcount;
+   int flg_ra, flg_rd, flg_tc, flg_qr, opcode;
+   int rrtype, rrclass, rdlength, rdstart;
+   int anstart, nsstart, arstart;
+   int ownermatched, l, nrrs;
+   unsigned long ttl, soattl;
+   const typeinfo *typei;
+   adns_query qu, nqu;
+   dns_rcode rcode;
+   adns_status st;
+   vbuf tempvb;
+   byte *newquery, *rrsdata;
+   parseinfo pai;
+   
+   if (dglen<DNS_HDRSIZE) {
+     adns__diag(ads,serv,0,"received datagram too short for message header (%d)",dglen);
+     return;
+   }
+   cbyte= 0;
+   GET_W(cbyte,id);
+   GET_B(cbyte,f1);
+   GET_B(cbyte,f2);
+   GET_W(cbyte,qdcount);
+   GET_W(cbyte,ancount);
+   GET_W(cbyte,nscount);
+   GET_W(cbyte,arcount);
+   assert(cbyte == DNS_HDRSIZE);
+ 
+   flg_qr= f1&0x80;
+   opcode= (f1&0x78)>>3;
+   flg_tc= f1&0x02;
+   flg_rd= f1&0x01;
+   flg_ra= f2&0x80;
+   rcode= (f2&0x0f);
+ 
+   cname_here= 0;
+   
+   if (!flg_qr) {
+     adns__diag(ads,serv,0,"server sent us a query, not a response");
+     return;
+   }
+   if (opcode) {
+     adns__diag(ads,serv,0,"server sent us unknown opcode %d (wanted 0=QUERY)",opcode);
+     return;
+   }
+ 
+   qu= 0;
+   /* See if we can find the relevant query, or leave qu=0 otherwise ... */   
+ 
+   if (qdcount == 1) {
+     for (qu= viatcp ? ads->tcpw.head : ads->udpw.head; qu; qu= nqu) {
+       nqu= qu->next;
+       if (qu->id != id) continue;
+       if (dglen < qu->query_dglen) continue;
+       if (memcmp(qu->query_dgram+DNS_HDRSIZE,
+                 dgram+DNS_HDRSIZE,
+                 qu->query_dglen-DNS_HDRSIZE))
+        continue;
+       if (viatcp) {
+        assert(qu->state == query_tcpw);
+       } else {
+        assert(qu->state == query_tosend);
+        if (!(qu->udpsent & (1<<serv))) continue;
+       }
+       break;
+     }
+     if (qu) {
+       /* We're definitely going to do something with this query now */
+       if (viatcp) LIST_UNLINK(ads->tcpw,qu);
+       else LIST_UNLINK(ads->udpw,qu);
+     }
+   }
+   
+   /* If we're going to ignore the packet, we return as soon as we have
+    * failed the query (if any) and printed the warning message (if
+    * any).
+    */
+   switch (rcode) {
+   case rcode_noerror:
+   case rcode_nxdomain:
+     break;
+   case rcode_formaterror:
+     adns__warn(ads,serv,qu,"server cannot understand our query (Format Error)");
+     if (qu) adns__query_fail(qu,adns_s_rcodeformaterror);
+     return;
+   case rcode_servfail:
+     if (qu) adns__query_fail(qu,adns_s_rcodeservfail);
+     else adns__debug(ads,serv,qu,"server failure on unidentifiable query");
+     return;
+   case rcode_notimp:
+     adns__warn(ads,serv,qu,"server claims not to implement our query");
+     if (qu) adns__query_fail(qu,adns_s_rcodenotimplemented);
+     return;
+   case rcode_refused:
+     adns__debug(ads,serv,qu,"server refused our query");
+     if (qu) adns__query_fail(qu,adns_s_rcoderefused);
+     return;
+   default:
+     adns__warn(ads,serv,qu,"server gave unknown response code %d",rcode);
+     if (qu) adns__query_fail(qu,adns_s_rcodeunknown);
+     return;
+   }
+ 
+   if (!qu) {
+     if (!qdcount) {
+       adns__diag(ads,serv,0,"server sent reply without quoting our question");
+     } else if (qdcount>1) {
+       adns__diag(ads,serv,0,"server claimed to answer %d questions with one message",
+                 qdcount);
+     } else if (ads->iflags & adns_if_debug) {
+       adns__vbuf_init(&tempvb);
+       adns__debug(ads,serv,0,"reply not found, id %02x, query owner %s",
+                  id, adns__diag_domain(ads,serv,0,&tempvb,dgram,dglen,DNS_HDRSIZE));
+       adns__vbuf_free(&tempvb);
+     }
+     return;
+   }
+ 
+   /* We're definitely going to do something with this packet and this query now. */
+   
+   anstart= qu->query_dglen;
+   arstart= -1;
+ 
+   /* Now, take a look at the answer section, and see if it is complete.
+    * If it has any CNAMEs we stuff them in the answer.
+    */
+   wantedrrs= 0;
+   cbyte= anstart;
+   for (rri= 0; rri<ancount; rri++) {
+     rrstart= cbyte;
+     st= adns__findrr(qu,serv, dgram,dglen,&cbyte,
+                     &rrtype,&rrclass,&ttl, &rdlength,&rdstart,
+                     &ownermatched);
+     if (st) { adns__query_fail(qu,st); return; }
+     if (rrtype == -1) goto x_truncated;
+ 
+     if (rrclass != DNS_CLASS_IN) {
+       adns__diag(ads,serv,qu,"ignoring answer RR with wrong class %d (expected IN=%d)",
+                 rrclass,DNS_CLASS_IN);
+       continue;
+     }
+     if (!ownermatched) {
+       if (ads->iflags & adns_if_debug) {
+        adns__debug(ads,serv,qu,"ignoring RR with an unexpected owner %s",
+                    adns__diag_domain(ads,serv,qu, &qu->vb, dgram,dglen,rrstart));
+       }
+       continue;
+     }
+     if (rrtype == adns_r_cname &&
+        (qu->typei->type & adns__rrt_typemask) != adns_r_cname) {
+       if (qu->flags & adns_qf_cname_forbid) {
+        adns__query_fail(qu,adns_s_prohibitedcname);
+        return;
+       } else if (qu->cname_dgram) { /* Ignore second and subsequent CNAME(s) */
+        adns__debug(ads,serv,qu,"allegedly canonical name %s is actually alias for %s",
+                    qu->answer->cname,
+                    adns__diag_domain(ads,serv,qu, &qu->vb, dgram,dglen,rdstart));
+        adns__query_fail(qu,adns_s_prohibitedcname);
+        return;
+       } else if (wantedrrs) { /* Ignore CNAME(s) after RR(s). */
+        adns__debug(ads,serv,qu,"ignoring CNAME (to %s) coexisting with RR",
+                    adns__diag_domain(ads,serv,qu, &qu->vb, dgram,dglen,rdstart));
+       } else {
+        qu->cname_begin= rdstart;
+        qu->cname_dglen= dglen;
+        st= adns__parse_domain(ads,serv,qu, &qu->vb,
+                               qu->flags & adns_qf_quotefail_cname ? 0 : pdf_quoteok,
+                               dgram,dglen, &rdstart,rdstart+rdlength);
+        if (!qu->vb.used) goto x_truncated;
+        if (st) { adns__query_fail(qu,st); return; }
+        l= strlen(qu->vb.buf)+1;
+        qu->answer->cname= adns__alloc_preserved(qu,l);
+        if (!qu->answer->cname) { adns__query_fail(qu,adns_s_nomemory); return; }
+ 
+        qu->cname_dgram= adns__alloc_mine(qu,dglen);
+        memcpy(qu->cname_dgram,dgram,dglen);
+ 
+        memcpy(qu->answer->cname,qu->vb.buf,l);
+        cname_here= 1;
+        adns__update_expires(qu,ttl,now);
+        /* If we find the answer section truncated after this point we restart
+         * the query at the CNAME; if beforehand then we obviously have to use
+         * TCP.  If there is no truncation we can use the whole answer if
+         * it contains the relevant info.
+         */
+       }
+     } else if (rrtype == (qu->typei->type & adns__rrt_typemask)) {
+       wantedrrs++;
+     } else {
+       adns__debug(ads,serv,qu,"ignoring answer RR with irrelevant type %d",rrtype);
+     }
+   }
+ 
+   /* We defer handling truncated responses here, in case there was a CNAME
+    * which we could use.
+    */
+   if (flg_tc) goto x_truncated;
+   
+   nsstart= cbyte;
+ 
+   if (!wantedrrs) {
+     /* Oops, NODATA or NXDOMAIN or perhaps a referral (which would be a problem) */
+ 
+     /* RFC2308: NODATA has _either_ a SOA _or_ _no_ NS records in authority section */
+     foundsoa= 0; soattl= 0; foundns= 0;
+     for (rri= 0; rri<nscount; rri++) {
+       rrstart= cbyte;
+       st= adns__findrr(qu,serv, dgram,dglen,&cbyte,
+                       &rrtype,&rrclass,&ttl, &rdlength,&rdstart, 0);
+       if (st) { adns__query_fail(qu,st); return; }
+       if (rrtype==-1) goto x_truncated;
+       if (rrclass != DNS_CLASS_IN) {
+        adns__diag(ads,serv,qu,
+                   "ignoring authority RR with wrong class %d (expected IN=%d)",
+                   rrclass,DNS_CLASS_IN);
+        continue;
+       }
+       if (rrtype == adns_r_soa_raw) { foundsoa= 1; soattl= ttl; break; }
+       else if (rrtype == adns_r_ns_raw) { foundns= 1; }
+     }
+     
+     if (rcode == rcode_nxdomain) {
+       /* We still wanted to look for the SOA so we could find the TTL. */
+       adns__update_expires(qu,soattl,now);
+ 
+       if (qu->flags & adns_qf_search) {
+        adns__search_next(ads,qu,now);
+       } else {
+        adns__query_fail(qu,adns_s_nxdomain);
+       }
+       return;
+     }
+ 
+     if (foundsoa || !foundns) {
+       /* Aha !  A NODATA response, good. */
+       adns__update_expires(qu,soattl,now);
+       adns__query_fail(qu,adns_s_nodata);
+       return;
+     }
+ 
+     /* Now what ?  No relevant answers, no SOA, and at least some NS's.
+      * Looks like a referral.  Just one last chance ... if we came across
+      * a CNAME in this datagram then we should probably do our own CNAME
+      * lookup now in the hope that we won't get a referral again.
+      */
+     if (cname_here) goto x_restartquery;
+ 
+     /* Bloody hell, I thought we asked for recursion ? */
+     if (!flg_ra) {
+       adns__diag(ads,serv,qu,"server is not willing to do recursive lookups for us");
+       adns__query_fail(qu,adns_s_norecurse);
+     } else {
+       if (!flg_rd)
+        adns__diag(ads,serv,qu,"server thinks we didn't ask for recursive lookup");
+       else
+        adns__debug(ads,serv,qu,"server claims to do recursion, but gave us a referral");
+       adns__query_fail(qu,adns_s_invalidresponse);
+     }
+     return;
+   }
+ 
+   /* Now, we have some RRs which we wanted. */
+ 
+   qu->answer->rrs.untyped= adns__alloc_interim(qu,qu->typei->rrsz*wantedrrs);
+   if (!qu->answer->rrs.untyped) { adns__query_fail(qu,adns_s_nomemory); return; }
+ 
+   typei= qu->typei;
+   cbyte= anstart;
+   rrsdata= qu->answer->rrs.bytes;
+ 
+   pai.ads= qu->ads;
+   pai.qu= qu;
+   pai.serv= serv;
+   pai.dgram= dgram;
+   pai.dglen= dglen;
+   pai.nsstart= nsstart;
+   pai.nscount= nscount;
+   pai.arcount= arcount;
+   pai.now= now;
+ 
+   for (rri=0, nrrs=0; rri<ancount; rri++) {
+     st= adns__findrr(qu,serv, dgram,dglen,&cbyte,
+                     &rrtype,&rrclass,&ttl, &rdlength,&rdstart,
+                     &ownermatched);
+     assert(!st); assert(rrtype != -1);
+     if (rrclass != DNS_CLASS_IN ||
+        rrtype != (qu->typei->type & adns__rrt_typemask) ||
+        !ownermatched)
+       continue;
+     adns__update_expires(qu,ttl,now);
+     st= typei->parse(&pai, rdstart,rdstart+rdlength, rrsdata+nrrs*typei->rrsz);
+     if (st) { adns__query_fail(qu,st); return; }
+     if (rdstart==-1) goto x_truncated;
+     nrrs++;
+   }
+   assert(nrrs==wantedrrs);
+   qu->answer->nrrs= nrrs;
+ 
+   /* This may have generated some child queries ... */
+   if (qu->children.head) {
+     qu->state= query_childw;
+     LIST_LINK_TAIL(ads->childw,qu);
+     return;
+   }
+   adns__query_done(qu);
+   return;
+ 
+  x_truncated:
+   
+   if (!flg_tc) {
+     adns__diag(ads,serv,qu,"server sent datagram which points outside itself");
+     adns__query_fail(qu,adns_s_invalidresponse);
+     return;
+   }
+   qu->flags |= adns_qf_usevc;
+   
+  x_restartquery:
+   if (qu->cname_dgram) {
+     st= adns__mkquery_frdgram(qu->ads,&qu->vb,&qu->id,
+                              qu->cname_dgram, qu->cname_dglen, qu->cname_begin,
+                              qu->typei->type, qu->flags);
+     if (st) { adns__query_fail(qu,st); return; }
+     
+     newquery= realloc(qu->query_dgram,qu->vb.used);
+     if (!newquery) { adns__query_fail(qu,adns_s_nomemory); return; }
+     
+     qu->query_dgram= newquery;
+     qu->query_dglen= qu->vb.used;
+     memcpy(newquery,qu->vb.buf,qu->vb.used);
+   }
+   
+   if (qu->state == query_tcpw) qu->state= query_tosend;
+   qu->retries= 0;
+   adns__reset_preserved(qu);
+   adns__query_send(qu,now);
+ }


ossp-pkg/adns/adns_test.c -> 1.1.1.3

*** /dev/null    Fri May  3 13:52:11 2024
--- -    Fri May  3 13:52:34 2024
***************
*** 0 ****
--- 1,339 ----
+ /*
+  * adnstest.c
+  * - simple test program, not part of the library
+  */
+ /*
+  *  This file is
+  *    Copyright (C) 1997-1999 Ian Jackson <ian@davenant.greenend.org.uk>
+  *
+  *  It is part of adns, which is
+  *    Copyright (C) 1997-2000 Ian Jackson <ian@davenant.greenend.org.uk>
+  *    Copyright (C) 1999 Tony Finch <dot@dotat.at>
+  *  
+  *  This program is free software; you can redistribute it and/or modify
+  *  it under the terms of the GNU General Public License as published by
+  *  the Free Software Foundation; either version 2, or (at your option)
+  *  any later version.
+  *  
+  *  This program is distributed in the hope that it will be useful,
+  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  *  GNU General Public License for more details.
+  *  
+  *  You should have received a copy of the GNU General Public License
+  *  along with this program; if not, write to the Free Software Foundation,
+  *  Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 
+  */
+ 
+ #include <stdio.h>
+ #include <sys/time.h>
+ #include <unistd.h>
+ #include <assert.h>
+ #include <stdlib.h>
+ #include <string.h>
+ #include <errno.h>
+ 
+ #include "adns.h"
+ 
+ #include "config.h"
+ 
+ #ifndef OUTPUTSTREAM
+ # define OUTPUTSTREAM stdout
+ #endif
+ 
+ struct myctx {
+   adns_query qu;
+   int doneyet, found;
+   const char *fdom;
+ };
+   
+ static struct myctx *mcs;
+ static adns_state ads;
+ static adns_rrtype *types_a;
+ 
+ static void quitnow(int rc) NONRETURNING;
+ static void quitnow(int rc) {
+   free(mcs);
+   free(types_a);
+   if (ads) adns_finish(ads);
+   
+   exit(rc);
+ }
+ 
+ #ifndef HAVE_POLL
+ #undef poll
+ int poll(struct pollfd *ufds, int nfds, int timeout) {
+   fputs("poll(2) not supported on this system\n",stderr);
+   quitnow(5);
+ }
+ #define adns_beforepoll(a,b,c,d,e) 0
+ #define adns_afterpoll(a,b,c,d) 0
+ #endif
+ 
+ static void failure_status(const char *what, adns_status st) NONRETURNING;
+ static void failure_status(const char *what, adns_status st) {
+   fprintf(stderr,"adns failure: %s: %s\n",what,adns_strerror(st));
+   quitnow(2);
+ }
+ 
+ static void failure_errno(const char *what, int errnoval) NONRETURNING;
+ static void failure_errno(const char *what, int errnoval) {
+   fprintf(stderr,"adns failure: %s: errno=%d\n",what,errnoval);
+   quitnow(2);
+ }
+ 
+ static void usageerr(const char *why) NONRETURNING;
+ static void usageerr(const char *why) {
+   fprintf(stderr,
+          "bad usage: %s\n"
+          "usage: adnstest [-<initflagsnum>[,<owninitflags>]] [/<initstring>]\n"
+          "              [ :<typenum>,... ]\n"
+          "              [ [<queryflagsnum>[,<ownqueryflags>]/]<domain> ... ]\n"
+          "initflags:   p  use poll(2) instead of select(2)\n"
+          "             s  use adns_wait with specified query, instead of 0\n"
+          "queryflags:  a  print status abbrevs instead of strings\n"
+          "exit status:  0 ok (though some queries may have failed)\n"
+          "              1 used by test harness to indicate test failed\n"
+          "              2 unable to submit or init or some such\n"
+          "              3 unexpected failure\n"
+          "              4 usage error\n"
+          "              5 operation not supported on this system\n",
+          why);
+   quitnow(4);
+ }
+ 
+ static const adns_rrtype defaulttypes[]= {
+   adns_r_a,
+   adns_r_ns_raw,
+   adns_r_cname,
+   adns_r_soa_raw,
+   adns_r_ptr_raw,
+   adns_r_hinfo,
+   adns_r_mx_raw,
+   adns_r_txt,
+   adns_r_rp_raw,
+   
+   adns_r_addr,
+   adns_r_ns,
+   adns_r_ptr,
+   adns_r_mx,
+   
+   adns_r_soa,
+   adns_r_rp,
+ 
+   adns_r_none
+ };
+ 
+ static void dumptype(adns_status ri, const char *rrtn, const char *fmtn) {
+   fprintf(stdout, "%s(%s)%s%s",
+          ri ? "?" : rrtn, ri ? "?" : fmtn ? fmtn : "-",
+          ri ? " " : "", ri ? adns_strerror(ri) : "");
+ }
+ 
+ static void fdom_split(const char *fdom, const char **dom_r, int *qf_r,
+                       char *ownflags, int ownflags_l) {
+   int qf;
+   char *ep;
+ 
+   qf= strtoul(fdom,&ep,0);
+   if (*ep == ',' && strchr(ep,'/')) {
+     ep++;
+     while (*ep != '/') {
+       if (--ownflags_l <= 0) { fputs("too many flags\n",stderr); quitnow(3); }
+       *ownflags++= *ep++;
+     }
+   }
+   if (*ep != '/') { *dom_r= fdom; *qf_r= 0; }
+   else { *dom_r= ep+1; *qf_r= qf; }
+   *ownflags= 0;
+ }
+ 
+ static int consistsof(const char *string, const char *accept) {
+   return strspn(string,accept) == strlen(string);
+ }
+ 
+ int main(int argc, char *const *argv) {
+   adns_query qu;
+   struct myctx *mc, *mcw;
+   void *mcr;
+   adns_answer *ans;
+   const char *initstring, *rrtn, *fmtn;
+   const char *const *fdomlist, *domain;
+   char *show, *cp;
+   int len, i, qc, qi, tc, ti, ch, qflags, initflagsnum;
+   adns_status ri;
+   int r;
+   const adns_rrtype *types;
+   struct timeval now;
+   char ownflags[10];
+   char *ep;
+   const char *initflags, *owninitflags;
+ 
+   if (argv[0] && argv[1] && argv[1][0] == '-') {
+     initflags= argv[1]+1;
+     argv++;
+   } else {
+     initflags= "";
+   }
+   if (argv[0] && argv[1] && argv[1][0] == '/') {
+     initstring= argv[1]+1;
+     argv++;
+   } else {
+     initstring= 0;
+   }
+ 
+   initflagsnum= strtoul(initflags,&ep,0);
+   if (*ep == ',') {
+     owninitflags= ep+1;
+     if (!consistsof(owninitflags,"ps")) usageerr("unknown owninitflag");
+   } else if (!*ep) {
+     owninitflags= "";
+   } else {
+     usageerr("bad <initflagsnum>[,<owninitflags>]");
+   }
+   
+   if (argv[0] && argv[1] && argv[1][0] == ':') {
+     for (cp= argv[1]+1, tc=1; (ch= *cp); cp++)
+       if (ch==',') tc++;
+     types_a= malloc(sizeof(*types_a)*(tc+1));
+     if (!types_a) { perror("malloc types"); quitnow(3); }
+     for (cp= argv[1]+1, ti=0; ti<tc; ti++) {
+       types_a[ti]= strtoul(cp,&cp,10);
+       if ((ch= *cp)) {
+        if (ch != ',') usageerr("unexpected char (not comma) in or between types");
+        cp++;
+       }
+     }
+     types_a[ti]= adns_r_none;
+     types= types_a;
+     argv++;
+   } else {
+     types_a= 0;
+     types= defaulttypes;
+   }
+   
+   if (!(argv[0] && argv[1])) usageerr("no query domains supplied");
+   fdomlist= (const char *const*)argv+1;
+ 
+   for (qc=0; fdomlist[qc]; qc++);
+   for (tc=0; types[tc] != adns_r_none; tc++);
+   mcs= malloc(tc ? sizeof(*mcs)*qc*tc : 1);
+   if (!mcs) { perror("malloc mcs"); quitnow(3); }
+ 
+   if (initstring) {
+     r= adns_init_strcfg(&ads,
+                        (adns_if_debug|adns_if_noautosys|adns_if_checkc_freq)
+                        ^initflagsnum,
+                        stdout,initstring);
+   } else {
+     r= adns_init(&ads,
+                 (adns_if_debug|adns_if_noautosys)^initflagsnum,
+                 0);
+   }
+   if (r) failure_errno("init",r);
+ 
+   setvbuf(stdout,0,_IOLBF,0);
+   
+   for (qi=0; qi<qc; qi++) {
+     fdom_split(fdomlist[qi],&domain,&qflags,ownflags,sizeof(ownflags));
+     if (!consistsof(ownflags,"a")) usageerr("unknown ownqueryflag");
+     for (ti=0; ti<tc; ti++) {
+       mc= &mcs[qi*tc+ti];
+       mc->doneyet= 0;
+       mc->fdom= fdomlist[qi];
+ 
+       fprintf(stdout,"%s flags %d type %d",domain,qflags,types[ti]);
+       r= adns_submit(ads,domain,types[ti],qflags,mc,&mc->qu);
+       if (r == ENOSYS) {
+        fprintf(stdout," not implemented\n");
+        mc->qu= 0;
+        mc->doneyet= 1;
+       } else if (r) {
+        failure_errno("submit",r);
+       } else {
+        ri= adns_rr_info(types[ti], &rrtn,&fmtn,0, 0,0);
+        putc(' ',stdout);
+        dumptype(ri,rrtn,fmtn);
+        fprintf(stdout," submitted\n");
+       }
+     }
+   }
+ 
+   for (;;) {
+     for (qi=0; qi<qc; qi++) {
+       for (ti=0; ti<tc; ti++) {
+        mc= &mcs[qi*tc+ti];
+        mc->found= 0;
+       }
+     }
+     for (adns_forallqueries_begin(ads);
+         (qu= adns_forallqueries_next(ads,&mcr));
+         ) {
+       mc= mcr;
+       assert(qu == mc->qu);
+       assert(!mc->doneyet);
+       mc->found= 1;
+     }
+     mcw= 0;
+     for (qi=0; qi<qc; qi++) {
+       for (ti=0; ti<tc; ti++) {
+        mc= &mcs[qi*tc+ti];
+        if (mc->doneyet) continue;
+        assert(mc->found);
+        if (!mcw) mcw= mc;
+       }
+     }
+     if (!mcw) break;
+ 
+     if (strchr(owninitflags,'s')) {
+       qu= mcw->qu;
+       mc= mcw;
+     } else {
+       qu= 0;
+       mc= 0;
+     }
+ 
+     if (strchr(owninitflags,'p')) {
+       r= adns_wait_poll(ads,&qu,&ans,&mcr);
+     } else {
+       r= adns_wait(ads,&qu,&ans,&mcr);
+     }
+     if (r) failure_errno("wait/check",r);
+     
+     if (mc) assert(mcr==mc);
+     else mc= mcr;
+     assert(qu==mc->qu);
+     assert(!mc->doneyet);
+     
+     fdom_split(mc->fdom,&domain,&qflags,ownflags,sizeof(ownflags));
+ 
+     if (gettimeofday(&now,0)) { perror("gettimeofday"); quitnow(3); }
+       
+     ri= adns_rr_info(ans->type, &rrtn,&fmtn,&len, 0,0);
+     fprintf(stdout, "%s flags %d type ",domain,qflags);
+     dumptype(ri,rrtn,fmtn);
+     fprintf(stdout, "%s%s: %s; nrrs=%d; cname=%s; owner=%s; ttl=%ld\n",
+            ownflags[0] ? " ownflags=" : "", ownflags,
+            strchr(ownflags,'a')
+            ? adns_errabbrev(ans->status)
+            : adns_strerror(ans->status),
+            ans->nrrs,
+            ans->cname ? ans->cname : "$",
+            ans->owner ? ans->owner : "$",
+            (long)ans->expires - (long)now.tv_sec);
+     if (ans->nrrs) {
+       assert(!ri);
+       for (i=0; i<ans->nrrs; i++) {
+        ri= adns_rr_info(ans->type, 0,0,0, ans->rrs.bytes + i*len, &show);
+        if (ri) failure_status("info",ri);
+        fprintf(stdout," %s\n",show);
+        free(show);
+       }
+     }
+     free(ans);
+ 
+     mc->doneyet= 1;
+   }
+ 
+   quitnow(0);
+ }


ossp-pkg/adns/adns_transmit.c -> 1.1.1.4

*** /dev/null    Fri May  3 13:52:11 2024
--- -    Fri May  3 13:52:34 2024
***************
*** 0 ****
--- 1,259 ----
+ /*
+  * transmit.c
+  * - construct queries
+  * - send queries
+  */
+ /*
+  *  This file is
+  *    Copyright (C) 1997-2000 Ian Jackson <ian@davenant.greenend.org.uk>
+  *
+  *  It is part of adns, which is
+  *    Copyright (C) 1997-2000 Ian Jackson <ian@davenant.greenend.org.uk>
+  *    Copyright (C) 1999 Tony Finch <dot@dotat.at>
+  *  
+  *  This program is free software; you can redistribute it and/or modify
+  *  it under the terms of the GNU General Public License as published by
+  *  the Free Software Foundation; either version 2, or (at your option)
+  *  any later version.
+  *  
+  *  This program is distributed in the hope that it will be useful,
+  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  *  GNU General Public License for more details.
+  *  
+  *  You should have received a copy of the GNU General Public License
+  *  along with this program; if not, write to the Free Software Foundation,
+  *  Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 
+  */
+ 
+ #include <errno.h>
+ 
+ #include <sys/types.h>
+ #include <sys/uio.h>
+ 
+ #include "internal.h"
+ #include "tvarith.h"
+ 
+ #define MKQUERY_START(vb) (rqp= (vb)->buf+(vb)->used)
+ #define MKQUERY_ADDB(b) *rqp++= (b)
+ #define MKQUERY_ADDW(w) (MKQUERY_ADDB(((w)>>8)&0x0ff), MKQUERY_ADDB((w)&0x0ff))
+ #define MKQUERY_STOP(vb) ((vb)->used= rqp-(vb)->buf)
+ 
+ static adns_status mkquery_header(adns_state ads, vbuf *vb, int *id_r, int qdlen) {
+   int id;
+   byte *rqp;
+   
+   if (!adns__vbuf_ensure(vb,DNS_HDRSIZE+qdlen+4)) return adns_s_nomemory;
+ 
+   vb->used= 0;
+   MKQUERY_START(vb);
+   
+   *id_r= id= (ads->nextid++) & 0x0ffff;
+   MKQUERY_ADDW(id);
+   MKQUERY_ADDB(0x01); /* QR=Q(0), OPCODE=QUERY(0000), !AA, !TC, RD */
+   MKQUERY_ADDB(0x00); /* !RA, Z=000, RCODE=NOERROR(0000) */
+   MKQUERY_ADDW(1); /* QDCOUNT=1 */
+   MKQUERY_ADDW(0); /* ANCOUNT=0 */
+   MKQUERY_ADDW(0); /* NSCOUNT=0 */
+   MKQUERY_ADDW(0); /* ARCOUNT=0 */
+ 
+   MKQUERY_STOP(vb);
+   
+   return adns_s_ok;
+ }
+ 
+ static adns_status mkquery_footer(vbuf *vb, adns_rrtype type) {
+   byte *rqp;
+ 
+   MKQUERY_START(vb);
+   MKQUERY_ADDW(type & adns__rrt_typemask); /* QTYPE */
+   MKQUERY_ADDW(DNS_CLASS_IN); /* QCLASS=IN */
+   MKQUERY_STOP(vb);
+   assert(vb->used <= vb->avail);
+   
+   return adns_s_ok;
+ }
+ 
+ adns_status adns__mkquery(adns_state ads, vbuf *vb, int *id_r,
+                          const char *owner, int ol,
+                          const typeinfo *typei, adns_queryflags flags) {
+   int ll, c, nbytes;
+   byte label[255], *rqp;
+   const char *p, *pe;
+   adns_status st;
+ 
+   st= mkquery_header(ads,vb,id_r,ol+2); if (st) return st;
+   
+   MKQUERY_START(vb);
+ 
+   p= owner; pe= owner+ol;
+   nbytes= 0;
+   while (p!=pe) {
+     ll= 0;
+     while (p!=pe && (c= *p++)!='.') {
+       if (c=='\\') {
+        if (!(flags & adns_qf_quoteok_query)) return adns_s_querydomaininvalid;
+        if (ctype_digit(p[0])) {
+          if (ctype_digit(p[1]) && ctype_digit(p[2])) {
+            c= (*p++ - '0')*100 + (*p++ - '0')*10 + (*p++ - '0');
+            if (c >= 256) return adns_s_querydomaininvalid;
+          } else {
+            return adns_s_querydomaininvalid;
+          }
+        } else if (!(c= *p++)) {
+          return adns_s_querydomaininvalid;
+        }
+       }
+       if (!(flags & adns_qf_quoteok_query)) {
+        if (c == '-') {
+          if (!ll) return adns_s_querydomaininvalid;
+        } else if (!ctype_alpha(c) && !ctype_digit(c)) {
+          return adns_s_querydomaininvalid;
+        }
+       }
+       if (ll == sizeof(label)) return adns_s_querydomaininvalid;
+       label[ll++]= c;
+     }
+     if (!ll) return adns_s_querydomaininvalid;
+     if (ll > DNS_MAXLABEL) return adns_s_querydomaintoolong;
+     nbytes+= ll+1;
+     if (nbytes >= DNS_MAXDOMAIN) return adns_s_querydomaintoolong;
+     MKQUERY_ADDB(ll);
+     memcpy(rqp,label,ll); rqp+= ll;
+   }
+   MKQUERY_ADDB(0);
+ 
+   MKQUERY_STOP(vb);
+   
+   st= mkquery_footer(vb,typei->type);
+   
+   return adns_s_ok;
+ }
+ 
+ adns_status adns__mkquery_frdgram(adns_state ads, vbuf *vb, int *id_r,
+                                  const byte *qd_dgram, int qd_dglen, int qd_begin,
+                                  adns_rrtype type, adns_queryflags flags) {
+   byte *rqp;
+   findlabel_state fls;
+   int lablen, labstart;
+   adns_status st;
+ 
+   st= mkquery_header(ads,vb,id_r,qd_dglen); if (st) return st;
+ 
+   MKQUERY_START(vb);
+ 
+   adns__findlabel_start(&fls,ads,-1,0,qd_dgram,qd_dglen,qd_dglen,qd_begin,0);
+   for (;;) {
+     st= adns__findlabel_next(&fls,&lablen,&labstart); assert(!st);
+     if (!lablen) break;
+     assert(lablen<255);
+     MKQUERY_ADDB(lablen);
+     memcpy(rqp,qd_dgram+labstart,lablen);
+     rqp+= lablen;
+   }
+   MKQUERY_ADDB(0);
+ 
+   MKQUERY_STOP(vb);
+   
+   st= mkquery_footer(vb,type);
+   
+   return adns_s_ok;
+ }
+ 
+ void adns__querysend_tcp(adns_query qu, struct timeval now) {
+   byte length[2];
+   struct iovec iov[2];
+   int wr, r;
+   adns_state ads;
+ 
+   if (qu->ads->tcpstate != server_ok) return;
+ 
+   assert(qu->state == query_tcpw);
+ 
+   length[0]= (qu->query_dglen&0x0ff00U) >>8;
+   length[1]= (qu->query_dglen&0x0ff);
+ 
+   ads= qu->ads;
+   if (!adns__vbuf_ensure(&ads->tcpsend,ads->tcpsend.used+qu->query_dglen+2)) return;
+ 
+   qu->retries++;
+ 
+   /* Reset idle timeout. */
+   ads->tcptimeout.tv_sec= ads->tcptimeout.tv_usec= 0;
+ 
+   if (ads->tcpsend.used) {
+     wr= 0;
+   } else {
+     iov[0].iov_base= length;
+     iov[0].iov_len= 2;
+     iov[1].iov_base= qu->query_dgram;
+     iov[1].iov_len= qu->query_dglen;
+     adns__sigpipe_protect(qu->ads);
+     wr= writev(qu->ads->tcpsocket,iov,2);
+     adns__sigpipe_unprotect(qu->ads);
+     if (wr < 0) {
+       if (!(errno == EAGAIN || errno == EINTR || errno == ENOSPC ||
+            errno == ENOBUFS || errno == ENOMEM)) {
+        adns__tcp_broken(ads,"write",strerror(errno));
+        return;
+       }
+       wr= 0;
+     }
+   }
+ 
+   if (wr<2) {
+     r= adns__vbuf_append(&ads->tcpsend,length,2-wr); assert(r);
+     wr= 0;
+   } else {
+     wr-= 2;
+   }
+   if (wr<qu->query_dglen) {
+     r= adns__vbuf_append(&ads->tcpsend,qu->query_dgram+wr,qu->query_dglen-wr); assert(r);
+   }
+ }
+ 
+ static void query_usetcp(adns_query qu, struct timeval now) {
+   qu->state= query_tcpw;
+   qu->timeout= now;
+   timevaladd(&qu->timeout,TCPWAITMS);
+   LIST_LINK_TAIL(qu->ads->tcpw,qu);
+   adns__querysend_tcp(qu,now);
+   adns__tcp_tryconnect(qu->ads,now);
+ }
+ 
+ void adns__query_send(adns_query qu, struct timeval now) {
+   struct sockaddr_in servaddr;
+   int serv, r;
+   adns_state ads;
+ 
+   assert(qu->state == query_tosend);
+   if ((qu->flags & adns_qf_usevc) || (qu->query_dglen > DNS_MAXUDP)) {
+     query_usetcp(qu,now);
+     return;
+   }
+ 
+   if (qu->retries >= UDPMAXRETRIES) {
+     adns__query_fail(qu,adns_s_timeout);
+     return;
+   }
+ 
+   serv= qu->udpnextserver;
+   memset(&servaddr,0,sizeof(servaddr));
+ 
+   ads= qu->ads;
+   servaddr.sin_family= AF_INET;
+   servaddr.sin_addr= ads->servers[serv].addr;
+   servaddr.sin_port= htons(DNS_PORT);
+   
+   r= sendto(ads->udpsocket,qu->query_dgram,qu->query_dglen,0,
+            (const struct sockaddr*)&servaddr,sizeof(servaddr));
+   if (r<0 && errno == EMSGSIZE) { qu->retries= 0; query_usetcp(qu,now); return; }
+   if (r<0 && errno != EAGAIN) adns__warn(ads,serv,0,"sendto failed: %s",strerror(errno));
+   
+   qu->timeout= now;
+   timevaladd(&qu->timeout,UDPRETRYMS);
+   qu->udpsent |= (1<<serv);
+   qu->udpnextserver= (serv+1)%ads->nservers;
+   qu->retries++;
+   LIST_LINK_TAIL(ads->udpw,qu);
+ }


ossp-pkg/adns/configure.in -> 1.1.1.3

*** /dev/null    Fri May  3 13:52:11 2024
--- -    Fri May  3 13:52:34 2024
***************
*** 0 ****
--- 1,125 ----
+ # configure.in - input to autoconf
+ #  
+ #  This file is
+ #    Copyright (C) 1997-2000 Ian Jackson <ian@davenant.greenend.org.uk>
+ #
+ #  It is part of adns, which is
+ #    Copyright (C) 1997-2000 Ian Jackson <ian@davenant.greenend.org.uk>
+ #    Copyright (C) 1999 Tony Finch <dot@dotat.at>
+ #  
+ #  This program is free software; you can redistribute it and/or modify
+ #  it under the terms of the GNU General Public License as published by
+ #  the Free Software Foundation; either version 2, or (at your option)
+ #  any later version.
+ #  
+ #  This program is distributed in the hope that it will be useful,
+ #  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ #  GNU General Public License for more details.
+ #  
+ #  You should have received a copy of the GNU General Public License
+ #  along with this program; if not, write to the Free Software Foundation,
+ #  Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 
+ 
+ AC_INIT(src/adns.h)
+ AC_CONFIG_HEADER(src/config.h)
+ 
+ AC_MSG_CHECKING(whether you requested dynamic linking)
+ AC_SUBST(ENABLE_DYNAMIC)
+ AC_ARG_ENABLE(dynamic,
+ [  --disable-dynamic       use static linking
+   --enable-dynamic[=elf]  create and use ELF dynamic library (default)],
+ [      case "$enableval" in
+        elf|yes)
+                ENABLE_DYNAMIC=elf
+                AC_MSG_RESULT([yes (ELF)])
+                ;;
+        no)     ENABLE_DYNAMIC=no
+                AC_MSG_RESULT(no)
+                ;;
+        *)      AC_MSG_ERROR(
+ ["invalid value $enableval for --enable-dynamic, try yes or elf"])
+                ;;
+        esac
+ ],[
+                ENABLE_DYNAMIC=yes
+                AC_MSG_RESULT([yes, by default])
+ ])
+ 
+ AC_PROG_CC
+ AC_PROG_CPP
+ AC_PROG_RANLIB
+ AC_PROG_INSTALL
+ 
+ AC_CHECK_FUNCS(poll)
+ ADNS_C_GETFUNC(socket,socket)
+ ADNS_C_GETFUNC(inet_ntoa,nsl)
+ 
+ PROGS_IF_TSEARCH=adnsresfilter
+ AC_SUBST(PROGS_HAVE_TSEARCH)
+ AC_CHECK_FUNC(tsearch,[
+  PROGS_HAVE_TSEARCH=$PROGS_IF_TSEARCH
+ ],[
+  PROGS_HAVE_TSEARCH='';
+  AC_MSG_WARN([tsearch missing - not building client program(s) $PROGS_IF_TSEARCH])
+ ])
+ 
+ AC_MSG_CHECKING(for INADDR_LOOPBACK)
+ AC_CACHE_VAL(adns_cv_decl_inaddrloopback,[
+  AC_TRY_COMPILE([
+ #include <sys/socket.h>
+ #include <netinet/in.h>
+ #include <arpa/inet.h>
+  ],[
+   INADDR_LOOPBACK;
+  ],
+  adns_cv_decl_inaddrloopback=yes,
+  adns_cv_decl_inaddrloopback=no)])
+ if test "$adns_cv_decl_inaddrloopback" = yes; then
+  AC_MSG_RESULT(found)
+ else
+  AC_MSG_RESULT([not in standard headers, urgh...])
+  AC_CHECK_HEADER(rpc/types.h,[
+   AC_DEFINE(HAVEUSE_RPCTYPES_H)
+  ],[
+   AC_MSG_ERROR([cannot find INADDR_LOOPBACK or rpc/types.h])
+  ])
+ fi
+ 
+ ADNS_C_GETFUNC(inet_aton,resolv,[
+  LIBS="-lresolv $LIBS";
+  AC_MSG_WARN([inet_aton is in libresolv, urgh.  Must use -lresolv.])
+ ])
+ 
+ ADNS_C_GCCATTRIB
+ 
+ AC_SUBST(WARNS)
+ 
+ if test "${GCC-no}" = yes; then
+        WARNS="-Wall -Wmissing-prototypes -Wwrite-strings -Wstrict-prototypes -Wcast-qual -Wpointer-arith"
+ else
+        WARNS=
+ fi
+ 
+ AC_SUBST(SHLIBCC)
+ AC_SUBST(MKSHLIB_1)
+ AC_SUBST(MKSHLIB_2)
+ AC_SUBST(MKSHLIB_3)
+ 
+ AC_SUBST(SHLIBFORLINK)
+ AC_SUBST(SHLIBFILE)
+ AC_SUBST(SHLIBSONAME)
+ 
+ SHLIBFORLINK='libadns.so'
+ SHLIBSONAME='$(SHLIBFORLINK).$(MAJOR)'
+ SHLIBFILE='$(SHLIBSONAME).$(MINOR)'
+ 
+ SHLIBCC='$(CC) $(CFLAGS) -fpic'
+ MKSHLIB_1='$(CC) $(LDFLAGS) -shared -Wl,-soname=$(SHLIBSONAME) -o'
+ MKSHLIB_2=''
+ MKSHLIB_3='-lc'
+ 
+ AC_OUTPUT(
+        settings.make Makefile
+        src/Makefile client/Makefile dynamic/Makefile regress/Makefile
+ )

CVSTrac 2.0.1