chiark / gitweb /
log bad closes
[disorder] / lib / event.c
1 /*
2  * This file is part of DisOrder.
3  * Copyright (C) 2004, 2005, 2007 Richard Kettlewell
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
18  * USA
19  */
20 /** @file lib/event.c
21  * @brief DisOrder event loop
22  */
23
24 #include <config.h>
25
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <sys/time.h>
29 #include <sys/types.h>
30 #include <sys/resource.h>
31 #include <sys/wait.h>
32 #include <sys/stat.h>
33 #include <unistd.h>
34 #include <assert.h>
35 #include <signal.h>
36 #include <errno.h>
37 #include <string.h>
38 #include <limits.h>
39 #include <sys/socket.h>
40 #include <netinet/in.h>
41 #include <sys/un.h>
42 #include <stdio.h>
43 #include "event.h"
44 #include "mem.h"
45 #include "log.h"
46 #include "syscalls.h"
47 #include "printf.h"
48 #include "sink.h"
49 #include "vector.h"
50
51 /** @brief A timeout */
52 struct timeout {
53   struct timeout *next;
54   struct timeval when;
55   ev_timeout_callback *callback;
56   void *u;
57   int resolve;
58 };
59
60 /** @brief A file descriptor in one mode */
61 struct fd {
62   int fd;
63   ev_fd_callback *callback;
64   void *u;
65   const char *what;
66 };
67
68 /** @brief All the file descriptors in a given mode */
69 struct fdmode {
70   /** @brief Mask of active file descriptors passed to @c select() */
71   fd_set enabled;
72
73   /** @brief File descriptor mask returned from @c select() */
74   fd_set tripped;
75
76   /** @brief Number of file descriptors in @p fds */
77   int nfds;
78
79   /** @brief Number of slots in @p fds */
80   int fdslots;
81
82   /** @brief Array of all active file descriptors */
83   struct fd *fds;
84
85   /** @brief Highest-numbered file descriptor or 0 */
86   int maxfd;
87 };
88
89 /** @brief A signal handler */
90 struct signal {
91   struct sigaction oldsa;
92   ev_signal_callback *callback;
93   void *u;
94 };
95
96 /** @brief A child process */
97 struct child {
98   pid_t pid;
99   int options;
100   ev_child_callback *callback;
101   void *u;
102 };
103
104 /** @brief An event loop */
105 struct ev_source {
106   /** @brief File descriptors, per mode */
107   struct fdmode mode[ev_nmodes];
108
109   /** @brief Sorted linked list of timeouts
110    *
111    * We could use @ref HEAP_TYPE now, but there aren't many timeouts.
112    */
113   struct timeout *timeouts;
114
115   /** @brief Array of handled signals */
116   struct signal signals[NSIG];
117
118   /** @brief Mask of handled signals */
119   sigset_t sigmask;
120
121   /** @brief Escape early from handling of @c select() results
122    *
123    * This is set if any of the file descriptor arrays are invalidated, since
124    * it's then not safe for processing of them to continue.
125    */
126   int escape;
127
128   /** @brief Signal handling pipe
129    *
130    * The signal handle writes signal numbers down this pipe.
131    */
132   int sigpipe[2];
133
134   /** @brief Number of child processes in @p children */
135   int nchildren;
136
137   /** @brief Number of slots in @p children */
138   int nchildslots;
139
140   /** @brief Array of child processes */
141   struct child *children;
142 };
143
144 /** @brief Names of file descriptor modes */
145 static const char *modenames[] = { "read", "write", "except" };
146
147 /* utilities ******************************************************************/
148
149 /** @brief Great-than comparison for timevals
150  *
151  * Ought to be in @file lib/timeval.h
152  */
153 static inline int gt(const struct timeval *a, const struct timeval *b) {
154   if(a->tv_sec > b->tv_sec)
155     return 1;
156   if(a->tv_sec == b->tv_sec
157      && a->tv_usec > b->tv_usec)
158     return 1;
159   return 0;
160 }
161
162 /** @brief Greater-than-or-equal comparison for timevals
163  *
164  * Ought to be in @file lib/timeval.h
165  */
166 static inline int ge(const struct timeval *a, const struct timeval *b) {
167   return !gt(b, a);
168 }
169
170 /* creation *******************************************************************/
171
172 /** @brief Create a new event loop */
173 ev_source *ev_new(void) {
174   ev_source *ev = xmalloc(sizeof *ev);
175   int n;
176
177   memset(ev, 0, sizeof *ev);
178   for(n = 0; n < ev_nmodes; ++n)
179     FD_ZERO(&ev->mode[n].enabled);
180   ev->sigpipe[0] = ev->sigpipe[1] = -1;
181   sigemptyset(&ev->sigmask);
182   return ev;
183 }
184
185 /* event loop *****************************************************************/
186
187 /** @brief Run the event loop
188  * @return -1 on error, non-0 if any callback returned non-0
189  */
190 int ev_run(ev_source *ev) {
191   for(;;) {
192     struct timeval now;
193     struct timeval delta;
194     int n, mode;
195     int ret;
196     int maxfd;
197     struct timeout *t, **tt;
198     struct stat sb;
199
200     xgettimeofday(&now, 0);
201     /* Handle timeouts.  We don't want to handle any timeouts that are added
202      * while we're handling them (otherwise we'd have to break out of infinite
203      * loops, preferrably without starving better-behaved subsystems).  Hence
204      * the slightly complicated two-phase approach here. */
205     for(t = ev->timeouts;
206         t && ge(&now, &t->when);
207         t = t->next) {
208       t->resolve = 1;
209       D(("calling timeout for %ld.%ld callback %p %p",
210          (long)t->when.tv_sec, (long)t->when.tv_usec,
211          (void *)t->callback, t->u));
212       ret = t->callback(ev, &now, t->u);
213       if(ret)
214         return ret;
215     }
216     tt = &ev->timeouts;
217     while((t = *tt)) {
218       if(t->resolve)
219         *tt = t->next;
220       else
221         tt = &t->next;
222     }
223     maxfd = 0;
224     for(mode = 0; mode < ev_nmodes; ++mode) {
225       ev->mode[mode].tripped = ev->mode[mode].enabled;
226       if(ev->mode[mode].maxfd > maxfd)
227         maxfd = ev->mode[mode].maxfd;
228     }
229     xsigprocmask(SIG_UNBLOCK, &ev->sigmask, 0);
230     do {
231       if(ev->timeouts) {
232         xgettimeofday(&now, 0);
233         delta.tv_sec = ev->timeouts->when.tv_sec - now.tv_sec;
234         delta.tv_usec = ev->timeouts->when.tv_usec - now.tv_usec;
235         if(delta.tv_usec < 0) {
236           delta.tv_usec += 1000000;
237           --delta.tv_sec;
238         }
239         if(delta.tv_sec < 0)
240           delta.tv_sec = delta.tv_usec = 0;
241         n = select(maxfd + 1,
242                    &ev->mode[ev_read].tripped,
243                    &ev->mode[ev_write].tripped,
244                    &ev->mode[ev_except].tripped,
245                    &delta);
246       } else {
247         n = select(maxfd + 1,
248                    &ev->mode[ev_read].tripped,
249                    &ev->mode[ev_write].tripped,
250                    &ev->mode[ev_except].tripped,
251                    0);
252       }
253     } while(n < 0 && errno == EINTR);
254     xsigprocmask(SIG_BLOCK, &ev->sigmask, 0);
255     if(n < 0) {
256       error(errno, "error calling select");
257       if(errno == EBADF) {
258         /* If there's a bad FD in the mix then check them all and log what we
259          * find, to ease debugging */
260         for(mode = 0; mode < ev_nmodes; ++mode) {
261           for(n = 0; n < ev->mode[mode].nfds; ++n) {
262             const int fd = ev->mode[mode].fds[n].fd;
263
264             if(FD_ISSET(fd, &ev->mode[mode].enabled)
265                && fstat(fd, &sb) < 0)
266               error(errno, "mode %s fstat %d (%s)",
267                     modenames[mode], fd, ev->mode[mode].fds[n].what);
268           }
269           for(n = 0; n <= maxfd; ++n)
270             if(FD_ISSET(n, &ev->mode[mode].enabled)
271                && fstat(n, &sb) < 0)
272               error(errno, "mode %s fstat %d", modenames[mode], n);
273         }
274       }
275       return -1;
276     }
277     if(n > 0) {
278       /* if anything deranges the meaning of an fd, or re-orders the
279        * fds[] tables, we'd better give up; such operations will
280        * therefore set @escape@. */
281       ev->escape = 0;
282       for(mode = 0; mode < ev_nmodes && !ev->escape; ++mode)
283         for(n = 0; n < ev->mode[mode].nfds && !ev->escape; ++n) {
284           int fd = ev->mode[mode].fds[n].fd;
285           if(FD_ISSET(fd, &ev->mode[mode].tripped)) {
286             D(("calling %s fd %d callback %p %p", modenames[mode], fd,
287                (void *)ev->mode[mode].fds[n].callback,
288                ev->mode[mode].fds[n].u));
289             ret = ev->mode[mode].fds[n].callback(ev, fd,
290                                                  ev->mode[mode].fds[n].u);
291             if(ret)
292               return ret;
293           }
294         }
295     }
296     /* we'll pick up timeouts back round the loop */
297   }
298 }
299
300 /* file descriptors ***********************************************************/
301
302 /** @brief Register a file descriptor
303  * @param ev Event loop
304  * @param mode @c ev_read or @c ev_write
305  * @param fd File descriptor
306  * @param callback Called when @p is readable/writable
307  * @param u Passed to @p callback
308  * @param what Text description
309  * @return 0 on success, non-0 on error
310  *
311  * Sets @ref ev_source::escape, so no further processing of file descriptors
312  * will occur this time round the event loop.
313  */
314 int ev_fd(ev_source *ev,
315           ev_fdmode mode,
316           int fd,
317           ev_fd_callback *callback,
318           void *u,
319           const char *what) {
320   int n;
321
322   D(("registering %s fd %d callback %p %p", modenames[mode], fd,
323      (void *)callback, u));
324   assert(mode < ev_nmodes);
325   if(ev->mode[mode].nfds >= ev->mode[mode].fdslots) {
326     ev->mode[mode].fdslots = (ev->mode[mode].fdslots
327                                ? 2 * ev->mode[mode].fdslots : 16);
328     D(("expanding %s fd table to %d entries", modenames[mode],
329        ev->mode[mode].fdslots));
330     ev->mode[mode].fds = xrealloc(ev->mode[mode].fds,
331                                   ev->mode[mode].fdslots * sizeof (struct fd));
332   }
333   n = ev->mode[mode].nfds++;
334   FD_SET(fd, &ev->mode[mode].enabled);
335   ev->mode[mode].fds[n].fd = fd;
336   ev->mode[mode].fds[n].callback = callback;
337   ev->mode[mode].fds[n].u = u;
338   ev->mode[mode].fds[n].what = what;
339   if(fd > ev->mode[mode].maxfd)
340     ev->mode[mode].maxfd = fd;
341   ev->escape = 1;
342   return 0;
343 }
344
345 /** @brief Cancel a file descriptor
346  * @param ev Event loop
347  * @param mode @c ev_read or @c ev_write
348  * @param fd File descriptor
349  * @return 0 on success, non-0 on error
350  *
351  * Sets @ref ev_source::escape, so no further processing of file descriptors
352  * will occur this time round the event loop.
353  */
354 int ev_fd_cancel(ev_source *ev, ev_fdmode mode, int fd) {
355   int n;
356   int maxfd;
357
358   D(("cancelling mode %s fd %d", modenames[mode], fd));
359   /* find the right struct fd */
360   for(n = 0; n < ev->mode[mode].nfds && fd != ev->mode[mode].fds[n].fd; ++n)
361     ;
362   assert(n < ev->mode[mode].nfds);
363   /* swap in the last fd and reduce the count */
364   if(n != ev->mode[mode].nfds - 1)
365     ev->mode[mode].fds[n] = ev->mode[mode].fds[ev->mode[mode].nfds - 1];
366   --ev->mode[mode].nfds;
367   /* if that was the biggest fd, find the new biggest one */
368   if(fd == ev->mode[mode].maxfd) {
369     maxfd = 0;
370     for(n = 0; n < ev->mode[mode].nfds; ++n)
371       if(ev->mode[mode].fds[n].fd > maxfd)
372         maxfd = ev->mode[mode].fds[n].fd;
373     ev->mode[mode].maxfd = maxfd;
374   }
375   /* don't tell select about this fd any more */
376   FD_CLR(fd, &ev->mode[mode].enabled);
377   ev->escape = 1;
378   return 0;
379 }
380
381 /** @brief Re-enable a file descriptor
382  * @param ev Event loop
383  * @param mode @c ev_read or @c ev_write
384  * @param fd File descriptor
385  * @return 0 on success, non-0 on error
386  *
387  * It is harmless if @p fd is currently disabled, but it must not have been
388  * cancelled.
389  */
390 int ev_fd_enable(ev_source *ev, ev_fdmode mode, int fd) {
391   D(("enabling mode %s fd %d", modenames[mode], fd));
392   FD_SET(fd, &ev->mode[mode].enabled);
393   return 0;
394 }
395
396 /** @brief Temporarily disable a file descriptor
397  * @param ev Event loop
398  * @param mode @c ev_read or @c ev_write
399  * @param fd File descriptor
400  * @return 0 on success, non-0 on error
401  *
402  * Re-enable with ev_fd_enable().  It is harmless if @p fd is already disabled,
403  * but it must not have been cancelled.
404  */
405 int ev_fd_disable(ev_source *ev, ev_fdmode mode, int fd) {
406   D(("disabling mode %s fd %d", modenames[mode], fd));
407   FD_CLR(fd, &ev->mode[mode].enabled);
408   FD_CLR(fd, &ev->mode[mode].tripped);
409   return 0;
410 }
411
412 /** @brief Log a report of file descriptor state */
413 void ev_report(ev_source *ev) {
414   int n, fd;
415   ev_fdmode mode;
416   struct dynstr d[1];
417   char b[4096];
418
419   dynstr_init(d);
420   for(mode = 0; mode < ev_nmodes; ++mode) {
421     info("mode %s maxfd %d", modenames[mode], ev->mode[mode].maxfd);
422     for(n = 0; n < ev->mode[mode].nfds; ++n) {
423       fd = ev->mode[mode].fds[n].fd;
424       info("fd %s %d%s%s (%s)", modenames[mode], fd,
425            FD_ISSET(fd, &ev->mode[mode].enabled) ? " enabled" : "",
426            FD_ISSET(fd, &ev->mode[mode].tripped) ? " tripped" : "",
427            ev->mode[mode].fds[n].what);
428     }
429     d->nvec = 0;
430     for(fd = 0; fd <= ev->mode[mode].maxfd; ++fd) {
431       if(!FD_ISSET(fd, &ev->mode[mode].enabled))
432         continue;
433       for(n = 0; n < ev->mode[mode].nfds; ++n) {
434         if(ev->mode[mode].fds[n].fd == fd)
435           break;
436       }
437       if(n < ev->mode[mode].nfds)
438         snprintf(b, sizeof b, "%d(%s)", fd, ev->mode[mode].fds[n].what);
439       else
440         snprintf(b, sizeof b, "%d", fd);
441       dynstr_append(d, ' ');
442       dynstr_append_string(d, b);
443     }
444     dynstr_terminate(d);
445     info("%s enabled:%s", modenames[mode], d->vec);
446   }
447 }
448
449 /* timeouts *******************************************************************/
450
451 /** @brief Register a timeout
452  * @param ev Event source
453  * @param handle Where to store timeout handle, or @c NULL
454  * @param when Earliest time to call @p callback, or @c NULL
455  * @param callback Function to call at or after @p when
456  * @param u Passed to @p callback
457  * @return 0 on success, non-0 on error
458  *
459  * If @p when is a null pointer then a time of 0 is assumed.  The effect is to
460  * call the timeout handler from ev_run() next time around the event loop.
461  * This is used internally to schedule various operations if it is not
462  * convenient to call them from the current place in the call stack, or
463  * externally to ensure that other clients of the event loop get a look in when
464  * performing some lengthy operation.
465  */
466 int ev_timeout(ev_source *ev,
467                ev_timeout_handle *handlep,
468                const struct timeval *when,
469                ev_timeout_callback *callback,
470                void *u) {
471   struct timeout *t, *p, **pp;
472
473   D(("registering timeout at %ld.%ld callback %p %p",
474      when ? (long)when->tv_sec : 0, when ? (long)when->tv_usec : 0,
475      (void *)callback, u));
476   t = xmalloc(sizeof *t);
477   if(when)
478     t->when = *when;
479   t->callback = callback;
480   t->u = u;
481   pp = &ev->timeouts;
482   while((p = *pp) && gt(&t->when, &p->when))
483     pp = &p->next;
484   t->next = p;
485   *pp = t;
486   if(handlep)
487     *handlep = t;
488   return 0;
489 }
490
491 /** @brief Cancel a timeout
492  * @param ev Event loop
493  * @param handle Handle returned from ev_timeout(), or 0
494  * @return 0 on success, non-0 on error
495  *
496  * If @p handle is 0 then this is a no-op.
497  */
498 int ev_timeout_cancel(ev_source *ev,
499                       ev_timeout_handle handle) {
500   struct timeout *t = handle, *p, **pp;
501
502   if(!t)
503     return 0;
504   for(pp = &ev->timeouts; (p = *pp) && p != t; pp = &p->next)
505     ;
506   if(p) {
507     *pp = p->next;
508     return 0;
509   } else
510     return -1;
511 }
512
513 /* signals ********************************************************************/
514
515 /** @brief Mapping of signals to pipe write ends
516  *
517  * The pipes are per-event loop, it's possible in theory for there to be
518  * multiple event loops (e.g. in different threads), although in fact DisOrder
519  * does not do this.
520  */
521 static int sigfd[NSIG];
522
523 /** @brief The signal handler
524  * @param s Signal number
525  *
526  * Writes to @c sigfd[s].
527  */
528 static void sighandler(int s) {
529   unsigned char sc = s;
530   static const char errmsg[] = "error writing to signal pipe";
531
532   /* probably the reader has stopped listening for some reason */
533   if(write(sigfd[s], &sc, 1) < 0) {
534     write(2, errmsg, sizeof errmsg - 1);
535     abort();
536   }
537 }
538
539 /** @brief Read callback for signals */
540 static int signal_read(ev_source *ev,
541                        int attribute((unused)) fd,
542                        void attribute((unused)) *u) {
543   unsigned char s;
544   int n;
545   int ret;
546
547   if((n = read(ev->sigpipe[0], &s, 1)) == 1)
548     if((ret = ev->signals[s].callback(ev, s, ev->signals[s].u)))
549       return ret;
550   assert(n != 0);
551   if(n < 0 && (errno != EINTR && errno != EAGAIN)) {
552     error(errno, "error reading from signal pipe %d", ev->sigpipe[0]);
553     return -1;
554   }
555   return 0;
556 }
557
558 /** @brief Close the signal pipe */
559 static void close_sigpipe(ev_source *ev) {
560   int save_errno = errno;
561
562   xclose(ev->sigpipe[0]);
563   xclose(ev->sigpipe[1]);
564   ev->sigpipe[0] = ev->sigpipe[1] = -1;
565   errno = save_errno;
566 }
567
568 /** @brief Register a signal handler
569  * @param ev Event loop
570  * @param sig Signal to handle
571  * @param callback Called when signal is delivered
572  * @param u Passed to @p callback
573  * @return 0 on success, non-0 on error
574  *
575  * Note that @p callback is called from inside ev_run(), not from inside the
576  * signal handler, so the usual restrictions on signal handlers do not apply.
577  */
578 int ev_signal(ev_source *ev,
579               int sig,
580               ev_signal_callback *callback,
581               void *u) {
582   int n;
583   struct sigaction sa;
584
585   D(("registering signal %d handler callback %p %p", sig, (void *)callback, u));
586   assert(sig > 0);
587   assert(sig < NSIG);
588   assert(sig <= UCHAR_MAX);
589   if(ev->sigpipe[0] == -1) {
590     D(("creating signal pipe"));
591     xpipe(ev->sigpipe);
592     D(("signal pipe is %d, %d", ev->sigpipe[0], ev->sigpipe[1]));
593     for(n = 0; n < 2; ++n) {
594       nonblock(ev->sigpipe[n]);
595       cloexec(ev->sigpipe[n]);
596     }
597     if(ev_fd(ev, ev_read, ev->sigpipe[0], signal_read, 0, "sigpipe read")) {
598       close_sigpipe(ev);
599       return -1;
600     }
601   }
602   sigaddset(&ev->sigmask, sig);
603   xsigprocmask(SIG_BLOCK, &ev->sigmask, 0);
604   sigfd[sig] = ev->sigpipe[1];
605   ev->signals[sig].callback = callback;
606   ev->signals[sig].u = u;
607   sa.sa_handler = sighandler;
608   sigfillset(&sa.sa_mask);
609   sa.sa_flags = SA_RESTART;
610   xsigaction(sig, &sa, &ev->signals[sig].oldsa);
611   ev->escape = 1;
612   return 0;
613 }
614
615 /** @brief Cancel a signal handler
616  * @param ev Event loop
617  * @param sig Signal to cancel
618  * @return 0 on success, non-0 on error
619  */
620 int ev_signal_cancel(ev_source *ev,
621                      int sig) {
622   sigset_t ss;
623
624   xsigaction(sig, &ev->signals[sig].oldsa, 0);
625   ev->signals[sig].callback = 0;
626   ev->escape = 1;
627   sigdelset(&ev->sigmask, sig);
628   sigemptyset(&ss);
629   sigaddset(&ss, sig);
630   xsigprocmask(SIG_UNBLOCK, &ss, 0);
631   return 0;
632 }
633
634 /** @brief Clean up signal handling
635  * @param ev Event loop
636  *
637  * This function can be called from inside a fork.  It restores signal
638  * handlers, unblocks the signals, and closes the signal pipe for @p ev.
639  */
640 void ev_signal_atfork(ev_source *ev) {
641   int sig;
642
643   if(ev->sigpipe[0] != -1) {
644     /* revert any handled signals to their original state */
645     for(sig = 1; sig < NSIG; ++sig) {
646       if(ev->signals[sig].callback != 0)
647         xsigaction(sig, &ev->signals[sig].oldsa, 0);
648     }
649     /* and then unblock them */
650     xsigprocmask(SIG_UNBLOCK, &ev->sigmask, 0);
651     /* don't want a copy of the signal pipe open inside the fork */
652     xclose(ev->sigpipe[0]);
653     xclose(ev->sigpipe[1]);
654   }
655 }
656
657 /* child processes ************************************************************/
658
659 /** @brief Called on SIGCHLD */
660 static int sigchld_callback(ev_source *ev,
661                             int attribute((unused)) sig,
662                             void attribute((unused)) *u) {
663   struct rusage ru;
664   pid_t r;
665   int status, n, ret, revisit;
666
667   do {
668     revisit = 0;
669     for(n = 0; n < ev->nchildren; ++n) {
670       r = wait4(ev->children[n].pid,
671                 &status,
672                 ev->children[n].options | WNOHANG,
673                 &ru);
674       if(r > 0) {
675         ev_child_callback *c = ev->children[n].callback;
676         void *cu = ev->children[n].u;
677
678         if(WIFEXITED(status) || WIFSIGNALED(status))
679           ev_child_cancel(ev, r);
680         revisit = 1;
681         if((ret = c(ev, r, status, &ru, cu)))
682           return ret;
683       } else if(r < 0) {
684         /* We should "never" get an ECHILD but it can in fact happen.  For
685          * instance on Linux 2.4.31, and probably other versions, if someone
686          * straces a child process and then a different child process
687          * terminates, when we wait4() the trace process we will get ECHILD
688          * because it has been reparented to strace.  Obviously this is a
689          * hopeless design flaw in the tracing infrastructure, but we don't
690          * want the disorder server to bomb out because of it.  So we just log
691          * the problem and ignore it.
692          */
693         error(errno, "error calling wait4 for PID %lu (broken ptrace?)",
694               (unsigned long)ev->children[n].pid);
695         if(errno != ECHILD)
696           return -1;
697       }
698     }
699   } while(revisit);
700   return 0;
701 }
702
703 /** @brief Configure event loop for child process handling
704  * @return 0 on success, non-0 on error
705  *
706  * Currently at most one event loop can handle child processes and it must be
707  * distinguished from others by calling this function on it.  This could be
708  * fixed but since no process ever makes use of more than one event loop there
709  * is no need.
710  */
711 int ev_child_setup(ev_source *ev) {
712   D(("installing SIGCHLD handler"));
713   return ev_signal(ev, SIGCHLD, sigchld_callback, 0);
714 }
715
716 /** @brief Wait for a child process to terminate
717  * @param ev Event loop
718  * @param pid Process ID of child
719  * @param options Options to pass to @c wait4()
720  * @param callback Called when child terminates (or possibly when it stops)
721  * @param u Passed to @p callback
722  * @return 0 on success, non-0 on error
723  *
724  * You must have called ev_child_setup() on @p ev once first.
725  */
726 int ev_child(ev_source *ev,
727              pid_t pid,
728              int options,
729              ev_child_callback *callback,
730              void *u) {
731   int n;
732
733   D(("registering child handling %ld options %d callback %p %p",
734      (long)pid, options, (void *)callback, u));
735   assert(ev->signals[SIGCHLD].callback == sigchld_callback);
736   if(ev->nchildren >= ev->nchildslots) {
737     ev->nchildslots = ev->nchildslots ? 2 * ev->nchildslots : 16;
738     ev->children = xrealloc(ev->children,
739                             ev->nchildslots * sizeof (struct child));
740   }
741   n = ev->nchildren++;
742   ev->children[n].pid = pid;
743   ev->children[n].options = options;
744   ev->children[n].callback = callback;
745   ev->children[n].u = u;
746   return 0;
747 }
748
749 /** @brief Stop waiting for a child process
750  * @param ev Event loop
751  * @param pid Child process ID
752  * @return 0 on success, non-0 on error
753  */ 
754 int ev_child_cancel(ev_source *ev,
755                     pid_t pid) {
756   int n;
757
758   for(n = 0; n < ev->nchildren && ev->children[n].pid != pid; ++n)
759     ;
760   assert(n < ev->nchildren);
761   if(n != ev->nchildren - 1)
762     ev->children[n] = ev->children[ev->nchildren - 1];
763   --ev->nchildren;
764   return 0;
765 }
766
767 /* socket listeners ***********************************************************/
768
769 /** @brief State for a socket listener */
770 struct listen_state {
771   ev_listen_callback *callback;
772   void *u;
773 };
774
775 /** @brief Called when a listenign socket is readable */
776 static int listen_callback(ev_source *ev, int fd, void *u) {
777   const struct listen_state *l = u;
778   int newfd;
779   union {
780     struct sockaddr_in in;
781 #if HAVE_STRUCT_SOCKADDR_IN6
782     struct sockaddr_in6 in6;
783 #endif
784     struct sockaddr_un un;
785     struct sockaddr sa;
786   } addr;
787   socklen_t addrlen;
788   int ret;
789
790   D(("callback for listener fd %d", fd));
791   while((addrlen = sizeof addr),
792         (newfd = accept(fd, &addr.sa, &addrlen)) >= 0) {
793     if((ret = l->callback(ev, newfd, &addr.sa, addrlen, l->u)))
794       return ret;
795   }
796   switch(errno) {
797   case EINTR:
798   case EAGAIN:
799     break;
800 #ifdef ECONNABORTED
801   case ECONNABORTED:
802     error(errno, "error calling accept");
803     break;
804 #endif
805 #ifdef EPROTO
806   case EPROTO:
807     /* XXX on some systems EPROTO should be fatal, but we don't know if
808      * we're running on one of them */
809     error(errno, "error calling accept");
810     break;
811 #endif
812   default:
813     fatal(errno, "error calling accept");
814     break;
815   }
816   if(errno != EINTR && errno != EAGAIN)
817     error(errno, "error calling accept");
818   return 0;
819 }
820
821 /** @brief Listen on a socket for inbound stream connections
822  * @param ev Event source
823  * @param fd File descriptor of socket
824  * @param callback Called when a new connection arrives
825  * @param u Passed to @p callback
826  * @param what Text description of socket
827  * @return 0 on success, non-0 on error
828  */
829 int ev_listen(ev_source *ev,
830               int fd,
831               ev_listen_callback *callback,
832               void *u,
833               const char *what) {
834   struct listen_state *l = xmalloc(sizeof *l);
835
836   D(("registering listener fd %d callback %p %p", fd, (void *)callback, u));
837   l->callback = callback;
838   l->u = u;
839   return ev_fd(ev, ev_read, fd, listen_callback, l, what);
840 }
841
842 /** @brief Stop listening on a socket
843  * @param ev Event loop
844  * @param fd File descriptor of socket
845  * @return 0 on success, non-0 on error
846  */ 
847 int ev_listen_cancel(ev_source *ev, int fd) {
848   D(("cancelling listener fd %d", fd));
849   return ev_fd_cancel(ev, ev_read, fd);
850 }
851
852 /* buffer *********************************************************************/
853
854 /** @brief Buffer structure */
855 struct buffer {
856   char *base, *start, *end, *top;
857 };
858
859 /* @brief Make sure there is @p bytes available at @c b->end */
860 static void buffer_space(struct buffer *b, size_t bytes) {
861   D(("buffer_space %p %p %p %p want %lu",
862      (void *)b->base, (void *)b->start, (void *)b->end, (void *)b->top,
863      (unsigned long)bytes));
864   if(b->start == b->end)
865     b->start = b->end = b->base;
866   if((size_t)(b->top - b->end) < bytes) {
867     if((size_t)((b->top - b->end) + (b->start - b->base)) < bytes) {
868       size_t newspace = b->end - b->start + bytes, n;
869       char *newbase;
870
871       for(n = 16; n < newspace; n *= 2)
872         ;
873       newbase = xmalloc_noptr(n);
874       memcpy(newbase, b->start, b->end - b->start);
875       b->base = newbase;
876       b->end = newbase + (b->end - b->start);
877       b->top = newbase + n;
878       b->start = newbase;               /* must be last */
879     } else {
880       memmove(b->base, b->start, b->end - b->start);
881       b->end = b->base + (b->end - b->start);
882       b->start = b->base;
883     }
884   }
885   D(("result %p %p %p %p",
886      (void *)b->base, (void *)b->start, (void *)b->end, (void *)b->top));
887 }
888
889 /* buffered writer ************************************************************/
890
891 /** @brief State structure for a buffered writer */
892 struct ev_writer {
893   struct sink s;
894   struct buffer b;
895   int fd;
896   int eof;
897   ev_error_callback *callback;
898   void *u;
899   ev_source *ev;
900
901   /** @brief Maximum amount of time between succesful writes, 0 = don't care */
902   int timebound;
903   /** @brief Maximum amount of data to buffer, 0 = don't care */
904   int spacebound;
905   /** @brief Synthesized error code */
906   int syntherror;
907   /** @brief Timeout handle for @p timebound (or 0) */
908   ev_timeout_handle timeout;
909
910   const char *what;
911 };
912
913 /** @brief Synthesized error callback
914  *
915  * Calls @p callback with @p w->syntherr as the error code (which might be 0).
916  */
917 static int writer_shutdown(ev_source *ev,
918                            const attribute((unused)) struct timeval *now,
919                            void *u) {
920   ev_writer *w = u;
921   int fd;
922
923   if(w->fd == -1)
924     return 0;                           /* already closed */
925   ev_timeout_cancel(ev, w->timeout);
926   w->timeout = 0;
927   fd = w->fd;
928   w->fd = -1;
929   return w->callback(ev, fd, w->syntherror, w->u);
930 }
931
932 /** @brief Called when a writer's @p timebound expires */
933 static int writer_timebound_exceeded(ev_source *ev,
934                                      const struct timeval attribute((unused)) *now,
935                                      void *u) {
936   ev_writer *const w = u;
937   int fd;
938
939   if(w->fd == -1)
940     return 0;                           /* already closed */
941   error(0, "abandoning writer %s because no writes within %ds",
942         w->what, w->timebound);
943   fd = w->fd;
944   w->fd = -1;
945   return w->callback(ev, fd, ETIMEDOUT, w->u);
946 }
947
948 /** @brief Set the time bound callback (if not set already) */
949 static void writer_set_timebound(ev_writer *w) {
950   if(w->timebound && !w->timeout) {
951     struct timeval when;
952     ev_source *const ev = w->ev;
953     
954     xgettimeofday(&when, 0);
955     when.tv_sec += w->timebound;
956     ev_timeout(ev, &w->timeout, &when, writer_timebound_exceeded, w);
957   }
958 }
959
960 /** @brief Called when a writer's file descriptor is writable */
961 static int writer_callback(ev_source *ev, int fd, void *u) {
962   ev_writer *const w = u;
963   int n;
964
965   if(w->fd == -1)
966     return 0;
967   n = write(fd, w->b.start, w->b.end - w->b.start);
968   D(("callback for writer fd %d, %ld bytes, n=%d, errno=%d",
969      fd, (long)(w->b.end - w->b.start), n, errno));
970   if(n >= 0) {
971     w->b.start += n;
972     ev_timeout_cancel(ev, w->timeout);
973     w->timeout = 0;
974     if(w->b.start == w->b.end) {
975       if(w->eof) {
976         ev_fd_cancel(ev, ev_write, fd);
977         w->fd = -1;
978         return w->callback(ev, fd, 0, w->u);
979       } else
980         ev_fd_disable(ev, ev_write, fd);
981     } else
982       writer_set_timebound(w);
983   } else {
984     switch(errno) {
985     case EINTR:
986     case EAGAIN:
987       break;
988     default:
989       ev_fd_cancel(ev, ev_write, fd);
990       w->fd = -1;
991       return w->callback(ev, fd, errno, w->u);
992     }
993   }
994   return 0;
995 }
996
997 /** @brief Write bytes to a writer's buffer
998  *
999  * This is the sink write callback.
1000  *
1001  * Calls ev_fd_enable() if necessary (i.e. if the buffer was empty but
1002  * now is not).
1003  */
1004 static int ev_writer_write(struct sink *sk, const void *s, int n) {
1005   ev_writer *w = (ev_writer *)sk;
1006
1007   if(!n)
1008     return 0;                           /* avoid silliness */
1009   buffer_space(&w->b, n);
1010   if(w->b.start == w->b.end)
1011     ev_fd_enable(w->ev, ev_write, w->fd);
1012   memcpy(w->b.end, s, n);
1013   w->b.end += n;
1014   if(w->spacebound && w->b.end - w->b.start > w->spacebound) {
1015     /* Buffer contents have exceeded the space bound.  We assume that the
1016      * remote client has gone away and TCP hasn't noticed yet, or that it's got
1017      * hopelessly stuck. */
1018     error(0, "abandoning writer %s because buffer has reached %td bytes",
1019           w->what, w->b.end - w->b.start);
1020     w->syntherror = EPIPE;
1021     ev_fd_cancel(w->ev, ev_write, w->fd);
1022     return ev_timeout(w->ev, 0, 0, writer_shutdown, w);
1023   }
1024   writer_set_timebound(w);
1025   return 0;
1026 }
1027
1028 /** @brief Create a new buffered writer
1029  * @param ev Event loop
1030  * @param fd File descriptor to write to
1031  * @param callback Called if an error occurs and when finished
1032  * @param u Passed to @p callback
1033  * @param what Text description
1034  * @return New writer or @c NULL
1035  */ 
1036 ev_writer *ev_writer_new(ev_source *ev,
1037                          int fd,
1038                          ev_error_callback *callback,
1039                          void *u,
1040                          const char *what) {
1041   ev_writer *w = xmalloc(sizeof *w);
1042
1043   D(("registering writer fd %d callback %p %p", fd, (void *)callback, u));
1044   w->s.write = ev_writer_write;
1045   w->fd = fd;
1046   w->callback = callback;
1047   w->u = u;
1048   w->ev = ev;
1049   w->timebound = 10 * 60;
1050   w->spacebound = 512 * 1024;
1051   w->what = what;
1052   if(ev_fd(ev, ev_write, fd, writer_callback, w, what))
1053     return 0;
1054   ev_fd_disable(ev, ev_write, fd);
1055   return w;
1056 }
1057
1058 /** @brief Get/set the time bound
1059  * @param w Writer
1060  * @param new_time_bound New bound or -1 for no change
1061  * @return Latest time bound
1062  *
1063  * If @p new_time_bound is negative then the current time bound is returned.
1064  * Otherwise it is set and the new value returned.
1065  *
1066  * The time bound is the number of seconds allowed between writes.  If it takes
1067  * longer than this to flush a buffer then the peer will be assumed to be dead
1068  * and an error will be synthesized.  0 means "don't care".  The default time
1069  * bound is 10 minutes.
1070  *
1071  * Note that this value does not take into account kernel buffering and
1072  * timeouts.
1073  */
1074 int ev_writer_time_bound(ev_writer *w,
1075                          int new_time_bound) {
1076   if(new_time_bound >= 0)
1077     w->timebound = new_time_bound;
1078   return w->timebound;
1079 }
1080
1081 /** @brief Get/set the space bound
1082  * @param w Writer
1083  * @param new_space_bound New bound or -1 for no change
1084  * @return Latest space bound
1085  *
1086  * If @p new_space_bound is negative then the current space bound is returned.
1087  * Otherwise it is set and the new value returned.
1088  *
1089  * The space bound is the number of bytes allowed between in the buffer.  If
1090  * the buffer exceeds this size an error will be synthesized.  0 means "don't
1091  * care".  The default space bound is 512Kbyte.
1092  *
1093  * Note that this value does not take into account kernel buffering.
1094  */
1095 int ev_writer_space_bound(ev_writer *w,
1096                           int new_space_bound) {
1097   if(new_space_bound >= 0)
1098     w->spacebound = new_space_bound;
1099   return w->spacebound;
1100 }
1101
1102 /** @brief Return the sink associated with a writer
1103  * @param w Writer
1104  * @return Pointer to sink
1105  *
1106  * Writing to the sink will arrange for those bytes to be written to the file
1107  * descriptor as and when it is writable.
1108  */
1109 struct sink *ev_writer_sink(ev_writer *w) {
1110   if(!w)
1111     fatal(0, "ev_write_sink called with null writer");
1112   return &w->s;
1113 }
1114
1115 /** @brief Close a writer
1116  * @param w Writer to close
1117  * @return 0 on success, non-0 on error
1118  *
1119  * Close a writer.  No more bytes should be written to its sink.
1120  *
1121  * When the last byte has been written the callback will be called with an
1122  * error code of 0.  It is guaranteed that this will NOT happen before
1123  * ev_writer_close() returns (although the file descriptor for the writer might
1124  * be cancelled by the time it returns).
1125  */
1126 int ev_writer_close(ev_writer *w) {
1127   D(("close writer fd %d", w->fd));
1128   w->eof = 1;
1129   if(w->b.start == w->b.end) {
1130     /* we're already finished */
1131     w->syntherror = 0;                  /* no error */
1132     ev_fd_cancel(w->ev, ev_write, w->fd);
1133     return ev_timeout(w->ev, 0, 0, writer_shutdown, w);
1134   }
1135   return 0;
1136 }
1137
1138 /** @brief Cancel a writer discarding any buffered data
1139  * @param w Writer to close
1140  * @return 0 on success, non-0 on error
1141  *
1142  * This cancels a writer immediately.  Any unwritten buffered data is discarded
1143  * and the error callback is never called.  This is appropriate to call if (for
1144  * instance) the read half of a TCP connection is known to have failed and the
1145  * writer is therefore obsolete.
1146  */
1147 int ev_writer_cancel(ev_writer *w) {
1148   ev_source *const ev = w->ev;
1149   D(("cancel writer fd %d", w->fd));
1150   ev_timeout_cancel(ev, w->timeout);
1151   w->timeout = 0;
1152   return ev_fd_cancel(w->ev, ev_write, w->fd);
1153 }
1154
1155 /** @brief Attempt to flush a writer
1156  * @param w Writer to flush
1157  * @return 0 on success, non-0 on error
1158  *
1159  * Does a speculative write of any buffered data.  Does not block if it cannot
1160  * be written.
1161  */
1162 int ev_writer_flush(ev_writer *w) {
1163   return writer_callback(w->ev, w->fd, w);
1164 }
1165
1166 /* buffered reader ************************************************************/
1167
1168 /** @brief State structure for a buffered reader */
1169 struct ev_reader {
1170   struct buffer b;
1171   int fd;
1172   ev_reader_callback *callback;
1173   ev_error_callback *error_callback;
1174   void *u;
1175   ev_source *ev;
1176   int eof;
1177 };
1178
1179 /** @brief Called when a reader's @p fd is readable */
1180 static int reader_callback(ev_source *ev, int fd, void *u) {
1181   ev_reader *r = u;
1182   int n;
1183
1184   buffer_space(&r->b, 1);
1185   n = read(fd, r->b.end, r->b.top - r->b.end);
1186   D(("read fd %d buffer %d returned %d errno %d",
1187      fd, (int)(r->b.top - r->b.end), n, errno));
1188   if(n > 0) {
1189     r->b.end += n;
1190     return r->callback(ev, r, fd, r->b.start, r->b.end - r->b.start, 0, r->u);
1191   } else if(n == 0) {
1192     r->eof = 1;
1193     ev_fd_cancel(ev, ev_read, fd);
1194     return r->callback(ev, r, fd, r->b.start, r->b.end - r->b.start, 1, r->u);
1195   } else {
1196     switch(errno) {
1197     case EINTR:
1198     case EAGAIN:
1199       break;
1200     default:
1201       ev_fd_cancel(ev, ev_read, fd);
1202       return r->error_callback(ev, fd, errno, r->u);
1203     }
1204   }
1205   return 0;
1206 }
1207
1208 /** @brief Create a new buffered reader
1209  * @param ev Event loop
1210  * @param fd File descriptor to read from
1211  * @param callback Called when new data is available
1212  * @param error_callback Called if an error occurs
1213  * @param u Passed to callbacks
1214  * @param what Text description
1215  * @return New reader or @c NULL
1216  */
1217 ev_reader *ev_reader_new(ev_source *ev,
1218                          int fd,
1219                          ev_reader_callback *callback,
1220                          ev_error_callback *error_callback,
1221                          void *u,
1222                          const char *what) {
1223   ev_reader *r = xmalloc(sizeof *r);
1224
1225   D(("registering reader fd %d callback %p %p %p",
1226      fd, (void *)callback, (void *)error_callback, u));
1227   r->fd = fd;
1228   r->callback = callback;
1229   r->error_callback = error_callback;
1230   r->u = u;
1231   r->ev = ev;
1232   if(ev_fd(ev, ev_read, fd, reader_callback, r, what))
1233     return 0;
1234   return r;
1235 }
1236
1237 void ev_reader_buffer(ev_reader *r, size_t nbytes) {
1238   buffer_space(&r->b, nbytes - (r->b.end - r->b.start));
1239 }
1240
1241 /** @brief Consume @p n bytes from the reader's buffer
1242  * @param r Reader
1243  * @param n Number of bytes to consume
1244  *
1245  * Tells the reader than the next @p n bytes have been dealt with and can now
1246  * be discarded.
1247  */
1248 void ev_reader_consume(ev_reader *r, size_t n) {
1249   r->b.start += n;
1250 }
1251
1252 /** @brief Cancel a reader
1253  * @param r Reader
1254  * @return 0 on success, non-0 on error
1255  */
1256 int ev_reader_cancel(ev_reader *r) {
1257   D(("cancel reader fd %d", r->fd));
1258   return ev_fd_cancel(r->ev, ev_read, r->fd);
1259 }
1260
1261 /** @brief Temporarily disable a reader
1262  * @param r Reader
1263  * @return 0 on success, non-0 on error
1264  *
1265  * No further callbacks for this reader will be made.  Re-enable with
1266  * ev_reader_enable().
1267  */
1268 int ev_reader_disable(ev_reader *r) {
1269   D(("disable reader fd %d", r->fd));
1270   return r->eof ? 0 : ev_fd_disable(r->ev, ev_read, r->fd);
1271 }
1272
1273 /** @brief Called from ev_run() for ev_reader_incomplete() */
1274 static int reader_continuation(ev_source attribute((unused)) *ev,
1275                                const attribute((unused)) struct timeval *now,
1276                                void *u) {
1277   ev_reader *r = u;
1278
1279   D(("reader continuation callback fd %d", r->fd));
1280   if(ev_fd_enable(r->ev, ev_read, r->fd)) return -1;
1281   return r->callback(ev, r, r->fd, r->b.start, r->b.end - r->b.start, r->eof, r->u);
1282 }
1283
1284 /** @brief Arrange another callback
1285  * @param r reader
1286  * @return 0 on success, non-0 on error
1287  *
1288  * Indicates that the reader can process more input but would like to yield to
1289  * other clients of the event loop.  Input will be disabled but it will be
1290  * re-enabled on the next iteration of the event loop and the read callback
1291  * will be called again (even if no further bytes are available).
1292  */
1293 int ev_reader_incomplete(ev_reader *r) {
1294   if(ev_fd_disable(r->ev, ev_read, r->fd)) return -1;
1295   return ev_timeout(r->ev, 0, 0, reader_continuation, r);
1296 }
1297
1298 static int reader_enabled(ev_source *ev,
1299                           const attribute((unused)) struct timeval *now,
1300                           void *u) {
1301   ev_reader *r = u;
1302
1303   D(("reader enabled callback fd %d", r->fd));
1304   return r->callback(ev, r, r->fd, r->b.start, r->b.end - r->b.start, r->eof, r->u);
1305 }
1306
1307 /** @brief Re-enable reading
1308  * @param r reader
1309  * @return 0 on success, non-0 on error
1310  *
1311  * If there is unconsumed data then you get a callback next time round the
1312  * event loop even if nothing new has been read.
1313  *
1314  * The idea is in your read callback you come across a line (or whatever) that
1315  * can't be processed immediately.  So you set up processing and disable
1316  * reading with ev_reader_disable().  Later when you finish processing you
1317  * re-enable.  You'll automatically get another callback directly from the
1318  * event loop (i.e. not from inside ev_reader_enable()) so you can handle the
1319  * next line (or whatever) if the whole thing has in fact already arrived.
1320  */
1321 int ev_reader_enable(ev_reader *r) {
1322   D(("enable reader fd %d", r->fd));
1323   return ((r->eof ? 0 : ev_fd_enable(r->ev, ev_read, r->fd))
1324           || ev_timeout(r->ev, 0, 0, reader_enabled, r)) ? -1 : 0;
1325 }
1326
1327 /*
1328 Local Variables:
1329 c-basic-offset:2
1330 comment-column:40
1331 fill-column:79
1332 End:
1333 */