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