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