chiark / gitweb /
time/space limits for client output buffering
[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
922   ev_timeout_cancel(ev, w->timeout);
923   w->timeout = 0;
924   return w->callback(ev, w->fd, w->syntherror, w->u);
925 }
926
927 /** @brief Called when a writer's @p timebound expires */
928 static int writer_timebound_exceeded(ev_source *ev,
929                                      const struct timeval attribute((unused)) *now,
930                                      void *u) {
931   ev_writer *const w = u;
932
933   error(0, "abandoning writer %s because no writes within %ds",
934         w->what, w->timebound);
935   return w->callback(ev, w->fd, ETIMEDOUT, w->u);
936 }
937
938 /** @brief Set the time bound callback (if not set already) */
939 static void writer_set_timebound(ev_writer *w) {
940   if(w->timebound && !w->timeout) {
941     struct timeval when;
942     ev_source *const ev = w->ev;
943     
944     xgettimeofday(&when, 0);
945     when.tv_sec += w->timebound;
946     ev_timeout(ev, &w->timeout, &when, writer_timebound_exceeded, w);
947   }
948 }
949
950 /** @brief Called when a writer's file descriptor is writable */
951 static int writer_callback(ev_source *ev, int fd, void *u) {
952   ev_writer *const w = u;
953   int n;
954
955   n = write(fd, w->b.start, w->b.end - w->b.start);
956   D(("callback for writer fd %d, %ld bytes, n=%d, errno=%d",
957      fd, (long)(w->b.end - w->b.start), n, errno));
958   if(n >= 0) {
959     w->b.start += n;
960     ev_timeout_cancel(ev, w->timeout);
961     w->timeout = 0;
962     if(w->b.start == w->b.end) {
963       if(w->eof) {
964         ev_fd_cancel(ev, ev_write, fd);
965         return w->callback(ev, fd, 0, w->u);
966       } else
967         ev_fd_disable(ev, ev_write, fd);
968     } else
969       writer_set_timebound(w);
970   } else {
971     switch(errno) {
972     case EINTR:
973     case EAGAIN:
974       break;
975     default:
976       ev_fd_cancel(ev, ev_write, fd);
977       return w->callback(ev, fd, errno, w->u);
978     }
979   }
980   return 0;
981 }
982
983 /** @brief Write bytes to a writer's buffer
984  *
985  * This is the sink write callback.
986  *
987  * Calls ev_fd_enable() if necessary (i.e. if the buffer was empty but
988  * now is not).
989  */
990 static int ev_writer_write(struct sink *sk, const void *s, int n) {
991   ev_writer *w = (ev_writer *)sk;
992
993   if(!n)
994     return 0;                           /* avoid silliness */
995   buffer_space(&w->b, n);
996   if(w->b.start == w->b.end)
997     ev_fd_enable(w->ev, ev_write, w->fd);
998   memcpy(w->b.end, s, n);
999   w->b.end += n;
1000   if(w->spacebound && w->b.end - w->b.start > w->spacebound) {
1001     /* Buffer contents have exceeded the space bound.  We assume that the
1002      * remote client has gone away and TCP hasn't noticed yet, or that it's got
1003      * hopelessly stuck. */
1004     error(0, "abandoning writer %s because buffer has reached %td bytes",
1005           w->what, w->b.end - w->b.start);
1006     w->syntherror = EPIPE;
1007     ev_fd_cancel(w->ev, ev_write, w->fd);
1008     return ev_timeout(w->ev, 0, 0, writer_shutdown, w);
1009   }
1010   writer_set_timebound(w);
1011   return 0;
1012 }
1013
1014 /** @brief Create a new buffered writer
1015  * @param ev Event loop
1016  * @param fd File descriptor to write to
1017  * @param callback Called if an error occurs and when finished
1018  * @param u Passed to @p callback
1019  * @param what Text description
1020  * @return New writer or @c NULL
1021  */ 
1022 ev_writer *ev_writer_new(ev_source *ev,
1023                          int fd,
1024                          ev_error_callback *callback,
1025                          void *u,
1026                          const char *what) {
1027   ev_writer *w = xmalloc(sizeof *w);
1028
1029   D(("registering writer fd %d callback %p %p", fd, (void *)callback, u));
1030   w->s.write = ev_writer_write;
1031   w->fd = fd;
1032   w->callback = callback;
1033   w->u = u;
1034   w->ev = ev;
1035   w->timebound = 10 * 60;
1036   w->spacebound = 512 * 1024;
1037   w->what = what;
1038   if(ev_fd(ev, ev_write, fd, writer_callback, w, what))
1039     return 0;
1040   ev_fd_disable(ev, ev_write, fd);
1041   return w;
1042 }
1043
1044 /** @brief Get/set the time bound
1045  * @param w Writer
1046  * @param new_time_bound New bound or -1 for no change
1047  * @return Latest time bound
1048  *
1049  * If @p new_time_bound is negative then the current time bound is returned.
1050  * Otherwise it is set and the new value returned.
1051  *
1052  * The time bound is the number of seconds allowed between writes.  If it takes
1053  * longer than this to flush a buffer then the peer will be assumed to be dead
1054  * and an error will be synthesized.  0 means "don't care".  The default time
1055  * bound is 10 minutes.
1056  *
1057  * Note that this value does not take into account kernel buffering and
1058  * timeouts.
1059  */
1060 int ev_writer_time_bound(ev_writer *w,
1061                          int new_time_bound) {
1062   if(new_time_bound >= 0)
1063     w->timebound = new_time_bound;
1064   return w->timebound;
1065 }
1066
1067 /** @brief Get/set the space bound
1068  * @param w Writer
1069  * @param new_space_bound New bound or -1 for no change
1070  * @return Latest space bound
1071  *
1072  * If @p new_space_bound is negative then the current space bound is returned.
1073  * Otherwise it is set and the new value returned.
1074  *
1075  * The space bound is the number of bytes allowed between in the buffer.  If
1076  * the buffer exceeds this size an error will be synthesized.  0 means "don't
1077  * care".  The default space bound is 512Kbyte.
1078  *
1079  * Note that this value does not take into account kernel buffering.
1080  */
1081 int ev_writer_space_bound(ev_writer *w,
1082                           int new_space_bound) {
1083   if(new_space_bound >= 0)
1084     w->spacebound = new_space_bound;
1085   return w->spacebound;
1086 }
1087
1088 /** @brief Return the sink associated with a writer
1089  * @param w Writer
1090  * @return Pointer to sink
1091  *
1092  * Writing to the sink will arrange for those bytes to be written to the file
1093  * descriptor as and when it is writable.
1094  */
1095 struct sink *ev_writer_sink(ev_writer *w) {
1096   if(!w)
1097     fatal(0, "ev_write_sink called with null writer");
1098   return &w->s;
1099 }
1100
1101 /** @brief Close a writer
1102  * @param w Writer to close
1103  * @return 0 on success, non-0 on error
1104  *
1105  * Close a writer.  No more bytes should be written to its sink.
1106  *
1107  * When the last byte has been written the callback will be called with an
1108  * error code of 0.  It is guaranteed that this will NOT happen before
1109  * ev_writer_close() returns (although the file descriptor for the writer might
1110  * be cancelled by the time it returns).
1111  */
1112 int ev_writer_close(ev_writer *w) {
1113   D(("close writer fd %d", w->fd));
1114   w->eof = 1;
1115   if(w->b.start == w->b.end) {
1116     /* we're already finished */
1117     w->syntherror = 0;                  /* no error */
1118     ev_fd_cancel(w->ev, ev_write, w->fd);
1119     return ev_timeout(w->ev, 0, 0, writer_shutdown, w);
1120   }
1121   return 0;
1122 }
1123
1124 /** @brief Cancel a writer discarding any buffered data
1125  * @param w Writer to close
1126  * @return 0 on success, non-0 on error
1127  *
1128  * This cancels a writer immediately.  Any unwritten buffered data is discarded
1129  * and the error callback is never called.  This is appropriate to call if (for
1130  * instance) the read half of a TCP connection is known to have failed and the
1131  * writer is therefore obsolete.
1132  */
1133 int ev_writer_cancel(ev_writer *w) {
1134   ev_source *const ev = w->ev;
1135   D(("cancel writer fd %d", w->fd));
1136   ev_timeout_cancel(ev, w->timeout);
1137   w->timeout = 0;
1138   return ev_fd_cancel(w->ev, ev_write, w->fd);
1139 }
1140
1141 /** @brief Attempt to flush a writer
1142  * @param w Writer to flush
1143  * @return 0 on success, non-0 on error
1144  *
1145  * Does a speculative write of any buffered data.  Does not block if it cannot
1146  * be written.
1147  */
1148 int ev_writer_flush(ev_writer *w) {
1149   return writer_callback(w->ev, w->fd, w);
1150 }
1151
1152 /* buffered reader ************************************************************/
1153
1154 /** @brief State structure for a buffered reader */
1155 struct ev_reader {
1156   struct buffer b;
1157   int fd;
1158   ev_reader_callback *callback;
1159   ev_error_callback *error_callback;
1160   void *u;
1161   ev_source *ev;
1162   int eof;
1163 };
1164
1165 /** @brief Called when a reader's @p fd is readable */
1166 static int reader_callback(ev_source *ev, int fd, void *u) {
1167   ev_reader *r = u;
1168   int n;
1169
1170   buffer_space(&r->b, 1);
1171   n = read(fd, r->b.end, r->b.top - r->b.end);
1172   D(("read fd %d buffer %d returned %d errno %d",
1173      fd, (int)(r->b.top - r->b.end), n, errno));
1174   if(n > 0) {
1175     r->b.end += n;
1176     return r->callback(ev, r, fd, r->b.start, r->b.end - r->b.start, 0, r->u);
1177   } else if(n == 0) {
1178     r->eof = 1;
1179     ev_fd_cancel(ev, ev_read, fd);
1180     return r->callback(ev, r, fd, r->b.start, r->b.end - r->b.start, 1, r->u);
1181   } else {
1182     switch(errno) {
1183     case EINTR:
1184     case EAGAIN:
1185       break;
1186     default:
1187       ev_fd_cancel(ev, ev_read, fd);
1188       return r->error_callback(ev, fd, errno, r->u);
1189     }
1190   }
1191   return 0;
1192 }
1193
1194 /** @brief Create a new buffered reader
1195  * @param ev Event loop
1196  * @param fd File descriptor to read from
1197  * @param callback Called when new data is available
1198  * @param error_callback Called if an error occurs
1199  * @param u Passed to callbacks
1200  * @param what Text description
1201  * @return New reader or @c NULL
1202  */
1203 ev_reader *ev_reader_new(ev_source *ev,
1204                          int fd,
1205                          ev_reader_callback *callback,
1206                          ev_error_callback *error_callback,
1207                          void *u,
1208                          const char *what) {
1209   ev_reader *r = xmalloc(sizeof *r);
1210
1211   D(("registering reader fd %d callback %p %p %p",
1212      fd, (void *)callback, (void *)error_callback, u));
1213   r->fd = fd;
1214   r->callback = callback;
1215   r->error_callback = error_callback;
1216   r->u = u;
1217   r->ev = ev;
1218   if(ev_fd(ev, ev_read, fd, reader_callback, r, what))
1219     return 0;
1220   return r;
1221 }
1222
1223 void ev_reader_buffer(ev_reader *r, size_t nbytes) {
1224   buffer_space(&r->b, nbytes - (r->b.end - r->b.start));
1225 }
1226
1227 /** @brief Consume @p n bytes from the reader's buffer
1228  * @param r Reader
1229  * @param n Number of bytes to consume
1230  *
1231  * Tells the reader than the next @p n bytes have been dealt with and can now
1232  * be discarded.
1233  */
1234 void ev_reader_consume(ev_reader *r, size_t n) {
1235   r->b.start += n;
1236 }
1237
1238 /** @brief Cancel a reader
1239  * @param r Reader
1240  * @return 0 on success, non-0 on error
1241  */
1242 int ev_reader_cancel(ev_reader *r) {
1243   D(("cancel reader fd %d", r->fd));
1244   return ev_fd_cancel(r->ev, ev_read, r->fd);
1245 }
1246
1247 /** @brief Temporarily disable a reader
1248  * @param r Reader
1249  * @return 0 on success, non-0 on error
1250  *
1251  * No further callbacks for this reader will be made.  Re-enable with
1252  * ev_reader_enable().
1253  */
1254 int ev_reader_disable(ev_reader *r) {
1255   D(("disable reader fd %d", r->fd));
1256   return r->eof ? 0 : ev_fd_disable(r->ev, ev_read, r->fd);
1257 }
1258
1259 /** @brief Called from ev_run() for ev_reader_incomplete() */
1260 static int reader_continuation(ev_source attribute((unused)) *ev,
1261                                const attribute((unused)) struct timeval *now,
1262                                void *u) {
1263   ev_reader *r = u;
1264
1265   D(("reader continuation callback fd %d", r->fd));
1266   if(ev_fd_enable(r->ev, ev_read, r->fd)) return -1;
1267   return r->callback(ev, r, r->fd, r->b.start, r->b.end - r->b.start, r->eof, r->u);
1268 }
1269
1270 /** @brief Arrange another callback
1271  * @param r reader
1272  * @return 0 on success, non-0 on error
1273  *
1274  * Indicates that the reader can process more input but would like to yield to
1275  * other clients of the event loop.  Input will be disabled but it will be
1276  * re-enabled on the next iteration of the event loop and the read callback
1277  * will be called again (even if no further bytes are available).
1278  */
1279 int ev_reader_incomplete(ev_reader *r) {
1280   if(ev_fd_disable(r->ev, ev_read, r->fd)) return -1;
1281   return ev_timeout(r->ev, 0, 0, reader_continuation, r);
1282 }
1283
1284 static int reader_enabled(ev_source *ev,
1285                           const attribute((unused)) struct timeval *now,
1286                           void *u) {
1287   ev_reader *r = u;
1288
1289   D(("reader enabled callback fd %d", r->fd));
1290   return r->callback(ev, r, r->fd, r->b.start, r->b.end - r->b.start, r->eof, r->u);
1291 }
1292
1293 /** @brief Re-enable reading
1294  * @param r reader
1295  * @return 0 on success, non-0 on error
1296  *
1297  * If there is unconsumed data then you get a callback next time round the
1298  * event loop even if nothing new has been read.
1299  *
1300  * The idea is in your read callback you come across a line (or whatever) that
1301  * can't be processed immediately.  So you set up processing and disable
1302  * reading with ev_reader_disable().  Later when you finish processing you
1303  * re-enable.  You'll automatically get another callback directly from the
1304  * event loop (i.e. not from inside ev_reader_enable()) so you can handle the
1305  * next line (or whatever) if the whole thing has in fact already arrived.
1306  */
1307 int ev_reader_enable(ev_reader *r) {
1308   D(("enable reader fd %d", r->fd));
1309   return ((r->eof ? 0 : ev_fd_enable(r->ev, ev_read, r->fd))
1310           || ev_timeout(r->ev, 0, 0, reader_enabled, r)) ? -1 : 0;
1311 }
1312
1313 /*
1314 Local Variables:
1315 c-basic-offset:2
1316 comment-column:40
1317 fill-column:79
1318 End:
1319 */