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