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