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