+ switch (ads->tcpstate) {
+ case server_disconnected:
+ break;
+ case server_connecting:
+ if (fd != ads->tcpsocket) break;
+ assert(ads->tcprecv.used==0);
+ assert(ads->tcprecv_skip==0);
+ for (;;) {
+ if (!adns__vbuf_ensure(&ads->tcprecv,1)) { r= ENOMEM; goto xit; }
+ r= read(ads->tcpsocket,&ads->tcprecv.buf,1);
+ if (r==0 || (r<0 && (errno==EAGAIN || errno==EWOULDBLOCK))) {
+ tcp_connected(ads,*now);
+ r= 0; goto xit;
+ }
+ if (r>0) {
+ adns__tcp_broken(ads,"connect/read","sent data before first request");
+ r= 0; goto xit;
+ }
+ if (errno==EINTR) continue;
+ if (errno_resources(errno)) { r= errno; goto xit; }
+ adns__tcp_broken(ads,"connect/read",strerror(errno));
+ r= 0; goto xit;
+ } /* not reached */
+ case server_ok:
+ if (!(ads->tcpsend.used && fd == ads->tcpsocket)) break;
+ for (;;) {
+ adns__sigpipe_protect(ads);
+ r= write(ads->tcpsocket,ads->tcpsend.buf,ads->tcpsend.used);
+ adns__sigpipe_unprotect(ads);
+ if (r<0) {
+ if (errno==EINTR) continue;
+ if (errno==EAGAIN || errno==EWOULDBLOCK) { r= 0; goto xit; }
+ if (errno_resources(errno)) { r= errno; goto xit; }
+ adns__tcp_broken(ads,"write",strerror(errno));
+ r= 0; goto xit;
+ } else if (r>0) {
+ ads->tcpsend.used -= r;
+ memmove(ads->tcpsend.buf,ads->tcpsend.buf+r,ads->tcpsend.used);
+ }
+ } /* not reached */
+ default:
+ abort();
+ }
+ r= 0;
+xit:
+ adns__consistency(ads,0,cc_entex);
+ return r;
+}
+
+int adns_processexceptional(adns_state ads, int fd, const struct timeval *now) {
+ adns__consistency(ads,0,cc_entex);
+ switch (ads->tcpstate) {
+ case server_disconnected:
+ break;
+ case server_connecting:
+ case server_ok:
+ if (fd != ads->tcpsocket) break;
+ adns__tcp_broken(ads,"poll/select","exceptional condition detected");
+ break;
+ default:
+ abort();
+ }
+ adns__consistency(ads,0,cc_entex);
+ return 0;
+}
+
+static void fd_event(adns_state ads, int fd,
+ int revent, int pollflag,
+ int maxfd, const fd_set *fds,
+ int (*func)(adns_state, int fd, const struct timeval *now),
+ struct timeval now, int *r_r) {
+ int r;
+
+ if (!(revent & pollflag)) return;
+ if (fds && !(fd<maxfd && FD_ISSET(fd,fds))) return;
+ r= func(ads,fd,&now);
+ if (r) {
+ if (r_r) {
+ *r_r= r;
+ } else {
+ adns__diag(ads,-1,0,"process fd failed after select: %s",strerror(errno));
+ adns_globalsystemfailure(ads);
+ }
+ }
+}
+
+void adns__fdevents(adns_state ads,
+ const struct pollfd *pollfds, int npollfds,
+ int maxfd, const fd_set *readfds,
+ const fd_set *writefds, const fd_set *exceptfds,
+ struct timeval now, int *r_r) {
+ int i, fd, revents;
+
+ for (i=0; i<npollfds; i++) {
+ fd= pollfds[i].fd;
+ if (fd >= maxfd) maxfd= fd+1;
+ revents= pollfds[i].revents;
+ fd_event(ads,fd, revents,POLLIN, maxfd,readfds, adns_processreadable,now,r_r);
+ fd_event(ads,fd, revents,POLLOUT, maxfd,writefds, adns_processwriteable,now,r_r);
+ fd_event(ads,fd, revents,POLLPRI, maxfd,exceptfds, adns_processexceptional,now,r_r);
+ }