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