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