chiark / gitweb /
Include <sys/times.h> in a few more files. Include <unistd.h> and
[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 (C) 1997-1999 Ian Jackson
9  *  
10  *  This program is free software; you can redistribute it and/or modify
11  *  it under the terms of the GNU General Public License as published by
12  *  the Free Software Foundation; either version 2, or (at your option)
13  *  any later version.
14  *  
15  *  This program is distributed in the hope that it will be useful,
16  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *  GNU General Public License for more details.
19  *  
20  *  You should have received a copy of the GNU General Public License
21  *  along with this program; if not, write to the Free Software Foundation,
22  *  Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 
23  */
24
25 #include <string.h>
26 #include <errno.h>
27 #include <stdlib.h>
28 #include <unistd.h>
29
30 #include <sys/types.h>
31 #include <sys/time.h>
32 #include <netdb.h>
33 #include <sys/socket.h>
34 #include <netinet/in.h>
35 #include <arpa/inet.h>
36
37 #include "internal.h"
38
39 /* TCP connection management */
40
41 void adns__tcp_broken(adns_state ads, const char *what, const char *why) {
42   int serv;
43   adns_query qu, nqu;
44   
45   assert(ads->tcpstate == server_connecting || ads->tcpstate == server_ok);
46   serv= ads->tcpserver;
47   adns__warn(ads,serv,0,"TCP connection lost: %s: %s",what,why);
48   close(ads->tcpsocket);
49   ads->tcpstate= server_disconnected;
50   
51   for (qu= ads->timew.head; qu; qu= nqu) {
52     nqu= qu->next;
53     if (qu->state == query_udp) continue;
54     assert(qu->state == query_tcpwait || qu->state == query_tcpsent);
55     qu->state= query_tcpwait;
56     qu->tcpfailed |= (1<<serv);
57     if (qu->tcpfailed == (1<<ads->nservers)-1) {
58       LIST_UNLINK(ads->timew,qu);
59       adns__query_fail(qu,adns_s_allservfail);
60     }
61   }
62
63   ads->tcprecv.used= ads->tcpsend.used= 0;
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->timew.head; qu; qu= nqu) {
73     nqu= qu->next;
74     if (qu->state == query_udp) continue;
75     assert (qu->state == query_tcpwait);
76     adns__query_tcp(qu,now);
77   }
78 }
79
80 void adns__tcp_tryconnect(adns_state ads, struct timeval now) {
81   int r, fd, tries;
82   struct sockaddr_in addr;
83   struct protoent *proto;
84
85   for (tries=0; tries<ads->nservers; tries++) {
86     if (ads->tcpstate == server_connecting || ads->tcpstate == server_ok) return;
87     assert(ads->tcpstate == server_disconnected);
88     assert(!ads->tcpsend.used);
89     assert(!ads->tcprecv.used);
90
91     proto= getprotobyname("tcp");
92     if (!proto) { adns__diag(ads,-1,0,"unable to find protocol no. for TCP !"); return; }
93     fd= socket(AF_INET,SOCK_STREAM,proto->p_proto);
94     if (fd<0) {
95       adns__diag(ads,-1,0,"cannot create TCP socket: %s",strerror(errno));
96       return;
97     }
98     r= adns__setnonblock(ads,fd);
99     if (r) {
100       adns__diag(ads,-1,0,"cannot make TCP socket nonblocking: %s",strerror(r));
101       close(fd);
102       return;
103     }
104     memset(&addr,0,sizeof(addr));
105     addr.sin_family= AF_INET;
106     addr.sin_port= htons(DNS_PORT);
107     addr.sin_addr= ads->servers[ads->tcpserver].addr;
108     r= connect(fd,(const struct sockaddr*)&addr,sizeof(addr));
109     ads->tcpsocket= fd;
110     ads->tcpstate= server_connecting;
111     if (r==0) { tcp_connected(ads,now); continue; }
112     if (errno == EWOULDBLOCK || errno == EINPROGRESS) return;
113     adns__tcp_broken(ads,"connect",strerror(errno));
114   }
115 }
116
117 /* `Interest' functions - find out which fd's we might be interested in,
118  * and when we want to be called back for a timeout.
119  */
120
121 static void inter_maxto(struct timeval **tv_io, struct timeval *tvbuf,
122                         struct timeval maxto) {
123   struct timeval *rbuf;
124
125   if (!tv_io) return;
126   rbuf= *tv_io;
127   if (!rbuf) {
128     *tvbuf= maxto; *tv_io= tvbuf;
129   } else {
130     if (timercmp(rbuf,&maxto,>)) *rbuf= maxto;
131   }
132 /*fprintf(stderr,"inter_maxto maxto=%ld.%06ld result=%ld.%06ld\n",
133         maxto.tv_sec,maxto.tv_usec,(**tv_io).tv_sec,(**tv_io).tv_usec);*/
134 }
135
136 static void inter_maxtoabs(struct timeval **tv_io, struct timeval *tvbuf,
137                            struct timeval now, struct timeval maxtime) {
138   ldiv_t dr;
139
140 /*fprintf(stderr,"inter_maxtoabs now=%ld.%06ld maxtime=%ld.%06ld\n",
141         now.tv_sec,now.tv_usec,maxtime.tv_sec,maxtime.tv_usec);*/
142   if (!tv_io) return;
143   maxtime.tv_sec -= (now.tv_sec+2);
144   maxtime.tv_usec -= (now.tv_usec-2000000);
145   dr= ldiv(maxtime.tv_usec,1000000);
146   maxtime.tv_sec += dr.quot;
147   maxtime.tv_usec -= dr.quot*1000000;
148   if (maxtime.tv_sec<0) timerclear(&maxtime);
149   inter_maxto(tv_io,tvbuf,maxtime);
150 }
151
152 static void inter_addfd(int *maxfd, fd_set *fds, int fd) {
153   if (!maxfd || !fds) return;
154   if (fd>=*maxfd) *maxfd= fd+1;
155   FD_SET(fd,fds);
156 }
157
158 static void checktimeouts(adns_state ads, struct timeval now,
159                           struct timeval **tv_io, struct timeval *tvbuf) {
160   adns_query qu, nqu;
161   
162   for (qu= ads->timew.head; qu; qu= nqu) {
163     nqu= qu->next;
164     if (timercmp(&now,&qu->timeout,>)) {
165       LIST_UNLINK(ads->timew,qu);
166       if (qu->state != query_udp) {
167         adns__query_fail(qu,adns_s_timeout);
168       } else {
169         adns__query_udp(qu,now);
170       }
171     } else {
172       inter_maxtoabs(tv_io,tvbuf,now,qu->timeout);
173     }
174   }
175 }  
176  
177 void adns_interest(adns_state ads, int *maxfd,
178                    fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
179                    struct timeval **tv_io, struct timeval *tvbuf) {
180   struct timeval now;
181   struct timeval tvto_lr;
182   int r;
183   
184 /*fprintf(stderr,"adns_interest\n");*/
185
186   r= gettimeofday(&now,0);
187   if (r) {
188     adns__warn(ads,-1,0,"gettimeofday failed - will sleep for a bit: %s",
189                strerror(errno));
190     timerclear(&tvto_lr); timevaladd(&tvto_lr,LOCALRESOURCEMS);
191     inter_maxto(tv_io, tvbuf, tvto_lr);
192   } else {
193     checktimeouts(ads,now,tv_io,tvbuf);
194   }
195   
196   inter_addfd(maxfd,readfds,ads->udpsocket);
197
198   switch (ads->tcpstate) {
199   case server_disconnected:
200     break;
201   case server_connecting:
202     inter_addfd(maxfd,writefds,ads->tcpsocket);
203     break;
204   case server_ok:
205     inter_addfd(maxfd,readfds,ads->tcpsocket);
206     inter_addfd(maxfd,exceptfds,ads->tcpsocket);
207     if (ads->tcpsend.used) inter_addfd(maxfd,writefds,ads->tcpsocket);
208     break;
209   default:
210     abort();
211   }
212 }
213
214 /* Callback procedures - these do the real work of reception and timeout, etc. */
215
216 static int callb_checkfd(int maxfd, const fd_set *fds, int fd) {
217   return maxfd<0 || !fds ? 1 :
218          fd<maxfd && FD_ISSET(fd,fds);
219 }
220
221 static int internal_callback(adns_state ads, int maxfd,
222                              const fd_set *readfds, const fd_set *writefds,
223                              const fd_set *exceptfds,
224                              struct timeval now) {
225   int skip, want, dgramlen, count, udpaddrlen, r, serv;
226   byte udpbuf[DNS_MAXUDP];
227   struct sockaddr_in udpaddr;
228
229   count= 0;
230
231   switch (ads->tcpstate) {
232   case server_disconnected:
233     break;
234   case server_connecting:
235     if (callb_checkfd(maxfd,writefds,ads->tcpsocket)) {
236       count++;
237       assert(ads->tcprecv.used==0);
238       if (!adns__vbuf_ensure(&ads->tcprecv,1)) return -1;
239       if (ads->tcprecv.buf) {
240         r= read(ads->tcpsocket,&ads->tcprecv.buf,1);
241         if (r==0 || (r<0 && (errno==EAGAIN || errno==EWOULDBLOCK))) {
242           tcp_connected(ads,now);
243         } else if (r>0) {
244           adns__tcp_broken(ads,"connect/read","sent data before first request");
245         } else if (errno!=EINTR) {
246           adns__tcp_broken(ads,"connect/read",strerror(errno));
247         }
248       }
249     }
250     break;
251   case server_ok:
252     count+= callb_checkfd(maxfd,readfds,ads->tcpsocket) +
253             callb_checkfd(maxfd,exceptfds,ads->tcpsocket) +
254       (ads->tcpsend.used && callb_checkfd(maxfd,writefds,ads->tcpsocket));
255     if (callb_checkfd(maxfd,readfds,ads->tcpsocket)) {
256       skip= 0;
257       for (;;) {
258         if (ads->tcprecv.used<skip+2) {
259           want= 2;
260         } else {
261           dgramlen= (ads->tcprecv.buf[skip]<<8) | ads->tcprecv.buf[skip+1];
262           if (ads->tcprecv.used<skip+2+dgramlen) {
263             want= 2+dgramlen;
264           } else {
265             adns__procdgram(ads,ads->tcprecv.buf+skip+2,dgramlen,ads->tcpserver,now);
266             skip+= 2+dgramlen; continue;
267           }
268         }
269         ads->tcprecv.used -= skip;
270         memmove(ads->tcprecv.buf,ads->tcprecv.buf+skip,ads->tcprecv.used);
271         skip= 0;
272         if (!adns__vbuf_ensure(&ads->tcprecv,want)) return -1;
273         assert(ads->tcprecv.used <= ads->tcprecv.avail);
274         if (ads->tcprecv.used == ads->tcprecv.avail) continue;
275         r= read(ads->tcpsocket,
276                 ads->tcprecv.buf+ads->tcprecv.used,
277                 ads->tcprecv.avail-ads->tcprecv.used);
278         if (r>0) {
279           ads->tcprecv.used+= r;
280         } else {
281           if (r<0) {
282             if (errno==EAGAIN || errno==EWOULDBLOCK || errno==ENOMEM) break;
283             if (errno==EINTR) continue;
284           }
285           adns__tcp_broken(ads,"read",r?strerror(errno):"closed");
286           break;
287         }
288       }
289     } else if (callb_checkfd(maxfd,exceptfds,ads->tcpsocket)) {
290       adns__tcp_broken(ads,"select","exceptional condition detected");
291     } else if (ads->tcpsend.used && callb_checkfd(maxfd,writefds,ads->tcpsocket)) {
292       adns__sigpipe_protect(ads);
293       r= write(ads->tcpsocket,ads->tcpsend.buf,ads->tcpsend.used);
294       adns__sigpipe_unprotect(ads);
295       if (r<0) {
296         if (errno!=EAGAIN && errno!=EWOULDBLOCK && errno!=ENOMEM && errno!=EINTR) {
297           adns__tcp_broken(ads,"write",strerror(errno));
298         }
299       } else if (r>0) {
300         ads->tcpsend.used -= r;
301         memmove(ads->tcpsend.buf,ads->tcpsend.buf+r,ads->tcpsend.used);
302       }
303     }
304     break;
305   default:
306     abort();
307   }
308
309   if (callb_checkfd(maxfd,readfds,ads->udpsocket)) {
310     count++;
311     for (;;) {
312       udpaddrlen= sizeof(udpaddr);
313       r= recvfrom(ads->udpsocket,udpbuf,sizeof(udpbuf),0,
314                   (struct sockaddr*)&udpaddr,&udpaddrlen);
315       if (r<0) {
316         if (!(errno == EAGAIN || errno == EWOULDBLOCK ||
317               errno == EINTR || errno == ENOMEM || errno == ENOBUFS))
318           adns__warn(ads,-1,0,"datagram receive error: %s",strerror(errno));
319         break;
320       }
321       if (udpaddrlen != sizeof(udpaddr)) {
322         adns__diag(ads,-1,0,"datagram received with wrong address length %d"
323                    " (expected %d)", udpaddrlen,sizeof(udpaddr));
324         continue;
325       }
326       if (udpaddr.sin_family != AF_INET) {
327         adns__diag(ads,-1,0,"datagram received with wrong protocol family"
328                    " %u (expected %u)",udpaddr.sin_family,AF_INET);
329         continue;
330       }
331       if (ntohs(udpaddr.sin_port) != DNS_PORT) {
332         adns__diag(ads,-1,0,"datagram received from wrong port %u (expected %u)",
333                    ntohs(udpaddr.sin_port),DNS_PORT);
334         continue;
335       }
336       for (serv= 0;
337            serv < ads->nservers &&
338              ads->servers[serv].addr.s_addr != udpaddr.sin_addr.s_addr;
339            serv++);
340       if (serv >= ads->nservers) {
341         adns__warn(ads,-1,0,"datagram received from unknown nameserver %s",
342                    inet_ntoa(udpaddr.sin_addr));
343         continue;
344       }
345       adns__procdgram(ads,udpbuf,r,serv,now);
346     }
347   }
348   return count;
349 }
350
351 int adns_callback(adns_state ads, int maxfd,
352                   const fd_set *readfds, const fd_set *writefds,
353                   const fd_set *exceptfds) {
354   struct timeval now;
355   int r;
356
357   r= gettimeofday(&now,0); if (r) return -1;
358   checktimeouts(ads,now,0,0);
359   return internal_callback(ads,maxfd,readfds,writefds,exceptfds,now);
360 }
361
362 /* User-visible functions and their implementation. */
363
364 void adns__autosys(adns_state ads, struct timeval now) {
365   if (ads->iflags & adns_if_noautosys) return;
366   adns_callback(ads,-1,0,0,0);
367 }
368
369 static int internal_check(adns_state ads,
370                           adns_query *query_io,
371                           adns_answer **answer,
372                           void **context_r) {
373   adns_query qu;
374
375   qu= *query_io;
376   if (!qu) {
377     if (!ads->output.head) return EWOULDBLOCK;
378     qu= ads->output.head;
379   } else {
380     if (qu->id>=0) return EWOULDBLOCK;
381   }
382   LIST_UNLINK(ads->output,qu);
383   *answer= qu->answer;
384   if (context_r) *context_r= qu->ctx.ext;
385   free(qu);
386   return 0;
387 }
388
389 int adns_wait(adns_state ads,
390               adns_query *query_io,
391               adns_answer **answer_r,
392               void **context_r) {
393   int r, maxfd, rsel, rcb;
394   fd_set readfds, writefds, exceptfds;
395   struct timeval tvbuf, *tvp;
396   
397   for (;;) {
398     r= internal_check(ads,query_io,answer_r,context_r);
399     if (r != EWOULDBLOCK) return r;
400     maxfd= 0; tvp= 0;
401     FD_ZERO(&readfds); FD_ZERO(&writefds); FD_ZERO(&exceptfds);
402     adns_interest(ads,&maxfd,&readfds,&writefds,&exceptfds,&tvp,&tvbuf);
403     rsel= select(maxfd,&readfds,&writefds,&exceptfds,tvp);
404     if (rsel==-1) {
405       if (errno == EINTR && !(ads->iflags & adns_if_eintr)) continue;
406       return errno;
407     }
408     rcb= adns_callback(ads,maxfd,&readfds,&writefds,&exceptfds);
409     assert(rcb==rsel);
410   }
411 }
412
413 int adns_check(adns_state ads,
414                adns_query *query_io,
415                adns_answer **answer_r,
416                void **context_r) {
417   struct timeval now;
418   int r;
419   
420   r= gettimeofday(&now,0); if (r) return errno;
421   adns__autosys(ads,now);
422   return internal_check(ads,query_io,answer_r,context_r);
423 }