chiark / gitweb /
Incompatible changes:
[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 <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
36 #include "internal.h"
37
38 /* TCP connection management. */
39
40 void adns__tcp_closenext(adns_state ads) {
41   int serv;
42   
43   serv= ads->tcpserver;
44   close(ads->tcpsocket);
45   ads->tcpstate= server_disconnected;
46   ads->tcprecv.used= ads->tcpsend.used= 0;
47   ads->tcpserver= (serv+1)%ads->nservers;
48 }
49
50 void adns__tcp_broken(adns_state ads, const char *what, const char *why) {
51   int serv;
52   adns_query qu, nqu;
53   
54   assert(ads->tcpstate == server_connecting || ads->tcpstate == server_ok);
55   serv= ads->tcpserver;
56   adns__warn(ads,serv,0,"TCP connection lost: %s: %s",what,why);
57   adns__tcp_closenext(ads);
58   
59   for (qu= ads->timew.head; qu; qu= nqu) {
60     nqu= qu->next;
61     if (qu->state == query_tosend) continue;
62     assert(qu->state == query_tcpwait || qu->state == query_tcpsent);
63     qu->state= query_tcpwait;
64     qu->tcpfailed |= (1<<serv);
65     if (qu->tcpfailed == (1<<ads->nservers)-1) {
66       LIST_UNLINK(ads->timew,qu);
67       adns__query_fail(qu,adns_s_allservfail);
68     }
69   }
70 }
71
72 static void tcp_connected(adns_state ads, struct timeval now) {
73   adns_query qu, nqu;
74   
75   adns__debug(ads,ads->tcpserver,0,"TCP connected");
76   ads->tcpstate= server_ok;
77   for (qu= ads->timew.head; qu; qu= nqu) {
78     nqu= qu->next;
79     if (qu->state == query_tosend) continue;
80     assert (qu->state == query_tcpwait);
81     adns__query_tcp(qu,now);
82   }
83 }
84
85 void adns__tcp_tryconnect(adns_state ads, struct timeval now) {
86   int r, fd, tries;
87   struct sockaddr_in addr;
88   struct protoent *proto;
89
90   for (tries=0; tries<ads->nservers; tries++) {
91     if (ads->tcpstate == server_connecting || ads->tcpstate == server_ok) return;
92     assert(ads->tcpstate == server_disconnected);
93     assert(!ads->tcpsend.used);
94     assert(!ads->tcprecv.used);
95
96     proto= getprotobyname("tcp");
97     if (!proto) { adns__diag(ads,-1,0,"unable to find protocol no. for TCP !"); return; }
98     fd= socket(AF_INET,SOCK_STREAM,proto->p_proto);
99     if (fd<0) {
100       adns__diag(ads,-1,0,"cannot create TCP socket: %s",strerror(errno));
101       return;
102     }
103     r= adns__setnonblock(ads,fd);
104     if (r) {
105       adns__diag(ads,-1,0,"cannot make TCP socket nonblocking: %s",strerror(r));
106       close(fd);
107       return;
108     }
109     memset(&addr,0,sizeof(addr));
110     addr.sin_family= AF_INET;
111     addr.sin_port= htons(DNS_PORT);
112     addr.sin_addr= ads->servers[ads->tcpserver].addr;
113     r= connect(fd,(const struct sockaddr*)&addr,sizeof(addr));
114     ads->tcpsocket= fd;
115     ads->tcpstate= server_connecting;
116     if (r==0) { tcp_connected(ads,now); continue; }
117     if (errno == EWOULDBLOCK || errno == EINPROGRESS) return;
118     adns__tcp_broken(ads,"connect",strerror(errno));
119   }
120 }
121
122 /* Timeout handling functions. */
123
124 void adns__must_gettimeofday(adns_state ads, const struct timeval **now_io,
125                              struct timeval *tv_buf) {
126   const struct timeval *now;
127   int r;
128
129   now= *now_io;
130   if (now) return;
131   r= gettimeofday(tv_buf,0); if (!r) { *now_io= tv_buf; return; }
132   adns__diag(ads,-1,0,"gettimeofday failed: %s",strerror(errno));
133   adns_globalsystemfailure(ads);
134   return;
135 }
136
137 static void inter_maxto(struct timeval **tv_io, struct timeval *tvbuf,
138                         struct timeval maxto) {
139   struct timeval *rbuf;
140
141   if (!tv_io) return;
142   rbuf= *tv_io;
143   if (!rbuf) {
144     *tvbuf= maxto; *tv_io= tvbuf;
145   } else {
146     if (timercmp(rbuf,&maxto,>)) *rbuf= maxto;
147   }
148 /*fprintf(stderr,"inter_maxto maxto=%ld.%06ld result=%ld.%06ld\n",
149         maxto.tv_sec,maxto.tv_usec,(**tv_io).tv_sec,(**tv_io).tv_usec);*/
150 }
151
152 static void inter_maxtoabs(struct timeval **tv_io, struct timeval *tvbuf,
153                            struct timeval now, struct timeval maxtime) {
154   ldiv_t dr;
155
156 /*fprintf(stderr,"inter_maxtoabs now=%ld.%06ld maxtime=%ld.%06ld\n",
157         now.tv_sec,now.tv_usec,maxtime.tv_sec,maxtime.tv_usec);*/
158   if (!tv_io) return;
159   maxtime.tv_sec -= (now.tv_sec+2);
160   maxtime.tv_usec -= (now.tv_usec-2000000);
161   dr= ldiv(maxtime.tv_usec,1000000);
162   maxtime.tv_sec += dr.quot;
163   maxtime.tv_usec -= dr.quot*1000000;
164   if (maxtime.tv_sec<0) timerclear(&maxtime);
165   inter_maxto(tv_io,tvbuf,maxtime);
166 }
167
168 void adns__timeouts(adns_state ads, int act,
169                     struct timeval **tv_io, struct timeval *tvbuf,
170                     struct timeval now) {
171   adns_query qu, nqu;
172
173   for (qu= ads->timew.head; qu; qu= nqu) {
174     nqu= qu->next;
175     if (!timercmp(&now,&qu->timeout,>)) {
176       if (!tv_io) continue;
177       inter_maxtoabs(tv_io,tvbuf,now,qu->timeout);
178     } else {
179       if (!act) continue;
180       LIST_UNLINK(ads->timew,qu);
181       if (qu->state != query_tosend) {
182         adns__query_fail(qu,adns_s_timeout);
183       } else {
184         adns__query_send(qu,now);
185       }
186       nqu= ads->timew.head;
187     }
188   }
189 }  
190
191 void adns_firsttimeout(adns_state ads,
192                        struct timeval **tv_io, struct timeval *tvbuf,
193                        struct timeval now) {
194   adns__timeouts(ads, 0, tv_io,tvbuf, now);
195 }
196
197 void adns_processtimeouts(adns_state ads, const struct timeval *now) {
198   struct timeval tv_buf;
199
200   adns__must_gettimeofday(ads,&now,&tv_buf); if (!now) return;
201   adns__timeouts(ads, 1, 0,0, *now);
202 }
203
204 /* fd handling functions.  These are the top-level of the real work of
205  * reception and often transmission.
206  */
207
208 int adns__pollfds(adns_state ads, struct pollfd pollfds_buf[MAX_POLLFDS]) {
209   /* Returns the number of entries filled in.  Always zeroes revents. */
210
211   assert(MAX_POLLFDS==2);
212
213   pollfds_buf[0].fd= ads->udpsocket;
214   pollfds_buf[0].events= POLLIN;
215   pollfds_buf[0].revents= 0;
216
217   switch (ads->tcpstate) {
218   case server_disconnected:
219     return 1;
220   case server_connecting:
221     pollfds_buf[1].events= POLLOUT;
222     break;
223   case server_ok:
224     pollfds_buf[1].events= ads->tcpsend.used ? POLLIN|POLLOUT|POLLPRI : POLLIN|POLLPRI;
225     break;
226   default:
227     abort();
228   }
229   pollfds_buf[1].fd= ads->tcpsocket;
230   return 2;
231 }
232
233 int adns_processreadable(adns_state ads, int fd, const struct timeval *now) {
234   int skip, want, dgramlen, r, udpaddrlen, serv;
235   byte udpbuf[DNS_MAXUDP];
236   struct sockaddr_in udpaddr;
237   
238   switch (ads->tcpstate) {
239   case server_disconnected:
240   case server_connecting:
241     break;
242   case server_ok:
243     if (fd != ads->tcpsocket) break;
244     skip= 0;
245     for (;;) {
246       if (ads->tcprecv.used<skip+2) {
247         want= 2;
248       } else {
249         dgramlen= (ads->tcprecv.buf[skip]<<8) | ads->tcprecv.buf[skip+1];
250         if (ads->tcprecv.used<skip+2+dgramlen) {
251           want= 2+dgramlen;
252         } else {
253           adns__procdgram(ads,ads->tcprecv.buf+skip+2,dgramlen,ads->tcpserver,1,*now);
254           skip+= 2+dgramlen; continue;
255         }
256       }
257       ads->tcprecv.used -= skip;
258       memmove(ads->tcprecv.buf,ads->tcprecv.buf+skip,ads->tcprecv.used);
259       skip= 0;
260       if (!adns__vbuf_ensure(&ads->tcprecv,want)) return ENOMEM;
261       assert(ads->tcprecv.used <= ads->tcprecv.avail);
262       if (ads->tcprecv.used == ads->tcprecv.avail) continue;
263       r= read(ads->tcpsocket,
264               ads->tcprecv.buf+ads->tcprecv.used,
265               ads->tcprecv.avail-ads->tcprecv.used);
266       if (r>0) {
267         ads->tcprecv.used+= r;
268       } else {
269         if (r) {
270           if (errno==EAGAIN || errno==EWOULDBLOCK) return 0;
271           if (errno==EINTR) continue;
272           if (errno_resources(errno)) return errno;
273         }
274         adns__tcp_broken(ads,"read",r?strerror(errno):"closed");
275         return 0;
276       }
277     } /* never reached */
278   default:
279     abort();
280   }
281   if (fd == ads->udpsocket) {
282     for (;;) {
283       udpaddrlen= sizeof(udpaddr);
284       r= recvfrom(ads->udpsocket,udpbuf,sizeof(udpbuf),0,
285                   (struct sockaddr*)&udpaddr,&udpaddrlen);
286       if (r<0) {
287         if (errno == EAGAIN || errno == EWOULDBLOCK) return 0;
288         if (errno == EINTR) continue;
289         if (errno_resources(errno)) return errno;
290         adns__warn(ads,-1,0,"datagram receive error: %s",strerror(errno));
291         return 0;
292       }
293       if (udpaddrlen != sizeof(udpaddr)) {
294         adns__diag(ads,-1,0,"datagram received with wrong address length %d"
295                    " (expected %d)", udpaddrlen,sizeof(udpaddr));
296         continue;
297       }
298       if (udpaddr.sin_family != AF_INET) {
299         adns__diag(ads,-1,0,"datagram received with wrong protocol family"
300                    " %u (expected %u)",udpaddr.sin_family,AF_INET);
301         continue;
302       }
303       if (ntohs(udpaddr.sin_port) != DNS_PORT) {
304         adns__diag(ads,-1,0,"datagram received from wrong port %u (expected %u)",
305                    ntohs(udpaddr.sin_port),DNS_PORT);
306         continue;
307       }
308       for (serv= 0;
309            serv < ads->nservers &&
310              ads->servers[serv].addr.s_addr != udpaddr.sin_addr.s_addr;
311            serv++);
312       if (serv >= ads->nservers) {
313         adns__warn(ads,-1,0,"datagram received from unknown nameserver %s",
314                    inet_ntoa(udpaddr.sin_addr));
315         continue;
316       }
317       adns__procdgram(ads,udpbuf,r,serv,0,*now);
318     }
319   }
320   return 0;
321 }
322
323 int adns_processwriteable(adns_state ads, int fd, const struct timeval *now) {
324   int r;
325   
326   switch (ads->tcpstate) {
327   case server_disconnected:
328     break;
329   case server_connecting:
330     if (fd != ads->tcpsocket) break;
331     assert(ads->tcprecv.used==0);
332     for (;;) {
333       if (!adns__vbuf_ensure(&ads->tcprecv,1)) return ENOMEM;
334       r= read(ads->tcpsocket,&ads->tcprecv.buf,1);
335       if (r==0 || (r<0 && (errno==EAGAIN || errno==EWOULDBLOCK))) {
336         tcp_connected(ads,*now);
337         return 0;
338       }
339       if (r>0) {
340         adns__tcp_broken(ads,"connect/read","sent data before first request");
341         return 0;
342       }
343       if (errno==EINTR) continue;
344       if (errno_resources(errno)) return errno;
345       adns__tcp_broken(ads,"connect/read",strerror(errno));
346       return 0;
347     } /* not reached */
348   case server_ok:
349     if (!(ads->tcpsend.used && fd == ads->tcpsocket)) break;
350     for (;;) {
351       adns__sigpipe_protect(ads);
352       r= write(ads->tcpsocket,ads->tcpsend.buf,ads->tcpsend.used);
353       adns__sigpipe_unprotect(ads);
354       if (r<0) {
355         if (errno==EINTR) continue;
356         if (errno==EAGAIN || errno==EWOULDBLOCK) return 0;
357         if (errno_resources(errno)) return errno;
358         adns__tcp_broken(ads,"write",strerror(errno));
359         return 0;
360       } else if (r>0) {
361         ads->tcpsend.used -= r;
362         memmove(ads->tcpsend.buf,ads->tcpsend.buf+r,ads->tcpsend.used);
363       }
364     } /* not reached */
365   default:
366     abort();
367   }
368   return 0;
369 }
370   
371 int adns_processexceptional(adns_state ads, int fd, const struct timeval *now) {
372   switch (ads->tcpstate) {
373   case server_disconnected:
374     break;
375   case server_connecting:
376   case server_ok:
377     if (fd != ads->tcpsocket) break;
378     adns__tcp_broken(ads,"poll/select","exceptional condition detected");
379     return 0;
380   default:
381     abort();
382   }
383   return 0;
384 }
385
386 static void fd_event(adns_state ads, int fd,
387                      int revent, int pollflag,
388                      int maxfd, const fd_set *fds,
389                      int (*func)(adns_state, int fd, const struct timeval *now),
390                      struct timeval now, int *r_r) {
391   int r;
392   
393   if (!(revent & pollflag)) return;
394   if (fds && !(fd<maxfd && FD_ISSET(fd,fds))) return;
395   r= func(ads,fd,&now);
396   if (r) {
397     if (r_r) {
398       *r_r= r;
399     } else {
400       adns__diag(ads,-1,0,"process fd failed after select: %s",strerror(errno));
401       adns_globalsystemfailure(ads);
402     }
403   }
404 }
405
406 void adns__fdevents(adns_state ads,
407                     const struct pollfd *pollfds, int npollfds,
408                     int maxfd, const fd_set *readfds,
409                     const fd_set *writefds, const fd_set *exceptfds,
410                     struct timeval now, int *r_r) {
411   int i, fd, revents;
412
413   for (i=0; i<npollfds; i++) {
414     fd= pollfds[i].fd;
415     if (fd >= maxfd) maxfd= fd+1;
416     revents= pollfds[i].revents;
417     fd_event(ads,fd, revents,POLLIN, maxfd,readfds, adns_processreadable,now,r_r);
418     fd_event(ads,fd, revents,POLLOUT, maxfd,writefds, adns_processwriteable,now,r_r);
419     fd_event(ads,fd, revents,POLLPRI, maxfd,exceptfds, adns_processexceptional,now,r_r);
420   }
421 }
422
423 /* Wrappers for select(2). */
424
425 void adns_beforeselect(adns_state ads, int *maxfd_io, fd_set *readfds_io,
426                        fd_set *writefds_io, fd_set *exceptfds_io,
427                        struct timeval **tv_mod, struct timeval *tv_tobuf,
428                        const struct timeval *now) {
429   struct timeval tv_nowbuf;
430   struct pollfd pollfds[MAX_POLLFDS];
431   int i, fd, maxfd, npollfds;
432   
433   if (tv_mod && (!*tv_mod || (*tv_mod)->tv_sec || (*tv_mod)->tv_usec)) {
434     /* The caller is planning to sleep. */
435     adns__must_gettimeofday(ads,&now,&tv_nowbuf);
436     if (!now) return;
437     adns__timeouts(ads, 1, tv_mod,tv_tobuf, *now);
438   }
439
440   npollfds= adns__pollfds(ads,pollfds);
441   maxfd= *maxfd_io;
442   for (i=0; i<npollfds; i++) {
443     fd= pollfds[i].fd;
444     if (fd >= maxfd) maxfd= fd+1;
445     if (pollfds[i].events & POLLIN) FD_SET(fd,readfds_io);
446     if (pollfds[i].events & POLLOUT) FD_SET(fd,writefds_io);
447     if (pollfds[i].events & POLLPRI) FD_SET(fd,exceptfds_io);
448   }
449   *maxfd_io= maxfd;
450 }
451
452 void adns_afterselect(adns_state ads, int maxfd, const fd_set *readfds,
453                       const fd_set *writefds, const fd_set *exceptfds,
454                       const struct timeval *now) {
455   struct timeval tv_buf;
456   struct pollfd pollfds[MAX_POLLFDS];
457   int npollfds, i;
458
459   adns__must_gettimeofday(ads,&now,&tv_buf);
460   if (!now) return;
461   adns_processtimeouts(ads,now);
462
463   npollfds= adns__pollfds(ads,pollfds);
464   for (i=0; i<npollfds; i++) pollfds[i].revents= POLLIN|POLLOUT|POLLPRI;
465   adns__fdevents(ads,
466                  pollfds,npollfds,
467                  maxfd,readfds,writefds,exceptfds,
468                  *now, 0);
469 }
470
471 /* General helpful functions. */
472
473 void adns_globalsystemfailure(adns_state ads) {
474   while (ads->timew.head) {
475     adns__query_fail(ads->timew.head, adns_s_systemfail);
476   }
477   
478   switch (ads->tcpstate) {
479   case server_connecting:
480   case server_ok:
481     adns__tcp_closenext(ads);
482     break;
483   case server_disconnected:
484     break;
485   default:
486     abort();
487   }
488 }
489
490 int adns_processany(adns_state ads) {
491   int r;
492   struct timeval now;
493   struct pollfd pollfds[MAX_POLLFDS];
494   int npollfds;
495
496   r= gettimeofday(&now,0);
497   if (!r) adns_processtimeouts(ads,&now);
498
499   npollfds= adns__pollfds(ads,pollfds);
500   adns__fdevents(ads,
501                  pollfds,npollfds,
502                  0,0,0,0,
503                  now,&r);
504   return r;
505 }
506
507 void adns__autosys(adns_state ads, struct timeval now) {
508   if (ads->iflags & adns_if_noautosys) return;
509   adns_processany(ads);
510 }
511
512 static int internal_check(adns_state ads,
513                           adns_query *query_io,
514                           adns_answer **answer,
515                           void **context_r) {
516   adns_query qu;
517
518   qu= *query_io;
519   if (!qu) {
520     if (!ads->output.head) return EWOULDBLOCK;
521     qu= ads->output.head;
522   } else {
523     if (qu->id>=0) return EWOULDBLOCK;
524   }
525   LIST_UNLINK(ads->output,qu);
526   *answer= qu->answer;
527   if (context_r) *context_r= qu->ctx.ext;
528   *query_io= qu;
529   free(qu);
530   return 0;
531 }
532
533 int adns_wait(adns_state ads,
534               adns_query *query_io,
535               adns_answer **answer_r,
536               void **context_r) {
537   int r, maxfd, rsel;
538   fd_set readfds, writefds, exceptfds;
539   struct timeval tvbuf, *tvp;
540   
541   for (;;) {
542     r= internal_check(ads,query_io,answer_r,context_r);
543     if (r != EWOULDBLOCK) return r;
544     maxfd= 0; tvp= 0;
545     FD_ZERO(&readfds); FD_ZERO(&writefds); FD_ZERO(&exceptfds);
546     adns_beforeselect(ads,&maxfd,&readfds,&writefds,&exceptfds,&tvp,&tvbuf,0);
547     rsel= select(maxfd,&readfds,&writefds,&exceptfds,tvp);
548     if (rsel==-1) {
549       if (errno == EINTR) {
550         if (ads->iflags & adns_if_eintr) return EINTR;
551       } else {
552         adns__diag(ads,-1,0,"select failed in wait: %s",strerror(errno));
553         adns_globalsystemfailure(ads);
554       }
555     } else {
556       assert(rsel >= 0);
557       adns_afterselect(ads,maxfd,&readfds,&writefds,&exceptfds,0);
558     }
559   }
560 }
561
562 int adns_check(adns_state ads,
563                adns_query *query_io,
564                adns_answer **answer_r,
565                void **context_r) {
566   struct timeval now;
567   int r;
568   
569   r= gettimeofday(&now,0);
570   if (!r) adns__autosys(ads,now);
571   
572   return internal_check(ads,query_io,answer_r,context_r);
573 }