Author: Kev <klmitch@mit.edu>
[ircu2.10.12-pk.git] / libs / adns / src / event.c
1 /*
2  * event.c
3  * - event loop core
4  * - TCP connection management
5  * - user-visible check/wait and event-loop-related functions
6  */
7 /*
8  *  This file is
9  *    Copyright (C) 1997-2000 Ian Jackson <ian@davenant.greenend.org.uk>
10  *
11  *  It is part of adns, which is
12  *    Copyright (C) 1997-2000 Ian Jackson <ian@davenant.greenend.org.uk>
13  *    Copyright (C) 1999-2000 Tony Finch <dot@dotat.at>
14  *  
15  *  This program is free software; you can redistribute it and/or modify
16  *  it under the terms of the GNU General Public License as published by
17  *  the Free Software Foundation; either version 2, or (at your option)
18  *  any later version.
19  *  
20  *  This program is distributed in the hope that it will be useful,
21  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
22  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23  *  GNU General Public License for more details.
24  *  
25  *  You should have received a copy of the GNU General Public License
26  *  along with this program; if not, write to the Free Software Foundation,
27  *  Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 
28  */
29
30 #include <errno.h>
31 #include <stdlib.h>
32 #include <unistd.h>
33
34 #include <sys/types.h>
35 #include <sys/time.h>
36 #include <netdb.h>
37 #include <sys/socket.h>
38 #include <netinet/in.h>
39 #include <arpa/inet.h>
40
41 #include "internal.h"
42 #include "tvarith.h"
43
44 /* TCP connection management. */
45
46 static void tcp_close(adns_state ads) {
47   int serv;
48   
49   serv= ads->tcpserver;
50   close(ads->tcpsocket);
51   ads->tcpsocket= -1;
52   ads->tcprecv.used= ads->tcprecv_skip= ads->tcpsend.used= 0;
53 }
54
55 void adns__tcp_broken(adns_state ads, const char *what, const char *why) {
56   int serv;
57   adns_query qu;
58   
59   assert(ads->tcpstate == server_connecting || ads->tcpstate == server_ok);
60   serv= ads->tcpserver;
61   if (what) adns__warn(ads,serv,0,"TCP connection failed: %s: %s",what,why);
62
63   if (ads->tcpstate == server_connecting) {
64     /* Counts as a retry for all the queries waiting for TCP. */
65     for (qu= ads->tcpw.head; qu; qu= qu->next)
66       qu->retries++;
67   }
68
69   tcp_close(ads);
70   ads->tcpstate= server_broken;
71   ads->tcpserver= (serv+1)%ads->nservers;
72 }
73
74 static void tcp_connected(adns_state ads, struct timeval now) {
75   adns_query qu, nqu;
76   
77   adns__debug(ads,ads->tcpserver,0,"TCP connected");
78   ads->tcpstate= server_ok;
79   for (qu= ads->tcpw.head; qu && ads->tcpstate == server_ok; qu= nqu) {
80     nqu= qu->next;
81     assert(qu->state == query_tcpw);
82     adns__querysend_tcp(qu,now);
83   }
84 }
85
86 void adns__tcp_tryconnect(adns_state ads, struct timeval now) {
87   int r, fd, tries;
88   struct sockaddr_in addr;
89   struct protoent *proto;
90
91   for (tries=0; tries<ads->nservers; tries++) {
92     switch (ads->tcpstate) {
93     case server_connecting:
94     case server_ok:
95     case server_broken:
96       return;
97     case server_disconnected:
98       break;
99     default:
100       abort();
101     }
102     
103     assert(!ads->tcpsend.used);
104     assert(!ads->tcprecv.used);
105     assert(!ads->tcprecv_skip);
106
107     proto= getprotobyname("tcp");
108     if (!proto) { adns__diag(ads,-1,0,"unable to find protocol no. for TCP !"); return; }
109 #if 0
110     fd= socket(AF_INET,SOCK_STREAM,proto->p_proto);
111 #else
112     fd = -1;
113     errno = EPERM;
114 #endif
115     if (fd<0) {
116       adns__diag(ads,-1,0,"cannot create TCP socket: %s",strerror(errno));
117       return;
118     }
119     r= adns__setnonblock(ads,fd);
120     if (r) {
121       adns__diag(ads,-1,0,"cannot make TCP socket nonblocking: %s",strerror(r));
122       close(fd);
123       return;
124     }
125     memset(&addr,0,sizeof(addr));
126     addr.sin_family= AF_INET;
127     addr.sin_port= htons(DNS_PORT);
128     addr.sin_addr= ads->servers[ads->tcpserver].addr;
129     r= connect(fd,(const struct sockaddr*)&addr,sizeof(addr));
130     ads->tcpsocket= fd;
131     ads->tcpstate= server_connecting;
132     if (r==0) { tcp_connected(ads,now); return; }
133     if (errno == EWOULDBLOCK || errno == EINPROGRESS) {
134       ads->tcptimeout= now;
135       timevaladd(&ads->tcptimeout,TCPCONNMS);
136       return;
137     }
138     adns__tcp_broken(ads,"connect",strerror(errno));
139     ads->tcpstate= server_disconnected;
140   }
141 }
142
143 /* Timeout handling functions. */
144
145 void adns__must_gettimeofday(adns_state ads, const struct timeval **now_io,
146                              struct timeval *tv_buf) {
147   const struct timeval *now;
148   int r;
149
150   now= *now_io;
151   if (now) return;
152   r= gettimeofday(tv_buf,0); if (!r) { *now_io= tv_buf; return; }
153   adns__diag(ads,-1,0,"gettimeofday failed: %s",strerror(errno));
154   adns_globalsystemfailure(ads);
155   return;
156 }
157
158 static void inter_immed(struct timeval **tv_io, struct timeval *tvbuf) {
159   struct timeval *rbuf;
160
161   if (!tv_io) return;
162
163   rbuf= *tv_io;
164   if (!rbuf) { *tv_io= rbuf= tvbuf; }
165
166   timerclear(rbuf);
167 }
168     
169 static void inter_maxto(struct timeval **tv_io, struct timeval *tvbuf,
170                         struct timeval maxto) {
171   struct timeval *rbuf;
172
173   if (!tv_io) return;
174   rbuf= *tv_io;
175   if (!rbuf) {
176     *tvbuf= maxto; *tv_io= tvbuf;
177   } else {
178     if (timercmp(rbuf,&maxto,>)) *rbuf= maxto;
179   }
180 /*fprintf(stderr,"inter_maxto maxto=%ld.%06ld result=%ld.%06ld\n",
181         maxto.tv_sec,maxto.tv_usec,(**tv_io).tv_sec,(**tv_io).tv_usec);*/
182 }
183
184 static void inter_maxtoabs(struct timeval **tv_io, struct timeval *tvbuf,
185                            struct timeval now, struct timeval maxtime) {
186   /* tv_io may be 0 */
187   ldiv_t dr;
188
189 /*fprintf(stderr,"inter_maxtoabs now=%ld.%06ld maxtime=%ld.%06ld\n",
190         now.tv_sec,now.tv_usec,maxtime.tv_sec,maxtime.tv_usec);*/
191   if (!tv_io) return;
192   maxtime.tv_sec -= (now.tv_sec+2);
193   maxtime.tv_usec -= (now.tv_usec-2000000);
194   dr= ldiv(maxtime.tv_usec,1000000);
195   maxtime.tv_sec += dr.quot;
196   maxtime.tv_usec -= dr.quot*1000000;
197   if (maxtime.tv_sec<0) timerclear(&maxtime);
198   inter_maxto(tv_io,tvbuf,maxtime);
199 }
200
201 static void timeouts_queue(adns_state ads, int act,
202                            struct timeval **tv_io, struct timeval *tvbuf,
203                            struct timeval now, struct query_queue *queue) {
204   adns_query qu, nqu;
205   
206   for (qu= queue->head; qu; qu= nqu) {
207     nqu= qu->next;
208     if (!timercmp(&now,&qu->timeout,>)) {
209       inter_maxtoabs(tv_io,tvbuf,now,qu->timeout);
210     } else {
211       if (!act) { inter_immed(tv_io,tvbuf); return; }
212       LIST_UNLINK(*queue,qu);
213       if (qu->state != query_tosend) {
214         adns__query_fail(qu,adns_s_timeout);
215       } else {
216         adns__query_send(qu,now);
217       }
218       nqu= queue->head;
219     }
220   }
221 }
222
223 static void tcp_events(adns_state ads, int act,
224                        struct timeval **tv_io, struct timeval *tvbuf,
225                        struct timeval now) {
226   adns_query qu, nqu;
227   
228   for (;;) {
229     switch (ads->tcpstate) {
230     case server_broken:
231       if (!act) { inter_immed(tv_io,tvbuf); return; }
232       for (qu= ads->tcpw.head; qu; qu= nqu) {
233         nqu= qu->next;
234         assert(qu->state == query_tcpw);
235         if (qu->retries > ads->nservers) {
236           LIST_UNLINK(ads->tcpw,qu);
237           adns__query_fail(qu,adns_s_allservfail);
238         }
239       }
240       ads->tcpstate= server_disconnected;
241     case server_disconnected: /* fall through */
242       if (!ads->tcpw.head) return;
243       if (!act) { inter_immed(tv_io,tvbuf); return; }
244       adns__tcp_tryconnect(ads,now);
245       break;
246     case server_ok:
247       if (ads->tcpw.head) return;
248       if (!ads->tcptimeout.tv_sec) {
249         assert(!ads->tcptimeout.tv_usec);
250         ads->tcptimeout= now;
251         timevaladd(&ads->tcptimeout,TCPIDLEMS);
252       }
253     case server_connecting: /* fall through */
254       if (!act || !timercmp(&now,&ads->tcptimeout,>)) {
255         inter_maxtoabs(tv_io,tvbuf,now,ads->tcptimeout);
256         return;
257       } {
258         /* TCP timeout has happened */
259         switch (ads->tcpstate) {
260         case server_connecting: /* failed to connect */
261           adns__tcp_broken(ads,"unable to make connection","timed out");
262           break;
263         case server_ok: /* idle timeout */
264           tcp_close(ads);
265           ads->tcpstate= server_disconnected;
266           return;
267         default:
268           abort();
269         }
270       }
271       break;
272     default:
273       abort();
274     }
275   }
276   return;
277 }
278
279 void adns__timeouts(adns_state ads, int act,
280                     struct timeval **tv_io, struct timeval *tvbuf,
281                     struct timeval now) {
282   timeouts_queue(ads,act,tv_io,tvbuf,now, &ads->udpw);
283   timeouts_queue(ads,act,tv_io,tvbuf,now, &ads->tcpw);
284   tcp_events(ads,act,tv_io,tvbuf,now);
285 }
286
287 void adns_firsttimeout(adns_state ads,
288                        struct timeval **tv_io, struct timeval *tvbuf,
289                        struct timeval now) {
290   adns__consistency(ads,0,cc_entex);
291   adns__timeouts(ads, 0, tv_io,tvbuf, now);
292   adns__consistency(ads,0,cc_entex);
293 }
294
295 void adns_processtimeouts(adns_state ads, const struct timeval *now) {
296   struct timeval tv_buf;
297
298   adns__consistency(ads,0,cc_entex);
299   adns__must_gettimeofday(ads,&now,&tv_buf);
300   if (now) adns__timeouts(ads, 1, 0,0, *now);
301   adns__consistency(ads,0,cc_entex);
302 }
303
304 /* fd handling functions.  These are the top-level of the real work of
305  * reception and often transmission.
306  */
307
308 int adns__pollfds(adns_state ads, struct pollfd pollfds_buf[MAX_POLLFDS]) {
309   /* Returns the number of entries filled in.  Always zeroes revents. */
310
311   assert(MAX_POLLFDS==2);
312
313   pollfds_buf[0].fd= ads->udpsocket;
314   pollfds_buf[0].events= POLLIN;
315   pollfds_buf[0].revents= 0;
316
317   switch (ads->tcpstate) {
318   case server_disconnected:
319   case server_broken:
320     return 1;
321   case server_connecting:
322     pollfds_buf[1].events= POLLOUT;
323     break;
324   case server_ok:
325     pollfds_buf[1].events= ads->tcpsend.used ? POLLIN|POLLOUT|POLLPRI : POLLIN|POLLPRI;
326     break;
327   default:
328     abort();
329   }
330   pollfds_buf[1].fd= ads->tcpsocket;
331   return 2;
332 }
333
334 int adns_get_fd(adns_state ads)
335 {
336   return ads->udpsocket;
337 }
338
339 int adns_processreadable(adns_state ads, int fd, const struct timeval *now) {
340   int want, dgramlen, r, udpaddrlen, serv, old_skip;
341   byte udpbuf[DNS_MAXUDP];
342   struct sockaddr_in udpaddr;
343   
344   adns__consistency(ads,0,cc_entex);
345
346   switch (ads->tcpstate) {
347   case server_disconnected:
348   case server_broken:
349   case server_connecting:
350     break;
351   case server_ok:
352     if (fd != ads->tcpsocket) break;
353     assert(!ads->tcprecv_skip);
354     do {
355       if (ads->tcprecv.used >= ads->tcprecv_skip+2) {
356         dgramlen= ((ads->tcprecv.buf[ads->tcprecv_skip]<<8) |
357                    ads->tcprecv.buf[ads->tcprecv_skip+1]);
358         if (ads->tcprecv.used >= ads->tcprecv_skip+2+dgramlen) {
359           old_skip= ads->tcprecv_skip;
360           ads->tcprecv_skip += 2+dgramlen;
361           adns__procdgram(ads, ads->tcprecv.buf+old_skip+2,
362                           dgramlen, ads->tcpserver, 1,*now);
363           continue;
364         } else {
365           want= 2+dgramlen;
366         }
367       } else {
368         want= 2;
369       }
370       ads->tcprecv.used -= ads->tcprecv_skip;
371       memmove(ads->tcprecv.buf,ads->tcprecv.buf+ads->tcprecv_skip,ads->tcprecv.used);
372       ads->tcprecv_skip= 0;
373       if (!adns__vbuf_ensure(&ads->tcprecv,want)) { r= ENOMEM; goto xit; }
374       assert(ads->tcprecv.used <= ads->tcprecv.avail);
375       if (ads->tcprecv.used == ads->tcprecv.avail) continue;
376       r= read(ads->tcpsocket,
377               ads->tcprecv.buf+ads->tcprecv.used,
378               ads->tcprecv.avail-ads->tcprecv.used);
379       if (r>0) {
380         ads->tcprecv.used+= r;
381       } else {
382         if (r) {
383           if (errno==EAGAIN || errno==EWOULDBLOCK) { r= 0; goto xit; }
384           if (errno==EINTR) continue;
385           if (errno_resources(errno)) { r= errno; goto xit; }
386         }
387         adns__tcp_broken(ads,"read",r?strerror(errno):"closed");
388       }
389     } while (ads->tcpstate == server_ok);
390     r= 0; goto xit;
391   default:
392     abort();
393   }
394   if (fd == ads->udpsocket) {
395     for (;;) {
396       udpaddrlen= sizeof(udpaddr);
397       r= recvfrom(ads->udpsocket,udpbuf,sizeof(udpbuf),0,
398                   (struct sockaddr*)&udpaddr,&udpaddrlen);
399       if (r<0) {
400         if (errno == EAGAIN || errno == EWOULDBLOCK) { r= 0; goto xit; }
401         if (errno == EINTR) continue;
402         if (errno_resources(errno)) { r= errno; goto xit; }
403         adns__warn(ads,-1,0,"datagram receive error: %s",strerror(errno));
404         r= 0; goto xit;
405       }
406       if (udpaddrlen != sizeof(udpaddr)) {
407         adns__diag(ads,-1,0,"datagram received with wrong address length %d"
408                    " (expected %lu)", udpaddrlen,
409                    (unsigned long)sizeof(udpaddr));
410         continue;
411       }
412       if (udpaddr.sin_family != AF_INET) {
413         adns__diag(ads,-1,0,"datagram received with wrong protocol family"
414                    " %u (expected %u)",udpaddr.sin_family,AF_INET);
415         continue;
416       }
417       if (ntohs(udpaddr.sin_port) != DNS_PORT) {
418         adns__diag(ads,-1,0,"datagram received from wrong port %u (expected %u)",
419                    ntohs(udpaddr.sin_port),DNS_PORT);
420         continue;
421       }
422       for (serv= 0;
423            serv < ads->nservers &&
424              ads->servers[serv].addr.s_addr != udpaddr.sin_addr.s_addr;
425            serv++);
426       if (serv >= ads->nservers) {
427         adns__warn(ads,-1,0,"datagram received from unknown nameserver %s",
428                    inet_ntoa(udpaddr.sin_addr));
429         continue;
430       }
431       adns__procdgram(ads,udpbuf,r,serv,0,*now);
432     }
433   }
434   r= 0;
435 xit:
436   adns__consistency(ads,0,cc_entex);
437   return r;
438 }
439
440 int adns_processwriteable(adns_state ads, int fd, const struct timeval *now) {
441   int r;
442   
443   adns__consistency(ads,0,cc_entex);
444
445   switch (ads->tcpstate) {
446   case server_disconnected:
447   case server_broken:
448     break;
449   case server_connecting:
450     if (fd != ads->tcpsocket) break;
451     assert(ads->tcprecv.used==0);
452     assert(ads->tcprecv_skip==0);
453     for (;;) {
454       if (!adns__vbuf_ensure(&ads->tcprecv,1)) { r= ENOMEM; goto xit; }
455       r= read(ads->tcpsocket,&ads->tcprecv.buf,1);
456       if (r==0 || (r<0 && (errno==EAGAIN || errno==EWOULDBLOCK))) {
457         tcp_connected(ads,*now);
458         r= 0; goto xit;
459       }
460       if (r>0) {
461         adns__tcp_broken(ads,"connect/read","sent data before first request");
462         r= 0; goto xit;
463       }
464       if (errno==EINTR) continue;
465       if (errno_resources(errno)) { r= errno; goto xit; }
466       adns__tcp_broken(ads,"connect/read",strerror(errno));
467       r= 0; goto xit;
468     } /* not reached */
469   case server_ok:
470     if (fd != ads->tcpsocket) break;
471     while (ads->tcpsend.used) {
472       adns__sigpipe_protect(ads);
473       r= write(ads->tcpsocket,ads->tcpsend.buf,ads->tcpsend.used);
474       adns__sigpipe_unprotect(ads);
475       if (r<0) {
476         if (errno==EINTR) continue;
477         if (errno==EAGAIN || errno==EWOULDBLOCK) { r= 0; goto xit; }
478         if (errno_resources(errno)) { r= errno; goto xit; }
479         adns__tcp_broken(ads,"write",strerror(errno));
480         r= 0; goto xit;
481       } else if (r>0) {
482         ads->tcpsend.used -= r;
483         memmove(ads->tcpsend.buf,ads->tcpsend.buf+r,ads->tcpsend.used);
484       }
485     }
486     r= 0;
487     goto xit;
488   default:
489     abort();
490   }
491   r= 0;
492 xit:
493   adns__consistency(ads,0,cc_entex);
494   return r;
495 }
496   
497 int adns_processexceptional(adns_state ads, int fd, const struct timeval *now) {
498   adns__consistency(ads,0,cc_entex);
499   switch (ads->tcpstate) {
500   case server_disconnected:
501   case server_broken:
502     break;
503   case server_connecting:
504   case server_ok:
505     if (fd != ads->tcpsocket) break;
506     adns__tcp_broken(ads,"poll/select","exceptional condition detected");
507     break;
508   default:
509     abort();
510   }
511   adns__consistency(ads,0,cc_entex);
512   return 0;
513 }
514
515 static void fd_event(adns_state ads, int fd,
516                      int revent, int pollflag,
517                      int maxfd, const fd_set *fds,
518                      int (*func)(adns_state, int fd, const struct timeval *now),
519                      struct timeval now, int *r_r) {
520   int r;
521   
522   if (!(revent & pollflag)) return;
523   if (fds && !(fd<maxfd && FD_ISSET(fd,fds))) return;
524   r= func(ads,fd,&now);
525   if (r) {
526     if (r_r) {
527       *r_r= r;
528     } else {
529       adns__diag(ads,-1,0,"process fd failed after select: %s",strerror(errno));
530       adns_globalsystemfailure(ads);
531     }
532   }
533 }
534
535 void adns__fdevents(adns_state ads,
536                     const struct pollfd *pollfds, int npollfds,
537                     int maxfd, const fd_set *readfds,
538                     const fd_set *writefds, const fd_set *exceptfds,
539                     struct timeval now, int *r_r) {
540   int i, fd, revents;
541
542   for (i=0; i<npollfds; i++) {
543     fd= pollfds[i].fd;
544     if (fd >= maxfd) maxfd= fd+1;
545     revents= pollfds[i].revents;
546     fd_event(ads,fd, revents,POLLIN, maxfd,readfds, adns_processreadable,now,r_r);
547     fd_event(ads,fd, revents,POLLOUT, maxfd,writefds, adns_processwriteable,now,r_r);
548     fd_event(ads,fd, revents,POLLPRI, maxfd,exceptfds, adns_processexceptional,now,r_r);
549   }
550 }
551
552 /* Wrappers for select(2). */
553
554 void adns_beforeselect(adns_state ads, int *maxfd_io, fd_set *readfds_io,
555                        fd_set *writefds_io, fd_set *exceptfds_io,
556                        struct timeval **tv_mod, struct timeval *tv_tobuf,
557                        const struct timeval *now) {
558   struct timeval tv_nowbuf;
559   struct pollfd pollfds[MAX_POLLFDS];
560   int i, fd, maxfd, npollfds;
561   
562   adns__consistency(ads,0,cc_entex);
563
564   if (tv_mod && (!*tv_mod || (*tv_mod)->tv_sec || (*tv_mod)->tv_usec)) {
565     /* The caller is planning to sleep. */
566     adns__must_gettimeofday(ads,&now,&tv_nowbuf);
567     if (!now) { inter_immed(tv_mod,tv_tobuf); goto xit; }
568     adns__timeouts(ads, 0, tv_mod,tv_tobuf, *now);
569   }
570
571   npollfds= adns__pollfds(ads,pollfds);
572   maxfd= *maxfd_io;
573   for (i=0; i<npollfds; i++) {
574     fd= pollfds[i].fd;
575     if (fd >= maxfd) maxfd= fd+1;
576     if (pollfds[i].events & POLLIN) FD_SET(fd,readfds_io);
577     if (pollfds[i].events & POLLOUT) FD_SET(fd,writefds_io);
578     if (pollfds[i].events & POLLPRI) FD_SET(fd,exceptfds_io);
579   }
580   *maxfd_io= maxfd;
581
582 xit:
583   adns__consistency(ads,0,cc_entex);
584 }
585
586 void adns_afterselect(adns_state ads, int maxfd, const fd_set *readfds,
587                       const fd_set *writefds, const fd_set *exceptfds,
588                       const struct timeval *now) {
589   struct timeval tv_buf;
590   struct pollfd pollfds[MAX_POLLFDS];
591   int npollfds, i;
592
593   adns__consistency(ads,0,cc_entex);
594   adns__must_gettimeofday(ads,&now,&tv_buf);
595   if (!now) goto xit;
596   adns_processtimeouts(ads,now);
597
598   npollfds= adns__pollfds(ads,pollfds);
599   for (i=0; i<npollfds; i++) pollfds[i].revents= POLLIN|POLLOUT|POLLPRI;
600   adns__fdevents(ads,
601                  pollfds,npollfds,
602                  maxfd,readfds,writefds,exceptfds,
603                  *now, 0);
604 xit:
605   adns__consistency(ads,0,cc_entex);
606 }
607
608 /* General helpful functions. */
609
610 void adns_globalsystemfailure(adns_state ads) {
611   adns__consistency(ads,0,cc_entex);
612
613   while (ads->udpw.head) adns__query_fail(ads->udpw.head, adns_s_systemfail);
614   while (ads->tcpw.head) adns__query_fail(ads->tcpw.head, adns_s_systemfail);
615   
616   switch (ads->tcpstate) {
617   case server_connecting:
618   case server_ok:
619     adns__tcp_broken(ads,0,0);
620     break;
621   case server_disconnected:
622   case server_broken:
623     break;
624   default:
625     abort();
626   }
627   adns__consistency(ads,0,cc_entex);
628 }
629
630 int adns_processany(adns_state ads) {
631   int r, i;
632   struct timeval now;
633   struct pollfd pollfds[MAX_POLLFDS];
634   int npollfds;
635
636   adns__consistency(ads,0,cc_entex);
637
638   r= gettimeofday(&now,0);
639   if (!r) adns_processtimeouts(ads,&now);
640
641   /* We just use adns__fdevents to loop over the fd's trying them.
642    * This seems more sensible than calling select, since we're most
643    * likely just to want to do a read on one or two fds anyway.
644    */
645   npollfds= adns__pollfds(ads,pollfds);
646   for (i=0; i<npollfds; i++) pollfds[i].revents= pollfds[i].events & ~POLLPRI;
647   adns__fdevents(ads,
648                  pollfds,npollfds,
649                  0,0,0,0,
650                  now,&r);
651
652   adns__consistency(ads,0,cc_entex);
653   return 0;
654 }
655
656 void adns__autosys(adns_state ads, struct timeval now) {
657   if (ads->iflags & adns_if_noautosys) return;
658   adns_processany(ads);
659 }
660
661 int adns__internal_check(adns_state ads,
662                          adns_query *query_io,
663                          adns_answer **answer,
664                          void **context_r) {
665   adns_query qu;
666
667   qu= *query_io;
668   if (!qu) {
669     if (ads->output.head) {
670       qu= ads->output.head;
671     } else if (ads->udpw.head || ads->tcpw.head) {
672       return EAGAIN;
673     } else {
674       return ESRCH;
675     }
676   } else {
677     if (qu->id>=0) return EAGAIN;
678   }
679   LIST_UNLINK(ads->output,qu);
680   *answer= qu->answer;
681   if (context_r) *context_r= qu->ctx.ext;
682   *query_io= qu;
683   free(qu);
684   return 0;
685 }
686
687 int adns_wait(adns_state ads,
688               adns_query *query_io,
689               adns_answer **answer_r,
690               void **context_r) {
691   int r, maxfd, rsel;
692   fd_set readfds, writefds, exceptfds;
693   struct timeval tvbuf, *tvp;
694   
695   adns__consistency(ads,*query_io,cc_entex);
696   for (;;) {
697     r= adns__internal_check(ads,query_io,answer_r,context_r);
698     if (r != EAGAIN) break;
699     maxfd= 0; tvp= 0;
700     FD_ZERO(&readfds); FD_ZERO(&writefds); FD_ZERO(&exceptfds);
701     adns_beforeselect(ads,&maxfd,&readfds,&writefds,&exceptfds,&tvp,&tvbuf,0);
702     assert(tvp);
703     rsel= select(maxfd,&readfds,&writefds,&exceptfds,tvp);
704     if (rsel==-1) {
705       if (errno == EINTR) {
706         if (ads->iflags & adns_if_eintr) { r= EINTR; break; }
707       } else {
708         adns__diag(ads,-1,0,"select failed in wait: %s",strerror(errno));
709         adns_globalsystemfailure(ads);
710       }
711     } else {
712       assert(rsel >= 0);
713       adns_afterselect(ads,maxfd,&readfds,&writefds,&exceptfds,0);
714     }
715   }
716   adns__consistency(ads,0,cc_entex);
717   return r;
718 }
719
720 int adns_check(adns_state ads,
721                adns_query *query_io,
722                adns_answer **answer_r,
723                void **context_r) {
724   struct timeval now;
725   int r;
726   
727   adns__consistency(ads,*query_io,cc_entex);
728   r= gettimeofday(&now,0);
729   if (!r) adns__autosys(ads,now);
730
731   r= adns__internal_check(ads,query_io,answer_r,context_r);
732   adns__consistency(ads,0,cc_entex);
733   return r;
734 }