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